【问题标题】:Correctly using Log4jConfigurer in Spring在 Spring 中正确使用 Log4jConfigurer
【发布时间】:2012-08-29 19:03:55
【问题描述】:

在我们的应用程序中,我们决定将 log4j 配置文件命名为自定义名称,以避免无意中从另一个 jar 加载默认文件。要配置它,我们使用org.springframework.util.Log4jConfigurer 来指定 log4j 位置。

<bean
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetClass">
        <value>org.springframework.util.Log4jConfigurer</value>
    </property>
    <property name="targetMethod">
        <value>initLogging</value>
    </property>
    <property name="arguments">
        <list>
            <value>classpath:com/kilo/custom-log4j.xml</value>
        </list>
    </property>
</bean>

这也有助于将所有配置保留在代码中,让新开发人员开始运行(而不是将其保留在一些 setenv.sh 中用于容器并单独用于测试用例)。到目前为止,我们非常高兴,直到我们发现 Spring 容器本身的一些有价值的日志记录因此被遗漏了。

[ 2012-09-05 00:16:43,188 [main] support.DefaultListableBeanFactory.registerBeanDefinition():618  INFO ]: Overriding bean definition for bean 'beanA': replacing [Generic bean: class [com.kilo.spring.context.log.ClassA]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [com/kilo/spring/context/log/spring-application-context-2.xml]] with [Generic bean: class [com.kilo.spring.context.log.ClassA]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [com/kilo/spring/context/log/spring-application-context-1.xml]]
[ 2012-09-05 00:16:43,235 [main] support.DefaultListableBeanFactory.preInstantiateSingletons():555  INFO ]: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@8453227: defining beans [org.springframework.beans.factory.config.MethodInvokingFactoryBean#0,beanB,beanA]; root of factory hierarchy

如果我通过系统属性log4j.configuration 配置名称,我可以看到日志。我想如果我们将配置作为静态块放在其中一个类中,这可能会消失 - 但在 Web 应用程序中,这样做似乎很奇怪。 我可以使用任何其他技巧吗?随意指出我在这里遵循的任何/所有不正确的范例。

提前致谢!

【问题讨论】:

    标签: java spring log4j


    【解决方案1】:

    在Tomcat中你可以在tomcats中配置这样的字符串context.xml

    <Parameter name="log4j.configuration" value="whereEver"/>
    

    另一种方式是通过 JNDI 进行配置。

    顺便说一句,阅读了这个问题Initializing Log4J with Spring?,它包含一个链接(在已接受答案的评论中)指向通过 servlet 侦听器中的 jndi 配置 log4j 的实现。

    【讨论】:

    • 我忘了说我们需要确保我们的测试用例也可以使用正确的 log4j 文件。
    • @Kilokahn:我不明白在这个答案的上下文中这是什么意思?
    • 虽然这在 web 环境中工作得非常好,但我还希望我的子模块中存在的测试用例也使用正确的自定义 log4 文件。更一般地说,如何从通过 JUnit 运行的单元测试用例配置无缝日志记录。我不希望每次都去调试配置并添加 -D log4j.configuration=bar.xml (是的,我很懒惰:))
    • @Kilokahn: 然后在你的测试中配置 log4j
    猜你喜欢
    • 2018-06-14
    • 2016-07-28
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2014-12-10
    • 2022-01-21
    相关资源
    最近更新 更多