Running Program with Apache Log4j Configuration

Q

How to run my program with Apache Log4j configuration files? I have my program using Log4j 2 API compiled. And my log4j2.xml configuration file is ready.

✍: FYIcenter.com

A

The easiest way to run your program with a Log4j 2 configuration file is:

  • Name your configuration file as log4j2.xml.
  • Place your configuration file in a folder that is included in the classpath.

Here is a run session with the HelloLog4j2.java program and log4j2.xml:

fyicenter> dir .
  1584 HelloLog4j2.class
   662 log4j2.xml

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

  Logger class: org.apache.logging.log4j.core.Logger
  15:54:32.458 [main] FATAL fyiLogger - Hello - fatal
  15:54:32.461 [main] ERROR fyiLogger - Hello - error
  15:54:32.461 [main] WARN  fyiLogger - Hello - warn
  15:54:32.461 [main] INFO  fyiLogger - Hello - info
  15:54:32.461 [main] DEBUG fyiLogger - Hello - debug

fyicenter> type HelloLog4j2.log
  15:54:32.458 [main] FATAL fyiLogger - Hello - fatal
  15:54:32.461 [main] ERROR fyiLogger - Hello - error
  15:54:32.461 [main] WARN  fyiLogger - Hello - warn
  15:54:32.461 [main] INFO  fyiLogger - Hello - info
  15:54:32.461 [main] DEBUG fyiLogger - Hello - debug

The above session shows that:

  • The first command reports that the configuration file log4j2.xml is in the (.) folder.
  • The second command reports that execution is successful with expected log messages.
  • The third command reports that the log file HelloLog4j2.log does contain expected log messages.

 

Using Log4j 1.2 Bridge with Log4j 2 API

Configuration File for Apache Log4j

Using Apache Log4j in Java Programs

⇑⇑ FAQ for Apache Log4j

2015-11-11, 2147🔥, 0💬