Thursday, May 31, 2012

Log4j using properties file.


Please follow the following program to understand log4j implementation.
Here I have used console appender to log the events.
Java File: PropertyConfiguratorDemo
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class PropertyConfiguratorDemo {

      private static final Logger logger = Logger.getLogger(PropertyConfiguratorDemo.class);

      public static void main(String[] args) {
            PropertyConfigurator.configure("log.properties");
            logger.trace("Trace Message.");//Point to Point.
            logger.debug("Debug Message.");//Method to Method.         
            logger.info("Info Message.");//Information passing and recieving.
            logger.warn("Warning Message.");//Retrying again.
            logger.error("Error Message.");//Error occured and can continue further.
            logger.fatal("Fatal Message.");//Error occured and needs to stop application.
      }
}
Properties File: log.properties
log4j.rootLogger=DEBUG, Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d %p %c --> %M - %m%n

Output:
2012-05-31 16:19:36,781 DEBUG com.lenin.log4j.PropertyConfiguratorDemo --> main - Debug Message.
2012-05-31 16:19:36,781 INFO com.lenin.log4j.PropertyConfiguratorDemo --> main - Info Message.
2012-05-31 16:19:36,781 WARN com.lenin.log4j.PropertyConfiguratorDemo --> main - Warning Message.
2012-05-31 16:19:36,781 ERROR com.lenin.log4j.PropertyConfiguratorDemo --> main - Error Message.
2012-05-31 16:19:36,781 FATAL com.lenin.log4j.PropertyConfiguratorDemo --> main - Fatal Message.


No comments:

Post a Comment