通过 DI 在 Spring 框架中正确使用 LOG4J
我正在尝试使用 Log4j 作为 Spring 框架的一部分, 据我了解,通过使用适当的豆子 系统应该映射一个可在代码中访问的单例实例 同时将日志记录深度自动映射到类
类似于
Logger log = Logger.getLogger(getClass());
中 Log4J 的正常使用,我一直在使用以下 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
最好的问候
Mark
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
Similar to the normal use of Log4J as in
Logger log = Logger.getLogger(getClass());
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>
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
Please let me know if there are any better ways to integrate Log4j and Spring
Best Regards
Mark
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对你的问题的简短回答是 log4j 不适合 DI 。
Log4jConfigurer.initLogging()
方法具有 void 返回值,因此无需注入任何内容。我们的想法是,您调用该方法来引导 log4j,然后像往常一样使用 Log4j API(使用 Logger.getLogger(getClass()) )。不过,您通常不会将 Log4jConfigurer 配置为 Spring bean,但更常见的是您会在应用程序启动期间直接从自己的代码调用它。
如果这是一个 Web 应用程序,则 Spring 会提供更适合该环境的
Log4jConfigurer
替代方案(Log4jWebConfigurer
、Log4jConfigListener
)。顺便说一句,两年前我提交了一个功能请求以允许记录器自动连接,它是最终被标记为 Spring 3.1 的修复。霍雷。
The short answer to your question is that log4j is not DI friendly.
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 (usingLogger.getLogger(getClass())
).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.If this is a webapp, then Spring provides alternatives to
Log4jConfigurer
that are better suited to that environment (Log4jWebConfigurer
,Log4jConfigListener
).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.