Hello Program with Apache Log4j

Q

How to write a simple Hello program with Apache Log4j? I need it to test out which JARs are needed to compile and run my Java applications using Apache Log4j.

✍: FYIcenter.com

A

Below is a simple Hello program, HelloLog4j2.java, that calls the Log4j 2 API:

// Copyright (c) FYIcenter.com
import org.apache.logging.log4j.*;
public class HelloLog4j2 {
  private static final Logger logger = LogManager.getLogger("fyiLogger");
  public static void main(String[] args) {
    System.out.println("Logger class: "+logger.getClass().getName());
    logger.fatal("Hello - fatal");
    logger.error("Hello - error");
    logger.warn("Hello - warn");
    logger.info("Hello - info");
    logger.debug("Hello - debug");
    logger.trace("Hello - trace");
  }
}

This sample program, HelloLog4j2.java, does the following:

  • It uses only the Log2j 2 API only.
  • It creates logger object named as "fyiLogger".
  • It prints out the class name of the logger object.
  • It logs a simple message at each of 6 logging levels: fatal, error, warn, info, debug, and trace.

 

Compiling Program with Apache Log4j

Including Apache Log4j JAR Files in Classpath

Using Apache Log4j in Java Programs

⇑⇑ FAQ for Apache Log4j

2015-11-18, 1766🔥, 0💬