Master Java Logging: Configure Logback & Log4j2 in Spring Boot
This article explains how to use SLF4J as a facade for Logback or Log4j2, shows Maven dependencies, demonstrates logback.xml and logback‑spring.xml configurations, covers Spring Boot's default logging setup, custom log levels, profile‑based settings, and how to switch to Log4j2 for higher performance.
01 Background Introduction
Log files are essential for tracing and locating issues in software systems. Common Java logging frameworks include Log4j, Log4j2, and Logback; performance tests show Logback and Log4j2 are both excellent. Both integrate with SLF4J, which acts as a facade allowing easy switching of the underlying implementation.
When using SLF4J, you do not need to choose between Log4j2 or Logback; SLF4J delegates to whichever logging framework is present on the classpath. Only one implementation should be included to avoid circular dependencies.
For a Java web project using
Slf4j+
Logback, add the following Maven dependencies:
<code><!-- Add slf4j dependency -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- Add logback dependency -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency></code>Then create a
logback.xmlin the project root and configure parameters, for example:
<code><?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<property name="CUSTOM_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{90} - %msg%n" />
<contextName>${CONTEXT_NAME}</contextName>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CUSTOM_LOG_PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
</configuration></code>Finally, use the SLF4J facade to output logs:
<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogPrintUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(LogPrintUtil.class);
public static void main(String[] args) {
LOGGER.info("info信息");
LOGGER.warn("warn信息");
LOGGER.error("error信息");
}
}</code>02 Spring Boot Logging Configuration
Spring Boot automatically includes
spring-boot-starter-logging, which uses Logback and SLF4J under the hood. The default Logback configuration file is located at
org/springframework/boot/logging/logback/defaults.xml. You can simply use SLF4J to log.
Example Spring Boot application that logs at various levels:
<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LogApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(LogApplication.class);
public static void main(String[] args) {
SpringApplication.run(LogApplication.class, args);
LOGGER.error("Hello World");
LOGGER.warn("Hello World");
LOGGER.info("Hello World");
LOGGER.debug("Hello World");
LOGGER.trace("Hello World");
}
}</code>Running the service prints logs at the default
INFOlevel. To change the level, edit
application.properties, for example:
<code>logging.level.root=trace</code>Log level hierarchy (from lowest to highest):
<code>TRACE < DEBUG < INFO < WARN < ERROR</code>2.1 Logback Custom Configuration
There are two ways to customize Logback:
Create
logback.xml, which is loaded directly by Logback.
Create
logback-spring.xml, which is first processed by Spring Boot, allowing the use of Spring profiles and other advanced features.
Typical
logback-spring.xmlplaced under
src/main/resources:
<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- Define variables -->
<property name="log.dir" value="log-demo" />
<property name="custom.log.pattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{90} - %msg%n" />
<!-- Console appender -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${custom.log.pattern}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- File appender with rolling policy -->
<appender name="APP_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.dir}/log_info.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${custom.log.pattern}</pattern>
<charset>UTF-8</charset>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.dir}/histroy/log-%d{yyyy-MM-dd}-%i.log</fileNamePattern>
<maxHistory>30</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>250MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="APP_LOG" />
</root>
</configuration></code>Spring profiles can be used to apply different configurations for development and production environments.
2.2 Log4j2 Custom Configuration
To switch to Log4j2, exclude the default logging starter and add
spring-boot-starter-log4j2:
<code><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></code>Provide a custom
log4j2.xmlsimilar to the Logback configuration, defining console and rolling file appenders, pattern layout, and size‑based triggering policies.
Because the application code uses the SLF4J facade, no code changes are required to switch between Logback and Log4j2.
03 Summary
For simple, low‑concurrency applications, Logback is sufficient and offers good compatibility. For higher performance requirements, Log4j2 provides better speed, though Logback remains more compatible with existing libraries.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
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.