Configuring Log4j2 Logging for Spring 6
Add Log4j2 Dependencies
Add the following Maven dependencies to your proejct's pom.xml to enable Log4j2 integration:
<!-- Core Log4j2 library -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.19.0</version>
</dependency>
<!-- SLF4J 2 implementation binding for Log4j2 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j2-impl</artifactId>
<version>2.19.0</version>
</dependency>
Log4j2 Configuration File
Create a log4j2.xml configuration file in your project's resource root with the following content:
<?xml version="1.0" encoding="UTF-8"?>
<!-- status: sets Log4j2 internal logging output verbosity, can be omitted
monitorInterval: automatic configuration reloading check interval in seconds, minimum allowed value is 5 -->
<configuration monitorInterval="5" status="warn">
<!-- Log level priority order (highest to lowest): OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!-- Reusable configuration properties -->
<Properties>
<!-- Log output pattern:
%d = timestamp, %t = thread name, %-5level = 5-character left-aligned level name
%c{1.} = logger name, %M = method name, %L = line number, %msg = log content, %n = new line
highlight adds ANSI color coding for better console readability -->
<property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss,SSS} %highlight{%-5level} [%t] %highlight{%c{1.}.%M(%L)}: %msg%n" />
<!-- Base directory for log file output -->
<property name="LOG_DIR" value="log" />
</Properties>
<!-- Appenders define output destinations and formatting rules -->
<!-- Common appender types: Console, File, RollingFile -->
<appenders>
<!-- Console appender: outputs logs to the system console -->
<!-- target: accepts SYSTEM_OUT or SYSTEM_ERR, most use cases default to SYSTEM_OUT -->
<console name="Console" target="SYSTEM_OUT">
<!-- Apply the preconfigured log pattern layout -->
<PatternLayout pattern="${LOG_PATTERN}"/>
<!-- Threshold filter: only output logs equal to or above the configured level -->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
</console>
</appenders>
</configuration>