How to use Log4j 2 in a Java Application? Log4j 2 Maven Example

Here’s a step-by-step tutorial on how to use Log4j 2:

Step 1: Add Log4j 2 Dependency

The first step is to add the Log4j 2 dependency to your project. You can add the dependency by adding the following code to your project’s pom.xml file if you are using Maven:


Alternatively, if you are not using Maven, you can download the Log4j 2 JAR files from the Apache Log4j website and add them to your project’s classpath.

Step 2: Create a Log4j 2 Configuration File

The next step is to create a Log4j 2 configuration file. This configuration file tells Log4j 2 where to output log messages, what log level to use, and other configuration details. The Log4j 2 configuration file can be in XML, JSON, or YAML format.

Here’s an example of a Log4j 2 configuration file in XML format:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n"/>
    <Root level="debug">
      <AppenderRef ref="Console"/>

In this example, we have configured a console appender that logs messages to the console with a specific log pattern. We have also set the root logger’s log level to debug.

Step 3: Initialize Log4j 2

Now that you have added the Log4j 2 dependency and created a configuration file, the next step is to initialize Log4j 2 in your code. You can do this by calling the LogManager.getContext() method, which returns a LoggerContext instance, and passing it the path to your Log4j 2 configuration file. Here’s an example:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;

public class MyClass {
    private static final Logger logger;

    static {
        // Get the logger context
        LoggerContext context = (LoggerContext) LogManager.getContext(false);
        // Set the configuration file path
        context.setConfigLocation(new URI("path/to/log4j2.xml"));

        // Get the logger
        logger = LogManager.getLogger(MyClass.class);

    public void doSomething() {
        // Log a message
        logger.debug("Hello, Log4j 2!");

In this example, we get the logger context, set the configuration file path, and then get the logger for the MyClass class. We can then use the logger to log messages at different levels, such as debug, info, warn, error, and fatal.

Step 4: Log Messages

Using Log4j 2 Finally, we can use the logger to log messages in our code. Here’s an example:

public void doSomething() {
    String name = "John";
    int age = 30;
    // Log a message with variables"User {} is {} years old.", name, age);

Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author