XML vs Properties conf:
Properties can be defined by a properties file or by an XML file. Log4j looks for a file named log4j.xml and then for a file named log4j.properties. Both must be placed in the src folder.
The property file is less verbose than an XML file. The XML requires the log4j.dtd to be placed in the source folder as well. The XML requires a dom4j.jar which might not be included in older Java versions.
The properties file does not support some advanced configuration options like Filters, custom ErrorHandlers and a special type of appenders, i.e. AsyncAppender. ErrorHandlers defines how errors in log4j itself are handled, for example badly configured appenders. Filters are more interesting. From the available filters, I think that the level range filter is really missing for property files.
This filter allows to define that a[n] appender should receive log messages from Level INFO to WARN. This allows to split log messages across different logfiles. One for DEBUGGING messages, another for warnings, ...
The property appender only supports a minimum level. If you set it do INFO, you will receive WARN, ERROR and FATAL messages as well.
Thread safe:
Log4j is claimed to be thread safe in official doc except for
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html
You're sharing the PatternLayout between the two appenders, which according to the above API link:
This code is known to have synchronization and other issues which are not present in org.apache.log4j.EnhancedPatternLayout. EnhancedPatternLayout should be used in preference to PatternLayout. EnhancedPatternLayout is distributed in the log4j extras companion.
So create a new PatternLayout for each appender.
For uncaught exception:
implements Thread.UncaughtExceptionHandler
For standalone spring:
<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>
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 (using Logger.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).
Log4j tips
最新推荐文章于 2024-09-09 19:49:04 发布