Switch Spring Boot from Logback to Log4j2 for Faster, Flexible Logging
This guide explains how to replace Spring Boot's default Logback with Log4j2, covering Maven dependency changes, XML/YAML configuration, Java usage examples, advanced options like environment-specific files and asynchronous logging, and common troubleshooting tips.
Spring Boot uses Logback as its default logging framework, but in high‑concurrency or asynchronous scenarios Log4j2 provides better performance and richer features. The following steps show how to switch a Spring Boot project to Log4j2.
1. Exclude Logback and add Log4j2 dependencies
Modify pom.xml to exclude spring-boot-starter-logging and include spring-boot-starter-log4j2:
<dependencies>
<!-- Exclude Spring Boot's default logging (Logback) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Add Log4j2 dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
</dependencies>2. Create a Log4j2 configuration file
Place log4j2.xml under src/main/resources. A typical configuration defines properties, appenders, and loggers:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
<Properties>
<Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} %5p [%t] %-40.40c{1.} : %m%n%ex</Property>
<Property name="LOG_PATH">logs</Property>
<Property name="LOG_FILE_NAME">app</Property>
</Properties>
<Appenders>
<!-- Console output -->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
<!-- Rolling file output -->
<RollingFile name="File" fileName="${LOG_PATH}/${LOG_FILE_NAME}.log"
filePattern="${LOG_PATH}/${LOG_FILE_NAME}-%d{yyyy-MM-dd}-%i.log">
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<DefaultRolloverStrategy max="10"/>
</RollingFile>
</Appenders>
<Loggers>
<!-- Application package logging -->
<Logger name="com.yourpackage" level="debug" additivity="false">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Logger>
<!-- Framework logging -->
<Logger name="org.springframework" level="info"/>
<Logger name="org.hibernate" level="warn"/>
<!-- Root logger -->
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>3. Use Log4j2 in Java code
Import Log4j2 classes and create a static logger. Example controller logs messages at all levels:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
private static final Logger logger = LogManager.getLogger(MyController.class);
@GetMapping("/test")
public String test() {
logger.trace("This is a TRACE message");
logger.debug("This is a DEBUG message");
logger.info("This is an INFO message");
logger.warn("This is a WARN message");
logger.error("This is an ERROR message");
return "Check the logs!";
}
}4. Advanced configuration options
4.1 Use different configurations per environment
Specify the config file in application.properties or application.yml:
logging.config=classpath:log4j2-dev.xml4.2 Asynchronous logging for higher throughput
Add the Disruptor library and change the logger definition to AsyncLogger:
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.4.4</version>
</dependency> <AsyncLogger name="com.yourpackage" level="debug" additivity="false">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</AsyncLogger>4.3 YAML or JSON configuration
Log4j2 also supports YAML. An equivalent YAML snippet looks like:
Configuration:
status: warn
monitorInterval: 30
Appenders:
Console:
name: Console
target: SYSTEM_OUT
PatternLayout:
pattern: "%d{yyyy-MM-dd HH:mm:ss.SSS} %5p [%t] %-40.40c{1.} : %m%n%ex"
Loggers:
Root:
level: info
AppenderRef:
- ref: Console5. Common troubleshooting
Log conflict: Ensure spring-boot-starter-logging is excluded.
Configuration not applied: Verify that log4j2.xml is placed at the root of resources.
Log level ineffective: Check for multiple configuration files that may override each other.
By following these steps you can seamlessly switch a Spring Boot application to Log4j2, customize log output, and improve performance and maintainability.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ray's Galactic Tech
Practice together, never alone. We cover programming languages, development tools, learning methods, and pitfall notes. We simplify complex topics, guiding you from beginner to advanced. Weekly practical content—let's grow together!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
