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
Spring Boot also supports either Log4j or Log4j 2 for logging configuration, but only if one of them is on the classpath. If you are using the starter poms for assembling dependencies that means you have to exclude Logback and then include your chosen version of Log4j instead.
xml under the src folder. Create log4J configuration file log4j. properties under the src folder. The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
Community support: Log4j 1. x is not actively maintained, whereas Log4j 2 has an active community where questions are answered, features are added and bugs are fixed. Automatically reload its configuration upon modification without losing log events while reconfiguring.
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
).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With