Tuesday, January 13, 2009

Log4j for Developers

Log4j has proven to be very simple and useful tool for logging.

Log4j is quite easy to integrate with your application. Follow these two simple steps and you are ready to use the power of logging.

1. Include commons logging api in your classes.

org.commons.logging.Log logger = org.commons.logging.LogFactory.getLog(ThisClass.class);

Now you are ready to use the logging by using following methods...

logger.debug("Logging statement");
logger.info("Logging statement");
logger.fatal("Logging statement");

2. Add the following file to your classpath: log4j.properties
log4j.logger.com.mypkg=DEBUG, LOG_NAME
log4j.appender.LOG_NAME.File=C:\\log\\file.log
log4j.appender.LOG_NAME=org.apache.log4j.DailyRollingFileAppender
log4j.appender.LOG_NAME.layout=org.apache.log4j.PatternLayout
log4j.appender.LOG_NAME.Append=true


There are some more properties that you can specify. Refer Log4j documentation available on the net.