Wednesday, November 16, 2011

Log4j - Configuration

So far we have been using log4j in its most basic configuration, which sent message to the console.

Let us now upgrade it to write to a log file, in addition to console.

To do this, create a log4j.properties in your HelloWorld project directory (i.e. in the same pace as .classpath).

Type or copy-paste the following:
 # Set root logger level to DEBUG and its only appender to Appender1 & Appender2.  
 log4j.rootLogger=DEBUG, Appender1,Appender2  
   
 # Appender1 is set to be a ConsoleAppender.  
 log4j.appender.Appender1=org.apache.log4j.ConsoleAppender  
 log4j.appender.Appender2=org.apache.log4j.RollingFileAppender  
 log4j.appender.Appender2.File=HelloWorld.log  
   
   
 # Appender1 uses PatternLayout.  
 log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout  
 log4j.appender.Appender1.layout.ConversionPattern=%p %d %C %L %n %m %n
   
 log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout  
 log4j.appender.Appender2.layout.ConversionPattern=%p %d %C %L %n %m %n


Let us understand this configuration.

We are configuring the root logger with DEBUG level - this means that all log messages will get logged.

We are attaching it to two appenders - one which writes to the console, and the other to a file. We want the log file to be named HelloWorld.log.

RollingFileAppender, by default, will limit the log file size to 10 MB. When that limit is reached, it will start a new log file. This is very important for web applications which run for months without restarts. It prevents log files from getting humongous and un-openable in editors. Note that the RollingFileAppender can be configured in various ways - the most popular one being to roll log files on a daily basis (instead of by size).


we are associating a pattern to the appenders to tell it how to format the messages.
%p --> debug level of the message
%d --> time stamp
%C --> class which generated the message
%L --> line of code which generated the message
%n --> newline
%m --> message to be logged

Update your HelloWorld.java code to load this configuration, as shown below:
 package org.confucius;  
   
 import org.apache.log4j.PropertyConfigurator;  
 import org.apache.log4j.Logger;  
   
 public class HelloWorld {  
      public static void main(String[] args) {  
     PropertyConfigurator.configure("log4j.properties");  
           Logger logger = Logger.getLogger(HelloWorld.class);            
           logger.debug("Hello World!");  
      }  
 }  
   


Now if you rebuild and run HelloWorld.jar, you will see a HelloWorld.log file created.

No comments: