You are on page 1of 2

Simple Log4j Configuration

Log4j is a simple and flexible logging framework. In this tutorial you will learn how to configure log4j for your applications. Let's get started first download the latest version of log4j ( Download ). I am using log4j version 1.2.15. Add the log4j1.2.15.jar to the classpath. Next you need to create an instance of Logger class. You can create one using the Logger.getLogger(HelloWorld.class) method. It takes one argument the fully qualified class name. Now we need to configure log4j. The simple way to do that is using BasicConfigurator. configure() method. This will log all the messages on the console. Now everything is ready you can log messages using any of the print statements of the Logger class. In the following code I use the debug() method to display the "HelloWorld!" message. 01.package com.vaannila.helloworld; 02. 03.import org.apache.log4j.BasicConfigurator; 04.import org.apache.log4j.Logger; 05. 06.public class HelloWorld { 07. 08. static final Logger logger = Logger.getLogger(HelloWorld.class); 09. 10. public static void main(String[] args) { 11. BasicConfigurator.configure(); 12. logger.debug("Hello World!"); 13. } 14.} The other methods available are info(), warn(), error() and fatal(). Each method represents a logger level namely DEBUG, INFO, WARN, ERROR and FATAL. The following example shows how to use these methods. 01.package com.vaannila.helloworld; 02. 03.import org.apache.log4j.BasicConfigurator; 04.import org.apache.log4j.Logger; 05. 06.public class HelloWorld { 07. 08. static final Logger logger = Logger.getLogger(HelloWorld.class); 09. 10. public static void main(String[] args) { 11. BasicConfigurator.configure(); 12. logger.debug("Sample debug message"); 13. logger.info("Sample info message"); 14. logger.warn("Sample warn message"); 15. logger.error("Sample error message"); 16. logger.fatal("Sample fatal message"); 17. } 18.}

Here is the output of the above code. 1.0 [main] DEBUG com.vaannila.helloworld.HelloWorld - Sample debug message 2.0 [main] INFO com.vaannila.helloworld.HelloWorld - Sample info message 3.0 [main] WARN com.vaannila.helloworld.HelloWorld - Sample warn message 4.0 [main] ERROR com.vaannila.helloworld.HelloWorld - Sample error message 5.0 [main] FATAL com.vaannila.helloworld.HelloWorld - Sample fatal message The output contains the time elapsed from the start of the program in milliseconds, the thread name, the logger level, the class name and the log message.

You might also like