How to use Log4j2 in a Maven Project

This tutorial provides a detailed explanation on how to use Log4j2 in a Maven project. Log4j 2 is a powerful logging framework for Java applications that allows you to log messages based on their severity and route them to different destinations, such as consoles or files. With Log4j 2, you can customize your logging configuration easily and manage it efficiently. In this blog post, we will show you how to use Log4j 2 in a Java application using Maven and Eclipse.

What is Maven?

Maven is a popular build automation tool for Java projects that manages project dependencies, compiles the code, and produces executable files. It also provides a standard project structure and supports plugins for various tasks, such as testing, documentation generation, and deployment.

Setting up Log4j2 in Maven Project

Setting up Maven

To use Maven, you need to download and install it on your system. You can download Maven from the Apache Maven website (https://maven.apache.org/download.cgi). Once downloaded, extract the zip file to a directory of your choice.

To verify that Maven is installed correctly, open a terminal window and run the following command:

mvn -version

This command will display the version of Maven installed on your system.

Creating a Maven Project in Eclipse

To create a Maven project in Eclipse, follow these steps:

  1. Open Eclipse and click on File > New > Project.
  2. In the New Project wizard, select Maven > Maven Project and click Next.
  3. Choose an appropriate workspace location and click Next.
  4. Select the checkbox “Create a simple project” and click Next.
  5. Enter the group ID and artifact ID for your project and click Next.
  6. Choose the archetype for your project, such as “maven-archetype-quickstart” or “maven-archetype-webapp,” and click Next.
  7. Review your project details and click Finish.

Log4j2 Maven Configuration: Adding Log4j 2 Dependency

To use Log4j 2 in your Java application, you need to add its dependency to your project’s pom.xml file. Here’s how to do it:

  1. Open the pom.xml file in Eclipse.
  2. Add the following dependency to the <dependencies> section of your pom.xml file:
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.17.0</version>
</dependency>

This will add the Log4j 2 core library to your project.

  1. Save the pom.xml file.

Creating a Log4j 2 Configuration File

To configure Log4j 2 for your Java application, you need to create a configuration file. You can create a configuration file in either XML or properties format. Here’s an example of a Log4j 2 configuration file in XML format:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d %p %c{1.} [%t] %m%n"/>
    </Console>
    <File name="File" fileName="logs/mylog.log">
      <PatternLayout pattern="%d %p %c{1.} [%t] %m%n"/>
    </File>
  </Appenders>
  <Loggers>
    <Logger name="com.example" level="debug"/>
    <Root level="info">
      <AppenderRef ref="Console"/>
      <AppenderRef ref="File"/>
    </Root>
  </Loggers>
</Configuration>

This configuration file specifies two appenders, Console and File, that output log messages to the console and

a file named “mylog.log” in a directory named “logs” respectively. It also defines two loggers, one for the “com.example” package with the debug level and another for the root logger with the info level. The root logger is configured to use both the Console and File appenders.

Save this configuration file as “log4j2.xml” in the “src/main/resources” directory of your Maven project.

Using Log4j 2 in Java Code

To use Log4j 2 in your Java code, you need to create a logger instance and use it to log messages. Here’s an example:

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

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

    public static void main(String[] args) {
        logger.info("Starting MyApp");
        // some code
        logger.debug("Debug message");
        // some more code
        logger.error("Error message");
    }
}

In this example, we import the Log4j 2 LogManager and Logger classes. We create a logger instance for the MyApp class using the getLogger() method. We use the logger instance to log messages at different severity levels, such as info, debug, and error.

Running the Application

To run the application, you can either run it from the command line using Maven or run it directly from Eclipse.

To run the application using Maven, open a terminal window, navigate to your project directory, and run the following command:

mvn clean compile exec:java

This command will compile the code and run the main() method of the MyApp class.

To run the application from Eclipse, right-click on the MyApp class and select Run As > Java Application.

Viewing the Log Output

To view the log output, you can either check the console or the log file. If you configured Log4j 2 to output log messages to the console, you should see them in the console output when you run the application.

If you configured Log4j 2 to output log messages to a file, you can find the log file in the “logs” directory of your project. Open the log file in a text editor to view its contents.

The console output for the code would be:

Log4j2 in a Maven Project

This output shows the timestamp of each log message, followed by the log level, the name of the Java class that generated the log message (in this case, “MyApp”), the name of the thread that generated the log message, and the text of the log message. The pattern specified in the PatternLayout element of the Console appender configuration is used to format the log messages.

Note that the Loggers section of the configuration file sets the logging level for the “com.example” package to “debug”, but this does not affect the output of the given code, since the logger used in the code is configured to use the level specified in the Root logger, which is “info”.

Conclusion

In this tutorial, we have shown you how to use Log4j 2 in a Java application using Maven and Eclipse. We have demonstrated how to add Log4j 2 dependency to your project, create a Log4j 2 configuration file, use Log4j 2 in your Java code, and run the application. By following these steps, you can configure and use Log4j 2 in your Java projects to manage and customize your logging configuration easily and efficiently.

Learn Using Log4j 2 with Gradle.

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