Sub topic 14
Switching the backend to Log4j2
This chapter shows how to replace Logback with Log4j2 as the logging implementation in a Spring Boot application. It assumes you know the SLF4J and Logback setup from the earlier chapters. It also assumes you can read a Maven pom.xml or Gradle build file and run mvn dependency:tree or gradle dependencies.
What changes and what stays the same
Spring Boot logging has two layers. Your code calls the SLF4J API, and a backend does the formatting, filtering, and writing. Logback is the default backend. Switching to Log4j2 replaces only the backend.
Code that uses LoggerFactory.getLogger(...), {} placeholders, and MDC keeps working without edits. The RequestIdFilter from the MDC chapter runs as written, because Log4j2's SLF4J binding maps MDC onto its own ThreadContext.
These things do change:
- The configuration file format, from
logback-spring.xmltolog4j2-spring.xml. - Logback-only properties, such as
logging.logback.rollingpolicy.*, stop having any effect. - The dependencies on the classpath.
When to switch
Stay on Logback unless you have a reason. It is the default, the Spring Boot documentation covers it most thoroughly, and every property in this tutorial works with it.
| Reason | Verdict |
|---|---|
| Your organization standardizes on Log4j2 configuration and tooling | Switch |
| You need Log4j2 asynchronous loggers for high-throughput, low-latency logging | Switch |
| You depend on a Log4j2-specific appender or layout | Switch |
| You only want JSON output or different levels | Stay. Structured logging and Actuator work on both |
Swapping the dependencies
Spring Boot's spring-boot-starter-logging brings in Logback. You exclude it and add spring-boot-starter-log4j2, which brings in log4j-core and the SLF4J binding.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>Maven applies an exclusion only to the dependency it is declared on. Every Spring Boot starter depends on spring-boot-starter, which depends on spring-boot-starter-logging. If you use other starters, such as Actuator or Data JPA, Logback comes back through them. The Spring Boot documentation excludes it from spring-boot-starter itself, so every path is covered:
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>In Gradle, one exclusion applies to all configurations:
configurations {
all {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-log4j2'
}Verify the classpath
Do not assume the swap worked. Check that Logback is gone:
mvn dependency:tree | grep -E "logback|log4j"You should see log4j-core, log4j-api, log4j-slf4j2-impl, and log4j-jul. You should see no logback-classic.
What still works through properties
Spring Boot's logging system abstraction supports Log4j2, so many properties from earlier chapters carry over unchanged:
logging.level.root=warn
logging.level.com.example.orders=debug
logging.group.orders=com.example.orders,com.example.billing
logging.level.orders=debug
logging.file.name=logs/app.log
logging.pattern.console=%d{HH:mm:ss.SSS} %-5level [%X{requestId}] %logger{36} - %msg%nLevels, groups, logging.file.name, and the Actuator loggers endpoint behave as before. The pattern above also works because %d, %-5level, %X, %logger, %msg, and %n exist in both Logback and Log4j2. Anything else in a pattern must follow Log4j2 syntax, so check conversion words you have not used before.
The rolling properties are different:
# Logback only. Ignored with Log4j2.
logging.logback.rollingpolicy.max-file-size=10MB
logging.logback.rollingpolicy.max-history=14With Log4j2, you configure rolling in the XML file.
Writing log4j2-spring.xml
Spring Boot looks for log4j2-spring.xml on the classpath, before log4j2.xml, and it also accepts .properties, .yaml, and .json variants. As with Logback, prefer the -spring name. Spring Boot then loads the file after the Spring environment exists, which enables Spring-specific extensions such as profiles. If no file is found, Spring Boot uses its own default configuration.
Put this in src/main/resources/log4j2-spring.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="LOG_PATTERN">%d{HH:mm:ss.SSS} %-5level [%X{requestId}] %logger{36} - %msg%n</Property>
</Properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
<RollingFile name="File"
fileName="logs/app.log"
filePattern="logs/app-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<DefaultRolloverStrategy max="14"/>
</RollingFile>
</Appenders>
<Loggers>
<SpringProfile name="dev">
<Logger name="com.example.orders" level="debug"/>
</SpringProfile>
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>Points to notice:
status="WARN"sets the level for Log4j2's own internal messages. Raise it toDEBUGorTRACEtemporarily when your configuration does not load.SizeBasedTriggeringPolicyis the counterpart ofmax-file-size.DefaultRolloverStrategy max="14"keeps at most 14 files per time window. It is not the same as Logback'smax-history, which counts days.<SpringProfile>replaces Logback's<springProfile>. The element name is capitalized, and it works only inlog4j2-spring.xml, not in plainlog4j2.xml.- The Root logger has no profile condition. Wrapping the only Root element in a profile would leave the application on Log4j2's default level whenever no profile matches.
To read a Spring property inside the file, use the spring lookup, for example ${spring:spring.application.name}. This also needs the -spring file name.
To use a file with a different name or location, set logging.config=classpath:my-log4j2.xml.
Asynchronous loggers
The main performance reason to adopt Log4j2 is asynchronous logging. Log4j2's asynchronous loggers hand events to a background thread through the LMAX Disruptor library. Add com.lmax:disruptor as a dependency. Then create src/main/resources/log4j2.component.properties:
log4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelectorAsynchronous logging has trade-offs. Events still in the queue can be lost if the JVM dies abruptly. The caller no longer sees appender errors immediately. Stack traces and location information such as %L cost more or are unavailable unless you enable them. Measure before adopting it.
Structured logging and security
Structured logging from Spring Boot 3.4 works with Log4j2 too. The property logging.structured.format.console=ecs needs no XML changes. If your log4j2-spring.xml defines its own appenders, Spring Boot's structured property applies only to the appenders it configures itself, so keep the defaults or set the layout in your file.
Keep log4j-core at the version Spring Boot manages. Older Log4j2 releases contained the Log4Shell vulnerability (CVE-2021-44228). Overriding the version property downward reintroduces that risk.
Checklist after switching
- Run the dependency tree check and confirm no
logback-classic. - Delete or ignore
logback-spring.xmland thelogging.logback.*properties. They no longer apply. - Start the application and confirm the console output matches your pattern.
- Trigger a rollover in a test by setting a tiny
size, and confirm the archive file name. - Call the Actuator
loggersendpoint to confirm a runtime level change takes effect.
Exercise
After switching to Log4j2, your application.properties still contains logging.logback.rollingpolicy.max-file-size=10MB, but the log file grows past 10 MB without rolling. Why, and where should the limit be configured?
Show answer
logging.logback.rollingpolicy.* properties are read only by the Logback support, so Log4j2 ignores them. Set the limit in log4j2-spring.xml with a SizeBasedTriggeringPolicy (size="10MB") inside the Policies element of a RollingFile appender, and make sure that appender is referenced from the Root or a Logger.
Exercise
You excluded spring-boot-starter-logging from spring-boot-starter-web and added spring-boot-starter-log4j2. The application still fails at startup because Logback is on the classpath. What is the likely cause and how do you confirm it?
Show answer
Another starter, such as Actuator, still pulls in spring-boot-starter-logging through its own dependency on spring-boot-starter, because a Maven exclusion applies only to the dependency it is declared on. Run mvn dependency:tree and look for logback-classic. Fix it by excluding spring-boot-starter-logging from spring-boot-starter itself (or with a Gradle configurations.all exclusion).