Home / Java Techs / Java / Getting started with Log4j2

Getting started with Log4j2

Print Friendly, PDF & Email

Log4j2 is the upgraded version of Apache Log4j with significant improvements over its predecessor and provides many of the improvements available in Logback while fixing some inherent problems occurred in Logback’s architecture such as performance improvement, hot/automatic reloading once configuration files modified, Java 8 lambda support and custom log levels. We had already discussed how to use Log4j to manage log messages in your Java program fundamentally. Thus, this post will lead you to get started with Log4j2 and then present some of these improvements in a nutshell.

Log4j 2.4 and greater requires Java 7. Versions 2.0-alpha1 to 2.3 required Java 6.

Log4j2 dependencies

To use Log4j2 in your project, you have to declare along those lines of the following snippet in your build file. Here are the instructions for Maven and Gradle based projects.

Using Log4j in Apache Maven build

To build with Apache Maven, add the dependencies listed below in pom.xml  file.

Using Log4j in Gradle build

To build with Gradle, add the dependencies listed below in build.gradle  file.

For dependency declaration in other build tools, please consult section Maven, Ivy, Gradle, and SBT Artifacts in Log4j’s official documentation.

Log4j2 configuration file

Log4j supports multiple formats for configuration files. You freely go with log4j2.{xml, json, properties}. See below an example of log4j2.xml.

If you want to tell Log4j2 with log4j2.json, you need to add the dependencies listed below in pom.xml or build.gradle.



You should leave the configuration file anywhere in the application’s classpath. The common location is src/main/java/resources as shown in the screenshot below.

An illustrated program

You might prefer a small program to demonstrate how Log4j2 works. Here you are.

Run the petite program above, you will see the output along those lines of the following screenshot.

The source code of the sample project can be found in bitbucket.

We hope you enjoy our post. Please give your comments into feedback section.


About Admin

programming all time and taking a bread for the lunch hahaha... When you are engaging your work, nobody can attract you doing another thing. Otherwise, should should move to other jobs or are not interested in your job enough.