Configuring Logging in Spring Boot: Levels, Frameworks, and Custom Settings

This article explains how to configure logging in Spring Boot, covering supported versions, log levels, available logging frameworks, default Logback setup, code usage with Lombok, customizing log levels, directing output to files, formatting patterns, and detailed Logback XML configuration.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Configuring Logging in Spring Boot: Levels, Frameworks, and Custom Settings

Preface

Logging is rarely mentioned as a separate functional requirement during the requirements phase, but its importance in any system is undeniable. This article introduces how to configure logging in Spring Boot.

Spring Boot Version

The tutorial is based on Spring Boot version 2.3.4.RELEASE.

Log Levels

Common log levels from low to high are: TRACE < DEBUG < INFO < WARN < ERROR < FATAL.

If the project sets the log level to INFO, messages with lower levels such as TRACE and DEBUG will not be displayed.

Available Logging Frameworks

The most common logging frameworks are log4j, logback, and log4j2. While log4j is familiar, it is no longer maintained and its performance lags behind logback and log4j2. logback, designed by the creator of log4j, offers more than a ten‑fold performance improvement and is the default logging framework for Spring Boot.

Spring Boot Logging Framework

Spring Boot uses logback as its default logging framework, and it is generally not recommended to replace it.

To use the default logback you would normally add the following Maven dependency, but because it is the default, you do not need to add it explicitly:

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>

The default log level is INFO. When the application starts, the console output looks like this:

The default log pattern includes timestamp (millisecond precision), log level, process ID, a separator, thread name (in brackets), logger name (usually the class name), and the log message.

How to Use Logging in Code?

Two common approaches are shown.

Traditional way – declare a logger manually:

private final Logger logger = LoggerFactory.getLogger(DemoApplicationTests.class);

Using Lombok to reduce boilerplate:

Add Lombok dependency:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

Annotate the class with @Slf4j and use the generated logger:

@Slf4j
class DemoApplicationTests {
    @Test
    public void test() {
        log.debug("Output DEBUG log....");
    }
}

How to Customize Log Levels?

The default level is INFO, but you can change it globally: logging.level.root=DEBUG Or adjust a specific package: logging.level.com.example.demo=INFO Combined configuration example:

logging.level.root=DEBUG
logging.level.com.example.demo=INFO

How to Output Logs to Files?

By default logs go to the console. To write them to files, configure one of the following properties (only one should be set): logging.file.path: directory for log files logging.file.name: file name (default spring.log)

Example – write logs to ./logs/spring.log:

logging.file.path=./logs

How to Customize Log Format?

Two patterns can be defined – one for the console and one for files:

logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n
logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n

Pattern symbols meaning:

%d{HH:mm:ss.SSS} – timestamp
%thread – thread name
%-5level – left‑aligned level (5 characters)
%logger – logger name
%msg – log message
%n – platform‑specific newline

How to Define Custom Logback Configuration?

Spring Boot loads configuration files based on the logging system. For Logback, the following file names are recognized: logback-spring.xml, logback-spring.groovy, logback.xml, logback.groovy Place the chosen file under src/main/resources. Below is a complete logback-spring.xml example:

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
    <!-- Define log directory -->
    <property name="logPath" value="logs"/>
    <!-- Define log pattern -->
    <property name="PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} %L %M - %msg%xEx%n"/>
    <contextName>logback</contextName>

    <!-- Console appender -->
    <appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>${PATTERN}</pattern>
        </layout>
    </appender>

    <!-- File appender for normal logs -->
    <appender name="fileDEBUGLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>Error</level>
            <onMatch>DENY</onMatch>
            <onMismatch>ACCEPT</onMismatch>
        </filter>
        <File>${logPath}/log_demo.log</File>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${logPath}/log_demo_%d{yyyy-MM-dd}.log</FileNamePattern>
            <maxHistory>90</maxHistory>
        </rollingPolicy>
        <encoder>
            <charset>UTF-8</charset>
            <pattern>${PATTERN}</pattern>
        </encoder>
    </appender>

    <!-- File appender for error logs -->
    <appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>Error</level>
        </filter>
        <File>${logPath}/error.log</File>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${logPath}/error_%d{yyyy-MM-dd}.log</FileNamePattern>
            <maxHistory>90</maxHistory>
        </rollingPolicy>
        <encoder>
            <charset>UTF-8</charset>
            <pattern>${PATTERN}</pattern>
        </encoder>
    </appender>

    <!-- Root logger – base level and attached appenders -->
    <root level="DEBUG">
        <appender-ref ref="consoleLog"/>
        <appender-ref ref="fileDEBUGLog"/>
        <appender-ref ref="fileErrorLog"/>
    </root>

    <!-- Package‑specific loggers – override root level -->
    <logger name="org.springframework" level="DEBUG"/>
    <logger name="org.mybatis" level="DEBUG"/>
    <logger name="java.sql.Connection" level="DEBUG"/>
    <logger name="java.sql.Statement" level="DEBUG"/>
    <logger name="java.sql.PreparedStatement" level="DEBUG"/>
    <logger name="io.lettuce.*" level="INFO"/>
    <logger name="io.netty.*" level="ERROR"/>
    <logger name="com.rabbitmq.*" level="DEBUG"/>
    <logger name="org.springframework.amqp.*" level="DEBUG"/>
    <logger name="org.springframework.scheduling.*" level="DEBUG"/>
    <logger name="com.xxx.xxx.xx" additivity="false" level="DEBUG">
        <appender-ref ref="fileDEBUGLog"/>
        <appender-ref ref="fileErrorLog"/>
    </logger>
</configuration>

If you prefer a custom file name, set the logging.config property, e.g., logging.config=classpath:logging-config.xml.

Conclusion

This article covered the selection of logging frameworks for Spring Boot, the default Logback configuration, and detailed steps to customize log levels, output destinations, and patterns through both property settings and a full Logback XML configuration.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaConfigurationloggingSpring Bootlogbacklog4j
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

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.