Backend Development 15 min read

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.

macrozheng
macrozheng
macrozheng
Master Java Logging: Configure Logback & Log4j2 in Spring Boot

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>&lt;!-- Add slf4j dependency --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;
    &lt;version&gt;1.7.25&lt;/version&gt;
&lt;/dependency&gt;

&lt;!-- Add logback dependency --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
    &lt;artifactId&gt;logback-classic&lt;/artifactId&gt;
    &lt;version&gt;1.1.7&lt;/version&gt;
&lt;/dependency&gt;</code>

Then create a

logback.xml

in the project root and configure parameters, for example:

<code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;configuration scan="true" scanPeriod="60 seconds" debug="false"&gt;
    &lt;property name="CUSTOM_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{90} - %msg%n" /&gt;
    &lt;contextName&gt;${CONTEXT_NAME}&lt;/contextName&gt;
    &lt;appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"&gt;
        &lt;encoder&gt;
            &lt;pattern&gt;${CUSTOM_LOG_PATTERN}&lt;/pattern&gt;
            &lt;charset&gt;UTF-8&lt;/charset&gt;
        &lt;/encoder&gt;
    &lt;/appender&gt;
    &lt;root level="INFO"&gt;
        &lt;appender-ref ref="CONSOLE" /&gt;
    &lt;/root&gt;
&lt;/configuration&gt;</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

INFO

level. 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.xml

placed under

src/main/resources

:

<code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;configuration&gt;
    &lt;!-- Define variables --&gt;
    &lt;property name="log.dir" value="log-demo" /&gt;
    &lt;property name="custom.log.pattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{90} - %msg%n" /&gt;

    &lt;!-- Console appender --&gt;
    &lt;appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"&gt;
        &lt;encoder&gt;
            &lt;pattern&gt;${custom.log.pattern}&lt;/pattern&gt;
            &lt;charset&gt;UTF-8&lt;/charset&gt;
        &lt;/encoder&gt;
    &lt;/appender&gt;

    &lt;!-- File appender with rolling policy --&gt;
    &lt;appender name="APP_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender"&gt;
        &lt;file&gt;${log.dir}/log_info.log&lt;/file&gt;
        &lt;encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"&gt;
            &lt;pattern&gt;${custom.log.pattern}&lt;/pattern&gt;
            &lt;charset&gt;UTF-8&lt;/charset&gt;
        &lt;/encoder&gt;
        &lt;rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"&gt;
            &lt;fileNamePattern&gt;${log.dir}/histroy/log-%d{yyyy-MM-dd}-%i.log&lt;/fileNamePattern&gt;
            &lt;maxHistory&gt;30&lt;/maxHistory&gt;
            &lt;timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"&gt;
                &lt;maxFileSize&gt;250MB&lt;/maxFileSize&gt;
            &lt;/timeBasedFileNamingAndTriggeringPolicy&gt;
        &lt;/rollingPolicy&gt;
    &lt;/appender&gt;

    &lt;root level="INFO"&gt;
        &lt;appender-ref ref="CONSOLE" /&gt;
        &lt;appender-ref ref="APP_LOG" /&gt;
    &lt;/root&gt;
&lt;/configuration&gt;</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>&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter&lt;/artifactId&gt;
    &lt;exclusions&gt;
        &lt;exclusion&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-logging&lt;/artifactId&gt;
        &lt;/exclusion&gt;
    &lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-log4j2&lt;/artifactId&gt;
&lt;/dependency&gt;</code>

Provide a custom

log4j2.xml

similar 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.

JavaloggingSpring BootLogbackSlf4jlog4j2
macrozheng
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.