Running Program with Apache Log4j

Q

How to run my program with Log4j 2.4.1? My program uses Log4j 2 API only and I want to know which JAR file is needed to run it.

✍: FYIcenter.com

A

If your program is using Log4j 2 API, you need to run the program with 2 JAR files: the Log4j 2 API JAR and the Log4j 2 Core JAR, like log4j-api-2.14.1.jar and log4j-core-2.14.1.jar.

If you are using older versions of JDK, you may need to use older releases of Log4j 2 JARs. See the JDK compatibility table below:

               Release   JDK   Date 
               -------   ---   ----------
Apache Log4j   2.14.1      8   2021-03-12
Apache Log4j   2.12.1      7   2020-07-03
Apache Log4j   2.3         6   2020-07-03

Here is a run session with the HelloLog4j2.class program provided in the last tutorial. You see an error message, because the Log4j 2 Core JAR is not provided. Log4j 2 defaults to the built-in SimpleLogger to prints logging messages.

fyicenter> java -version
java version "15" 2020-09-15

fyicenter> java -cp .:log4j-api-2.14.1.jar HelloLog4j2

ERROR StatusLogger Log4j2 could not find a logging implementation. 
  Please add log4j-core to the classpath. 
  Using SimpleLogger to log to the console...

Logger class: org.apache.logging.log4j.simple.SimpleLogger
FATAL fyiLogger Hello - fatal
ERROR fyiLogger Hello - error

Run it again with both Log4j 2 API JAR and Log4j Core JAR provided. You see that Log4j uses the core.Logger to prints logging messages.

fyicenter> javac -cp .:log4j-api-2.14.1.jar:log4j-core-2.14.1.jar \
   HelloLog4j2.java

Logger class: org.apache.logging.log4j.core.Logger
14:37:38.928 [main] FATAL fyiLogger - Hello - fatal
14:37:38.931 [main] ERROR fyiLogger - Hello - error

If you are using an older release of Log4j, you may see the "No log4j2 configuration file found". Because Log4j 2 needs a configuration file to control logging behavior.

fyicenter> java -cp .;log4j-api-2.4.1.jar:log4j-core-2.4.1.jar \
   HelloLog4j2

ERROR StatusLogger No log4j2 configuration file found. 
Using default configuration: logging only errors to the console.
16:58:00.151 [main] FATAL HelloLog4j2 - Hello - fatal
16:58:00.152 [main] ERROR HelloLog4j2 - Hello - error   

The above session shows that:

  • The first command reports that we are using JDK 15.
  • The second command reports that execution partially fails, because log4j-core-2.14.1.jar is missing. But Log4j 2 API JAR is smart to using the SimpleLogger to write log messages to the console.
  • The third command reports that execution is successful with both log4j-api-2.14.1.jar and log4j-core-2.14.1.jar. Log messages appear on the console, because no configuration is provided.

 

Configuration File for Apache Log4j

Compiling Program with Apache Log4j

Using Apache Log4j in Java Programs

⇑⇑ FAQ for Apache Log4j

2015-11-11, 2396🔥, 0💬