Saturday, June 9, 2007

Configure Log4j/ Log4j Example


Steps to configure Log4j and to run a simple application are
1. Download Log4j from http://www.apache.org/
2. Extract all the contents to a directory.
3. In the directory find the jar file log4j-X.X.XX.jar under directory \dist\lib. Make sure ur class path points to this jar file.
4. Create a file named Log4jDemo.java and put the following contents in it.

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;


public class Log4jDemo
{
static Logger logger = Logger.getLogger(Log4jDemo.class);
public static void main(String args[])
{
PropertyConfigurator.configure("log4j.properties"); // or u can use file name with path eg. D:\\Demo\\log4j.properties
logger.debug("DEBUG Message");
logger.info("INFO Message");
logger.warn("WARN Message");
logger.error("ERROR Message");
logger.fatal("FATAL Message");
}

}

5. Create a new file named log4j.properties at the same directory where u have put the Log4jDemo.class file. Put the following contents in to it.


log4j.rootLogger=DEBUG, MF ,CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.CONSOLE.layout.ConversionPattern=[%t] %C at %L %-5p %c %x - %m%n

log4j.appender.MF=org.apache.log4j.RollingFileAppender
log4j.appender.MF.File=Main.log

log4j.appender.MF.MaxFileSize=100KB
# Keep one backup file
log4j.appender.MF.MaxBackupIndex=1

log4j.appender.MF.layout=org.apache.log4j.PatternLayout
log4j.appender.MF.layout.ConversionPattern=[%t] %C at %L %-5p %F (%L) %c %x - %m%n

6.Now when u run the Log4jDemo.java u get a console ouput and also saved to a file called Main.log

No comments:

Post a Comment