Configure Log4j2 -Java in minutes

Apache Log4j2 is used for printing info, error, debug, trace logging statements in enterprise applications.

Apache Log4j2.x is an extension of Log4j1.x which has more significant features comparatively.
Since major security vulnerabilities like Log4jShell & hacking possibilities are identified in Log4j1.x, it is always recommended to use Log4j2.x.

It is pretty simple to configure Log4j2 in any Java applications .

The following versions are being used for below example to configure Log4j2.

  • Java 5 & above
  • Maven
  • Log4j Version 2.17

Create a simple Maven application in Eclipse/Intellij which has the following file structures.,

Maven Simple File Structure

Lets add the following Log4j2 dependencies in the pom.xml

Once make a build to our Maven application using

mvn clean install

The dependencies will be pulled from Maven repositories and will be added to the application.

Lets create log4j2.properties inside src/main/resources folder., to notify the Log4j2 library, and during startup will read this property log4j2.properties automatically from this location.
We can also place in a different location, and point the log4j2.properties location in the Java Code directly.

PropertyConfigurator.configure(“log4j.properties”);

log4j2.properties (src/main/resources)

Lets create a simple Java Class, to demonstrate how easily we can use the logger.

Log4j2Example.java

Since the rootLogger.level = debug is debug mode in log4j2.properties, we could see all the logger statements are displayed in the below output.

Output:

If the rootLogger level is error ,
then only the error log will be displayed, other logger statements will not be printed.

If the rootLogger level is info,
then only info and error log will be displayed, debug logger statements will not be printed.

The complete Simple Log4j2 Example Project is available in the following GitHub Location.,

https://github.com/TutorialFlow/Log4j2Example

Leave a Comment

Your email address will not be published. Required fields are marked *