Menu Search Sign up

Log4j 2 Use in Java Program

The following simple java program illustrates how to use log4j 2 to write different log messages at different levels:

import org.apache.log4j.LogManager; //not needed for log4j 1.x
import org.apache.log4j.Logger;

import java.io.*;

public class log4jExample{
  /* Get actual class name to be printed on */
  static Logger log = LogManager.getLogger(
            Log4jSample.class.getName());
  //static Logger log = Logger.getLogger(    //used in log4j 1.x
  //          Log4jSample.class.getName());

  public static void main(String[] args)
                throws IOException {
   
      log.trace("Trace Message!");
      log.debug("Debug Message!");
      log.info("Info Message!");
      log.warn("Warn Message!");
      log.error("Error Message!");
      log.fatal("Fatal Message!");
  }
}