How to Configure Log4j 2 Logging in Spring Boot?
Last Updated :
20 May, 2024
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.
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is a Neural Network?
Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read
Use Case Diagram - Unified Modeling Language (UML)
A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
9 min read