通过DI在Spring Framework中正确使用LOG4J [英] Correct usage Of LOG4J in Spring Framework Via DI

查看:121
本文介绍了通过DI在Spring Framework中正确使用LOG4J的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Log4j作为Spring Framework的一部分,
据我所知通过使用适当的bean
,系统应该映射代码中可访问的单例实例
,同时将记录深度自动映射到类

I am trying to use Log4j as part of the Spring Framework, as far as i understand through the use of a an appropriate bean the system is supposed to map a singleton instance accessible in the code while mapping the logging depth automatically to the class

类似于正常使用Log4J,如

Similar to the normal use of Log4J as in

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

我一直在使用以下Spring bean定义

i have been using the following Spring bean definition

<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使用它吗

But i am unable to map this bean to a specific member in a given class nor am i able to use it through @autowired

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

Please let me know if there are any better ways to integrate Log4j and Spring

最好的问候

标记

推荐答案

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

The short answer to your question is that log4j is not DI friendly.

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

The Log4jConfigurer.initLogging() method has a void return value, so there's nothing to inject. The idea is that you call that method, which bootstraps log4j, and then you use the Log4j API as usual (using Logger.getLogger(getClass())).

你通常不会将 Log4jConfigurer 配置为Spring bean,但更常见的是你直接从你的bean调用它在应用程序启动期间拥有自己的代码。

You generally wouldn't configure Log4jConfigurer as a Spring bean, though, but more usually you'd invoke it directly from your own code during application startup.

如果这是一个webapp,那么Spring提供了更适合 Log4jConfigurer 的替代方案到那个环境( Log4jWebConfigurer Log4jConfigListener )。

If this is a webapp, then Spring provides alternatives to Log4jConfigurer that are better suited to that environment (Log4jWebConfigurer, Log4jConfigListener).

顺便提一下,2年前我提交了一个功能请求,允许记录器自动装配,它是最后被标记为Spring 3.1的修复程序。 Horray。

Incidentally, 2 years ago I filed a feature request to allow loggers to be autowired, and it's finally been marked as fix for Spring 3.1. Horray.

这篇关于通过DI在Spring Framework中正确使用LOG4J的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆