What is log4j2 and How to Configure log4j2 with Java in Maven Project?
Last Updated :
24 Apr, 2025
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.
Key Features of Log4j2
- Performance - The asynchronous logging capabilities of Log4j 2, which are designed with efficiency in mind, can greatly enhance logging performance by shifting the logging task to a different thread. In high-throughput and latency-sensitive applications, this can be extremely useful.
- Configuration - Compared to Log4j 1.x, Log4j 2 provided a new configuration syntax and enhanced configurability. It enables configuration through properties files, XML, JSON, YAML, and programmatically using the API. The program is more adaptable to different deployment settings since the configuration may be updated dynamically without requiring a restart.
- Build-In-support - SLF4J (Simple Logging Facade for Java) and Apache Commons Logging (JCL), two logging APIs, are supported natively by Log4j 2. This implies that you can utilize your favorite logging API while still taking advantage of Log4j 2's capabilities and performance enhancements.
- Support for Concurrent Applications- Log4j 2 has been designed to operate effectively in multi-threaded settings, ensuring thread safety and effective logging even in such applications.
Configuration with Maven
1. Add Dependency
First, you must add the Log4j 2 library in your project as a dependency. You can accomplish this by manually downloading the JAR files and adding them to your classpath or by manually adding the necessary dependency to your build tool Maven.
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.x.x</version> <!-- 'x' should be changed to the most recent version number. -->
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.x.x</version> <!-- 'x' should be changed to the most recent version number. -->
</dependency>
2. Make a configuration file for Log4j 2:
Making a Log4j 2 configuration file is the next step. By default, Log4j 2 searches the classpath for a file with the name log4j2.xml or log4j2.yaml. To configure the logging behavior, you can create one of these files. To get you started, here is a simple log4j2.xml configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<!-- Define the appenders -->
<Appenders>
<!-- Console Appender -->
<Console name="ConsoleAppender" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<!-- File Appender -->
<File name="FileAppender" fileName="applogs/application_logs.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n" />
</File>
</Appenders>
<!-- Define the loggers -->
<Loggers>
<!-- Root Logger -->
<Root level="info">
<AppenderRef ref="ConsoleAppender" />
<AppenderRef ref="FileAppender" />
</Root>
<!-- Logger for specific package -->
<Logger name="com.example.myapp" level="debug">
<AppenderRef ref="FileAppender" />
</Logger>
</Loggers>
</Configuration>
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
You 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, you 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.
Conclusion
In conclusion, the logging framework Log4j2 for Java applications is strong and popular. It overcomes the shortcomings of Log4j 1.x's predecessor and offers improved parallelism, performance, and configurability. Asynchronous logging, pluggable architecture, and support for a number of logging APIs are just a few of the characteristics that make Log4j2 a popular option for developers looking to add logging functionality to their applications.
Similar Reads
How to Configure Log4j 2 Logging in Spring Boot?
Log4j 2 Logging is a powerful logging framework that allows us to handle different aspects of logging in a Java application. It enables asynchronous logging and is known for its efficiency and flexibility. In Spring Boot applications, the Log4j 2 integration provides advanced logging mechanisms nece
3 min read
How to Create a Maven Project in IntelliJ IDEA?
Maven is a powerful project management tool based on POM (project object model). It is used for project build, dependency, and documentation. It simplifies the build process like ANT. But it is too much advanced than ANT. In the short term, we can tell maven is a tool that can build and manage any J
3 min read
How to Create an Apache Kafka Project in IntelliJ using Java and Maven?
Apache Kafka allows you to decouple your data streams and systems. So the idea is that the source systems will be responsible for sending their data into Apache Kafka. Then any target systems that want to get access to this data feed this data stream will have to query and read from Apache Kafka to
3 min read
Adding JGit to the Project with Maven
Integrating the JGit with Maven not only enhances the project version control capabilities but also streamlines workflow processes by leveraging the Maven build and dependency management system. This article will guide you through the steps of adding JGit to the Maven project and enabling you to har
3 min read
How to Assert Log Messages with JUnit in Java?
In Java applications, logging is essential for monitoring application behavior, debugging issues, and tracking performance. Verifying log messages is important for ensuring correct entries during specific actions. In this article, we will demonstrate how to assert log messages in tests using JUnit.P
6 min read
Building a Java Project with Maven
Maven is one of the most popular build automation tools. It is developed using the Java programming language and is primarily used for Java-based projects. However, it has been updated to support programming languages like C#, Ruby, and more. This article will teach us how to build a Java project wi
2 min read
How to Convert a Maven Project into Library to use it as Dependency?
Converting a Maven project into a library allows us to reuse its functionality across multiple projects by including it as a dependency. This process involves correctly setting up your project, packaging it, and installing or deploying it to a Maven repository. In this article, we will learn how to
2 min read
Logger config() method in Java with Examples
The config() method of a Logger class used to Log an config message. This method is used to pass config types logs to all the registered output Handler objects. Config Level: Configuration Information may be like what CPU the application is running on, how much is the disk and memory space. There ar
3 min read
Mapping a Dynamic JSON Object Field in Jackson with Java
All REST API services are providing the resultant output either as XML or JSON pattern only as both are portable in nature and among that JSON is more popular. We can expect unknown properties in a JSON object. There are different ways available to map dynamic JSON objects into Java classes. They ar
5 min read
How to Install Apache Maven on Windows, macOS, and Linux?
Apache Maven is a comprehensive build automation tool widely used for managing and building Java projects. It simplifies the process of managing project dependencies and building projects through a standardized approach. This article provides step-by-step instructions to install Apache Maven on Wind
4 min read