What is log4j2 and How to Configure log4j2 with Java in Maven Project? (original) (raw)

Last Updated : 19 Mar, 2026

The logging framework Log4j, which is extensively used, has been replaced by Log4j 2. It is a strong and adaptable logging library for Java applications made to fill the gaps left by Log4j 1.x's restrictions and shortfalls. The Apache Software Foundation created Log4j 2, which is a component of the Apache Logging Services project.

**Steps to Configuration with Maven

Step 1. **Add Dependency

Add the required Log4j 2 libraries to your Maven project:

Java `

org.apache.logging.log4j log4j-api 2.x.x org.apache.logging.log4j log4j-core 2.x.x

`

Step 2. Make a configuration file for Log4j 2

Create a file named log4j2.xml inside:

`

**Note: Put your log4j2.xml configuration file in **src/main/resources or src/test/resources folder

**3. Set up Log4j 2 in your Java program

We must initialize Log4j 2 with the configuration file you made in your Java application. Put the following code in the main method of your program, for example:

Java `

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

public class MyAppLogger { private static final Logger logger = LogManager.getLogger(MyAppLogger.class);

public static void main(String[] args) {
    // Logic for your application goes here.
    logger.trace("1.This is a TRACE message.");
    logger.debug("2.This is a DEBUG message.");
    logger.info("3.This is an INFO message.");
    logger.warn("4.This is a WARN message.");
    logger.error("5.This is an ERROR message.");
}

}

`

**Output:

If the Java code is executed, we will see log messages on the console and a log file (application_logs.log) in the application's "applogs" directory. The messages will appear as follows:

2023-07-23 12:34:56 [main] INFO MyAppLogger - 3.This is an INFO message.

2023-07-23 12:34:56 [main] WARN MyAppLogger - 4.This is a WARN message.

2023-07-23 12:34:56 [main] ERROR MyAppLogger - 5.This is an ERROR message.

Each log entry provides the thread name, log level, logger name, and the actual log message. The messages are timestamped. When an exception is caught, its stack trace is also recorded.