====== Integrating Log Configuration in Spring ====== ===== Background ===== As many people out there, I **do** prefer to have my configuration of the log files in the same file as the rest of the configuration, in other words, in the applicationContext.xml file. If you are using [[http://commons.apache.org/logging/commons-logging-1.0.3/usersguide.html|Apache Commons Logging]] with [[http://logging.apache.org/log4j/1.2/manual.html|Log4Java]], I've discovered an easy method to get the configuration information inside the configuration of your application context file. ===== First Step: create a LoggerConfiguratorBean ===== You have to create a LoggerConfiguratorBean bean with one unique method called setConfiguration like this: package com.mypackage.util; import java.util.Properties; import org.apache.log4j.PropertyConfigurator; public class LoggerConfiguratorBean { public void setConfiguration( Properties configuration ) { PropertyConfigurator.configure( configuration ); } } As you may have guessed the ''PropertyConfigurator'' class is a class to configure programmatically //Log4j//. It only have to receive a list of properties. Mmmmm.... a list of properties. You can inject a list of properties in a bean in Spring. Let's see how to do this. ===== Step two: configure the bean in Spring ===== TRACE, LOGFILE org.apache.log4j.FileAppender c:\temp\mylog.log org.apache.log4j.PatternLayout %-d{MMM dd HH:mm:ss} %-5p %30.30c %-25.25M %m%n ===== Step three: you are ready to use the log ===== Believe it or not, you are now ready to use log. Unless you have configured lazy loading of classes or something like that (in that case you have to specify that this class have to be created and wired //yes or yes//. Here is an example of log integration: import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /* * Just a simple test of the logger */ @RunWith(SpringJUnit4ClassRunner.class ) @ContextConfiguration(locations={"TestContext.xml"}) public class LoggerTest { @Autowired private ApplicationContext ctx; //@Autowired //private static LogFactory logFactory; private static Log log = LogFactory.getLog(LoggerTest.class); @Test public void creationAndDestruction() { log.fatal( "Fatal: this is the most severe type of warning" ); log.error( "Error: sligth than fatal, it is applied for runtime errors" ); log.warn( "Warn: use of deprecated API's, poorly configured apis, etc. " ); log.info( "Info: interesting runtime events" ); log.debug( "Debug: just debug messages" ); log.trace( "Trace: more detailed information" ); System.out.println( "hello" ); } }