Wednesday, November 20, 2024
Google search engine
HomeLanguagesJavaWhat is log4j2 and How to Configure log4j2 with Java in Maven...

What is log4j2 and How to Configure log4j2 with Java in Maven Project?

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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments