【问题标题】:Correct usage Of LOG4J in Spring Framework Via DISpring Framework中通过DI正确使用LOG4J
【发布时间】:2011-01-11 10:06:34
【问题描述】:

我正在尝试使用 Log4j 作为 Spring 框架的一部分, 据我了解,通过使用适当的 bean 系统应该映射代码中可访问的单例实例 同时将日志记录深度自动映射到类

类似于在

中正常使用Log4J

Logger log = Logger.getLogger(getClass());

我一直在使用下面的 Spring bean 定义

<bean id="log4jInitialization"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetClass"
        value="org.springframework.util.Log4jConfigurer" />
    <property name="targetMethod" value="initLogging" />
    <property name="arguments">
        <list>
            <value>conf\log4j.xml</value>
        </list>
    </property>
</bean>

但我无法将此 bean 映射到给定类中的特定成员 我也无法通过@autowired 使用它

如果有更好的集成 Log4j 和 Spring 的方法,请告诉我

最好的问候

标记

【问题讨论】:

    标签: java spring log4j


    【解决方案1】:

    对您的问题的简短回答是 log4j 对 DI 不友好。

    Log4jConfigurer.initLogging() 方法有一个 void 返回值,所以没有什么可以注入的。这个想法是你调用那个引导 log4j 的方法,然后像往常一样使用 Log4j API(使用Logger.getLogger(getClass()))。

    不过,您通常不会将 Log4jConfigurer 配置为 Spring bean,但通常您会在应用程序启动期间直接从自己的代码中调用它。

    如果这是一个 web 应用程序,那么 Spring 会提供更适合该环境的 Log4jConfigurer 替代方案(Log4jWebConfigurerLog4jConfigListener)。

    顺便说一句,2 年前我提交了一个feature request 以允许自动连接记录器,它最终被标记为 Spring 3.1 的修复程序。万岁。

    【讨论】:

    • 谢谢。希望您的建议在不久的将来得到落实。顺便说一句,我看到 log5j 找到了一个自动执行“Logger.getLogger(getClass())”的系统,希望 Spring 社区找到类似但更好的方法 - Log5j 做了一些危险的事情来实现这一点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多