Initiating the logger.

This can be done by calling getLogger() static method of the Logger class.
It takes the fully qualified class name as an argument.
eg : static final Logger logger = Logger.getLogger(HelloWorld.class);

Configuring log4j

BasicConfigurator is the Simplest way to configure the log4j. This will all the message in the console.
eg : BasicConfigurator.configure()

Logger levels :

There are five main logger levels as follows.

  • DEBUG – logger.debug()
  • INFO – logger.info()
  • WARN – logger.warn()
  • ERROR – logger.error()
  • FATAL – logger.fatal()

Code example:


import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class HelloWorld {

static final Logger logger = Logger.getLogger(HelloWorld.class);

 public static void main(String[] args) {
 BasicConfigurator.configure();
 logger.debug("Sample debug message");
 logger.info("Sample info message");
 logger.warn("Sample warn message");
 logger.error("Sample error message");
 logger.fatal("Sample fatal message");
 }
}

output :
0 [main] DEBUG log4j.simple.HelloWorld – Sample debug message
1 [main] INFO log4j.simple.HelloWorld – Sample info message
2 [main] WARN log4j.simple.HelloWorld – Sample warn message
2 [main] ERROR log4j.simple.HelloWorld – Sample error message
2 [main] FATAL log4j.simple.HelloWorld – Sample fatal message

Advertisements