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 necessary for debugging and monitoring application behavior.

Log4j 2 can be configured using a configuration file like XML where we can define loggers, appenders, and layouts. Here is a summary of each aspect.

  • Loggers: It can be used to capture the logging information.
  • Appenders: It can be used to publish the logging information to various destinations like files, consoles, etc.
  • Layouts: Define the format in which the logs are written of the Spring application.

Implementation to Configure Log4j 2 Logging in Spring Boot

Below are the steps to configure Log4j 2 Logging in the Spring Boot application.

Step 1:

Create a new Spring Boot project using Spring Initializr. When creating the project, include the following dependencies:

  • Spring Web
  • Spring Devtools
  • Lombok

External dependencies:

 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
<version>3.2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>


Once we create the project, the file structure looks like the image below.



Step 2: Add the Log4j 2 Configuration File

We can create the log4j2.xml file in the src/main/resources directory and put the below code.

XML
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="log-path">logs</Property>
    </Properties>
    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <RollingFile name="FileAppender" fileName="${log-path}/app.log"
                     filePattern="${log-path}/app-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="ConsoleAppender"/>
            <AppenderRef ref="FileAppender"/>
        </Root>
    </Loggers>
</Configuration>

This configuration directs the INFO level logs to the both the console and the file. Files can rotate based on the time or when they reached to 10MB.


Step 3: Implement the Logging in the Spring Application

Create the simple REST controller in the Spring Boot application to demonstrate the logging into the project. Go to src > org.example.springlogging > LoggingController and put the below code.

Java
package org.example.springlogging;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@RestController
public class LoggingController {

    private static final Logger logger = LogManager.getLogger(LoggingController.class);

    @GetMapping("/log")
    public String logExample() {
        logger.info("Info level log example");
        logger.debug("Debug level log example");
        logger.error("Error level log example", new Exception("Example exception"));
        return "Logging has been demonstrated. Check the console and the log file!";
    }
}


Step 4: Open the main class(no need to changes in main class).

Go to src > org.example.springlogging > SpringLoggingApplication and put the below code.

Java
package org.example.springlogging;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringLoggingApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringLoggingApplication.class, args);
    }

}


Step 5: Run the Application

Once we run the application, then the project will run at port 8080.


API Testing:

GET http://localhost:8080/log

Output:

After testing in Postman, the response will be like below:


Once we run the /log endpoints, we can check the logs directory to see the log files. The log files should adhere to the defined format and rotate according to the specified policy.


By the following these steps, we can effectively integrate the Log4j 2 into the Spring Boot application and it can enhancing the logging capabilities.



Contact Us