SoFunction
Updated on 2025-05-13

Spring Boot Integration Logback Ultimate Guide to From Basic to Advanced Configuration

1. Introduction to Logback and the basics of integration of Spring Boot

1.1 What is Logback?

Logback is a reliable, universal and fast Java logging framework, designed by the founder of Log4j as the successor to Log4j. It consists of three modules:

  • logback-core: Basic module
  • logback-classic: Implemented the SLF4J API
  • logback-access: Integrated with Servlet container to provide HTTP access logging function

Why choose Logback?

  • Performance is higher than Log4j
  • Rich documentation
  • Automatically reload configuration files
  • Automatically compress log files
  • More flexible filtering
  • Richer log formats

1.2 Spring Boot default logging framework

Spring Boot uses Logback as the log framework by default, when you usespring-boot-starterorspring-boot-starter-webLogback dependencies have been automatically introduced.

<!-- existSpring BootIn the project,You don't need to add explicitlyLogbackrely -->
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

1.3 Basic log usage examples

import org.;
import org.;
@RestController
public class DemoController {
    // Get the Logger instance, usually taking the current class as a parameter    private static final Logger logger = ();
    @GetMapping("/demo")
    public String demo() {
        ("This is a TRACE level message");
        ("This is a DEBUG level message");
        ("This is an INFO level message");
        ("This is a WARN level message");
        ("This is an ERROR level message");
        return "Check your console or log file!";
    }
}

2. Detailed explanation of Logback configuration file

2.1 Configuration file loading order

Spring Boot will look for Logback configuration files in the following order:

  • (Recommended)
  • If none of the above exists, use the default configuration

Why is it recommended to use?

  • You can use Spring Boot-specific<springProperty>Label
  • Supports Spring Profile-specific configurations

2.2 Basic configuration file structure

A complete Logback configuration file usually contains the following parts:

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;configuration&gt;
    &lt;!-- Attribute definition --&gt;
    &lt;property name="LOG_HOME" value="./logs" /&gt;
    &lt;!-- definitionappender --&gt;
    &lt;appender name="CONSOLE" class=""&gt;
        &lt;!-- encoderdefinition日志输出格式 --&gt;
        &lt;encoder&gt;
            &lt;pattern&gt;%d{yyyy-MM-dd HH:mm:} [%thread] %-5level %logger{36} - %msg%n&lt;/pattern&gt;
        &lt;/encoder&gt;
    &lt;/appender&gt;
    &lt;!-- definitionlogger --&gt;
    &lt;logger name="" level="DEBUG" /&gt;
    &lt;!-- rootloggerConfiguration --&gt;
    &lt;root level="INFO"&gt;
        &lt;appender-ref ref="CONSOLE" /&gt;
    &lt;/root&gt;
&lt;/configuration&gt;

3. In-depth analysis of core components

3.1 <configuration> element

<configuration>It is the root element of the Logback configuration file and supports the following important properties:

Attribute name type default value describe
scan boolean false Whether to monitor configuration file changes
scanPeriod Time interval 1 minute Check the time interval for configuration file changes
debug boolean false Whether to print Logback internal debugging information
packagingData boolean false Whether to include caller information (impact performance)

Example:

&lt;configuration scan="true" scanPeriod="30 seconds" debug="false"&gt;
    &lt;!-- Configuration content --&gt;
&lt;/configuration&gt;

Best Practices:

  • The development environment can be enabledscanTo dynamically adjust the configuration
  • The production environment should be closedscananddebugTo avoid performance overhead
  • Turn on only when diagnosing a problempackagingData

3.2 <property> element

Used to define variables, reusable in configuration files:

property:

  • name: Variable name (required)
  • value: Variable value
  • file: Loading properties from external files
  • resource: Loading properties from classpath resource
  • scope: Scope ("local" or "context")

Example:

&lt;!-- Direct definition --&gt;
&lt;property name="LOG_HOME" value="/var/logs/myapp" /&gt;
&lt;!-- Get from system environment variable --&gt;
&lt;property name="LOG_HOME" value="${LOG_DIR:-./logs}" /&gt;
&lt;!-- Load from external file --&gt;
&lt;property file="conf/" /&gt;
&lt;!-- existSpring BootUsed in --&gt;
&lt;springProperty scope="context" name="appName" source="" /&gt;

Variable reference method: ${variable name}

Scope description:

  • local: Only valid in the current configuration file
  • context: works throughout LoggerContext

3.3 <timestamp> Element

Used to define timestamp variables:

property:

  • key: Variable name
  • datePattern: Date format (follow Java SimpleDateFormat)
  • timeReference: Time reference point ("contextBirth" or current time)

Example:

<timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss" />
<property name="LOG_FILE" value="${LOG_HOME}/log-${bySecond}.log" />

3.4 <appender> element

Appender is responsible for defining the log output destination and is one of the most core components of Logback.

3.4.1 Appender general structure

&lt;appender name="UNIQUE_NAME" class="APPENDER_CLASS"&gt;
    &lt;!-- Filter configuration --&gt;
    &lt;filter class="" /&gt;
    &lt;!-- layout/Encoder configuration --&gt;
    &lt;encoder&gt;
        &lt;pattern&gt;%d{yyyy-MM-dd HH:mm:ss} %msg%n&lt;/pattern&gt;
    &lt;/encoder&gt;
    &lt;!-- Other unique configurations --&gt;
&lt;/appender&gt;

3.4.2 ConsoleAppender

Output logs to console (or)

Special attributes:

  • target: Output target ("" or ""), default to
  • withJansi: Whether to enable ANSI color support (requires jansi library)

Example:

<appender name="STDOUT" class="">
    <target></target>
    <encoder>
        <pattern>%d{HH:mm:} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

3.4.3 FileAppender

Output logs to a single file

Special attributes:

  • file: Log file path
  • append: Whether to append to the end of the file (default is true)
  • prudent: Whether it is safe mode (used when multiple processes write to the same file)

Example:

<appender name="FILE" class="">
    <file>${LOG_HOME}/</file>
    <append>true</append>
    <encoder>
        <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

3.4.4 RollingFileAppender

Enhanced FileAppender that supports log file scrolling, must be configuredrollingPolicy

Special attributes:

  • file: Current active log file path
  • rollingPolicy: Scrolling policy configuration
  • triggeringPolicy: Trigger policy configuration

Example:

<appender name="ROLLING_FILE" class="">
    <file>${LOG_HOME}/</file>
    <rollingPolicy class="">
        <fileNamePattern>${LOG_HOME}/myapp.%d{yyyy-MM-dd}.log</fileNamePattern>
        <maxHistory>30</maxHistory>
    </rollingPolicy>
    <encoder>
        <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

3.4.5 Detailed explanation of the scrolling strategy

Logback provides a variety of scrolling strategies:

TimeBasedRollingPolicyTime-based rolling strategy

property illustrate
fileNamePattern Scrolling file naming mode (must include %d)
maxHistory Maximum number of historical log files retained
totalSizeCap Total size limit for all log files
cleanHistoryOnStart Whether to clean up historical files at startup (default false)

SizeAndTimeBasedRollingPolicy
A scrolling strategy combining time and size

property illustrate
fileNamePattern Must include %d and %i
maxFileSize Maximum size of a single file
maxHistory Maximum number of historical log files retained
totalSizeCap Total size limit for all log files

FixedWindowRollingPolicy
Fixed window scrolling strategy

property illustrate
minIndex Minimum index of window
maxIndex The maximum index of the window
fileNamePattern Must include %i

3.4.6 Other Appender types

Appender type Class Name use
SMTPAppender Send error logs by email
DBAppender Store logs to database
SocketAppender Send logs via network socket
SyslogAppender Send logs to syslog server

3.5 <encoder> Element

Encoder is responsible for converting log events into byte arrays and writing to the output stream.

3.5.1 PatternLayoutEncoder

The most commonly used Encoder implementation supports rich pattern expressions:

<encoder class="">
    <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
    <outputPatternAsHeader>false</outputPatternAsHeader>
    <charset>UTF-8</charset>
</encoder>

Commonly used converters:

Converter illustrate
%d Date and time
%thread Thread name
%level Log Level
%logger Logger Name
%msg Log messages
%n Line breaks
%caller Caller information
%mdc MDC content
%ex Exception stack
%marker Log tags

Date format:
%d{format}, the format follows Java SimpleDateFormat:

  • %d{yyyy-MM-dd HH:mm:}
  • %d{ISO8601}
  • %d{ABSOLUTE}

Logger name abbreviation:
%logger{length},like%logger{36}Indicates that the maximum display of 36 characters

3.5.2 LayoutWrappingEncoder

Wrapping the Encoder of other Layout implementations:

<encoder class="">
    <layout class="">
        <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </layout>
</encoder>

3.6 <filter> element

Filter is used to filter log events and can be configured on Appender or Logger.

3.6.1 LevelFilter

Precisely match specific levels:

&lt;filter class=""&gt;
    &lt;level&gt;ERROR&lt;/level&gt;
    &lt;onMatch&gt;ACCEPT&lt;/onMatch&gt;  &lt;!-- Actions when matching --&gt;
    &lt;onMismatch&gt;DENY&lt;/onMismatch&gt;  &lt;!-- 不Actions when matching --&gt;
&lt;/filter&gt;

Action Type:

  • ACCEPT: Accept log events
  • DENY: Log rejection event
  • NEUTRAL: Neutral, determined by subsequent filters

3.6.2 ThresholdFilter

Threshold filtering, accepts logs at >= specified level:

<filter class="">
    <level>WARN</level>
</filter>

3.6.3 EvaluatorFilter

Filter using Groovy expressions:

<filter class="">
    <evaluator class="">
        <expression>
            () >= () && 
            ().contains("important")
        </expression>
    </evaluator>
    <onMatch>ACCEPT</onMatch>
    <onMismatch>DENY</onMismatch>
</filter>

3.6.4 Custom Filter

accomplishinterface:

public class SampleFilter extends Filter<ILoggingEvent> {
    @Override
    public FilterReply decide(ILoggingEvent event) {
        if (().contains("special")) {
            return ;
        }
        return ;
    }
}

Configuration:

<filter class="" />

3.7 <logger> and <root> elements

3.7.1 <logger>

Configure log behavior for a specific logger:

property:

  • name: Logger name (usually package or class name)
  • level: Log level
  • additivity: Whether to pass logs upwards (default is true)

Example:

&lt;!-- Configure log levels for specific packages --&gt;
&lt;logger name="" level="DEBUG" /&gt;
&lt;!-- Configure log levels for specific classes and disable themadditivity --&gt;
&lt;logger name="" level="TRACE" additivity="false"&gt;
    &lt;appender-ref ref="SPECIAL_APPENDER" /&gt;
&lt;/logger&gt;

3.7.2 <root>

Configure the root logger, and all loggers are ultimately inherited from the Root Logger:

property:

level: Log level of root logger

Example:

<root level="INFO">
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="FILE" />
</root>

Logger inheritance rules:

  • If no specific logger is configured, the level of the most recent ancestor logger is inherited
  • If no logger is configured, use the level of root logger
  • If the logger is configured but no level is specified, the level of the most recent ancestor logger is inherited

3.8 <turboFilter> Element

TurboFilter is a global filter that is executed before all Loggers:

<turboFilter class="">
    <Marker>important</Marker>
    <OnMatch>ACCEPT</OnMatch>
    <OnMismatch>NEUTRAL</OnMismatch>
</turboFilter>

Commonly used TurboFilter:

  • MDCFilter: Filter based on MDC value
  • DynamicThresholdFilter: Dynamic threshold filtering
  • LoggerFilter: Filter based on Logger name

4. Advanced configuration and usage skills

4.1 Detailed explanation of log level

Logback supports the following log levels (from low to high):

  • TRACE
  • DEBUG
  • INFO
  • WARN
  • ERROR

Log-level inheritance rules:

  • If no specific logger is configured, the level of the most recent ancestor logger is inherited
  • If no logger is configured, use the level of root logger

4.2 Using Spring Boot Properties

existYou can use Spring Boot properties:

<springProperty scope="context" name="appName" source="" defaultValue="myApp"/>
<property name="LOG_HOME" value="./logs/${appName}" />

4.3 Profile-based configuration

Different logging policies can be configured for different Spring Profiles:

<springProfile name="dev">
    <logger name="" level="DEBUG" />
</springProfile>
<springProfile name="prod">
    <logger name="" level="INFO" />
    <root level="WARN">
        <appender-ref ref="FILE" />
    </root>
</springProfile>

4.4 Log file scrolling strategy

TimeBasedRollingPolicy: Time-based rolling strategy

<rollingPolicy class="">
    <fileNamePattern>${LOG_HOME}/application.%d{yyyy-MM-dd}.log</fileNamePattern>
    <maxHistory>30</maxHistory>
</rollingPolicy>

SizeAndTimeBasedRollingPolicy: Time and size based scrolling strategy

<rollingPolicy class="">
    <fileNamePattern>${LOG_HOME}/application.%d{yyyy-MM-dd}.%</fileNamePattern>
    <maxFileSize>10MB</maxFileSize>
    <maxHistory>30</maxHistory>
    <totalSizeCap>1GB</totalSizeCap>
</rollingPolicy>

4.5 Log Filtering

LevelFilter: Filter by level

&lt;appender name="ERROR_FILE" class=""&gt;
    &lt;filter class=""&gt;
        &lt;level&gt;ERROR&lt;/level&gt;
        &lt;onMatch&gt;ACCEPT&lt;/onMatch&gt;
        &lt;onMismatch&gt;DENY&lt;/onMismatch&gt;
    &lt;/filter&gt;
    &lt;!-- Other configurations --&gt;
&lt;/appender&gt;

ThresholdFilter: Threshold filtering

&lt;appender name="WARN_FILE" class=""&gt;
    &lt;filter class=""&gt;
        &lt;level&gt;WARN&lt;/level&gt;
    &lt;/filter&gt;
    &lt;!-- Other configurations --&gt;
&lt;/appender&gt;

4.6 Asynchronous logging

Use AsyncAppender to improve log performance:

<appender name="ASYNC_FILE" class="">
    <queueSize>512</queueSize>
    <discardingThreshold>0</discardingThreshold>
    <includeCallerData>false</includeCallerData>
    <appender-ref ref="FILE" />
</appender>

Parameter description:

  • queueSize: Queue size (default 256)
  • discardingThreshold: When the remaining queue capacity is less than this value, discard the logs at TRACE, DEBUG, and INFO levels (20% of the default queue size)
  • includeCallerData: Whether to include caller data (impact performance)

Best Practices:

  • Recommended queue size for production environment is set to 512-2048
  • Close includeCallerData unless necessary
  • For key logs, set discardingThreshold=0 to ensure that no discarding

4.7 MDC (Mapped Diagnostic Context)

MDC can be used to add context information to the log:

import org.;
public class UserService {
    private static final Logger logger = ();
    public void login(String userId) {
        ("userId", userId);
        ("User logged in");
        ("userId");
    }
}

Use in configuration files:

<pattern>%d{yyyy-MM-dd HH:mm:} [%thread] [%X{userId}] %-5level %logger{36} - %msg%n</pattern>

Advanced usage:

&lt;!-- Only whenMDCExist inuserIdShown only when --&gt;
&lt;pattern&gt;%d{yyyy-MM-dd} [%thread] %mdc{userId:-} %-5level %logger{36} - %msg%n&lt;/pattern&gt;

4.8 Conditional configuration

use<if>Conditional statements (requires Janino library):

<if condition='property("env").equals("prod")'>
    <then>
        <root level="WARN">
            <appender-ref ref="FILE" />
        </root>
    </then>
    <else>
        <root level="DEBUG">
            <appender-ref ref="CONSOLE" />
        </root>
    </else>
</if>

V. Best Practices and Frequently Asked Questions

5.1 Logging Best Practices

Rational use of log levels

  • TRACE: Very detailed system operation information, usually only used during development
  • DEBUG: Debugging information, helps diagnose problems
  • INFO: Important business processing information
  • WARN: Potential problems, but the system still works
  • ERROR: Error event, but the system can continue to run

Log content specification

  • Record meaningful business information
  • Avoid recording sensitive information (passwords, credit card numbers, etc.)
  • The exception should be logged on the stack (using ("message", e))

Performance considerations

  • Avoid DEBUG level in production environment
  • Use caller data with caution (%C, %M, %F, %L, etc.)
  • Consider using asynchronous logs

5.2 Frequently Asked Questions

Problem 1: The log file does not scroll

  • examinefileNamePatternDate mode in
  • Ensure that the log volume meets the rolling conditions
  • Check file permissions

Solution

&lt;!-- Make sure the trigger policy is configured --&gt;
&lt;rollingPolicy class=""&gt;
    &lt;fileNamePattern&gt;logs/app-%d{yyyy-MM-dd}.%&lt;/fileNamePattern&gt;
    &lt;maxFileSize&gt;50MB&lt;/maxFileSize&gt;  &lt;!-- Must be configured --&gt;
    &lt;maxHistory&gt;30&lt;/maxHistory&gt;
&lt;/rollingPolicy&gt;

Question 2: The log file is too large

  • AdjustmentmaxFileSizeandmaxHistory
  • usetotalSizeCapLimit total size
  • Consider separating log files by level

Question 3: Incomplete log output

  • Check the level settings of logger
  • Check if there are filters that have logs filtered out
  • Check if there are conflicts between multiple configuration files

Question 4: Log output garbled

Solution

&lt;encoder&gt;
    &lt;pattern&gt;%msg%n&lt;/pattern&gt;
    &lt;charset&gt;UTF-8&lt;/charset&gt;  &lt;!-- Identify the character set --&gt;
&lt;/encoder&gt;

6. Complete configuration example

6.1 Development environment configuration ()

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!-- LogbackRoot tag of configuration file,All configuration elements must be included in this tag --&gt;
&lt;configuration&gt;
    &lt;!-- Attribute definition section,pass &lt;property&gt; Tag definition reusable properties,Convenient to reference in configuration files --&gt;
    &lt;!-- Define the home directory for log file storage --&gt;
    &lt;property name="LOG_HOME" value="/var/logs/myapp" /&gt;
    &lt;!-- Define the format pattern of log output,Included date and time、Thread name、Log Level、Logger name and log message --&gt;
    &lt;property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:} [%thread] %-5level %logger{36} - %msg%n" /&gt;
    &lt;!-- ConsoleAppenderConfiguration,用于Will日志输出到Console --&gt;
    &lt;appender name="CONSOLE" class=""&gt;
        &lt;!-- 编码器Configuration,Convert log events to strings of specified format --&gt;
        &lt;encoder&gt;
            &lt;!-- Use the log format pattern defined earlier --&gt;
            &lt;pattern&gt;${LOG_PATTERN}&lt;/pattern&gt;
        &lt;/encoder&gt;
        &lt;!-- 过滤器Configuration,Only allowed指定级别及以上的日志pass --&gt;
        &lt;filter class=""&gt;
            &lt;!-- Set the filtering level to WARN,That is, only output WARN Logs at or above levels --&gt;
            &lt;level&gt;WARN&lt;/level&gt;
        &lt;/filter&gt;
    &lt;/appender&gt;
    &lt;!-- Main fileAppenderConfiguration,Used to output logs to files,And support rolling policy --&gt;
    &lt;appender name="FILE" class=""&gt;
        &lt;!-- Specify the path to the log file,Use the log home directory defined earlier --&gt;
        &lt;file&gt;${LOG_HOME}/&lt;/file&gt;
        &lt;!-- 编码器Configuration,Convert log events to strings of specified format --&gt;
        &lt;encoder&gt;
            &lt;!-- Use the log format pattern defined earlier --&gt;
            &lt;pattern&gt;${LOG_PATTERN}&lt;/pattern&gt;
        &lt;/encoder&gt;
        &lt;!-- 滚动策略Configuration,Scroll based on file size and time --&gt;
        &lt;rollingPolicy class=""&gt;
            &lt;!-- Scrolled file naming mode,Include date and serial number --&gt;
            &lt;fileNamePattern&gt;${LOG_HOME}/application.%d{yyyy-MM-dd}.%&lt;/fileNamePattern&gt;
            &lt;!-- Maximum size of a single log file,More than this size will scroll --&gt;
            &lt;maxFileSize&gt;50MB&lt;/maxFileSize&gt;
            &lt;!-- Maximum number of days of historical log files retained --&gt;
            &lt;maxHistory&gt;30&lt;/maxHistory&gt;
            &lt;!-- The maximum total size of all log files --&gt;
            &lt;totalSizeCap&gt;5GB&lt;/totalSizeCap&gt;
        &lt;/rollingPolicy&gt;
    &lt;/appender&gt;
    &lt;!-- Error logAppenderConfiguration,Specially used for recording ERROR Level log --&gt;
    &lt;appender name="ERROR_FILE" class=""&gt;
        &lt;!-- 指定Error log文件的路径,Use the log home directory defined earlier --&gt;
        &lt;file&gt;${LOG_HOME}/&lt;/file&gt;
        &lt;!-- 编码器Configuration,Convert log events to strings of specified format --&gt;
        &lt;encoder&gt;
            &lt;!-- Use the log format pattern defined earlier --&gt;
            &lt;pattern&gt;${LOG_PATTERN}&lt;/pattern&gt;
        &lt;/encoder&gt;
        &lt;!-- 过滤器Configuration,Only allowed ERROR Level logpass --&gt;
        &lt;filter class=""&gt;
            &lt;!-- Set the filtering level to ERROR --&gt;
            &lt;level&gt;ERROR&lt;/level&gt;
            &lt;!-- 当Log Level匹配时,允许pass --&gt;
            &lt;onMatch&gt;ACCEPT&lt;/onMatch&gt;
            &lt;!-- 当Log Level不匹配时,拒绝pass --&gt;
            &lt;onMismatch&gt;DENY&lt;/onMismatch&gt;
        &lt;/filter&gt;
        &lt;!-- 滚动策略Configuration,Roll based on time --&gt;
        &lt;rollingPolicy class=""&gt;
            &lt;!-- Scrolled file naming mode,Included dates --&gt;
            &lt;fileNamePattern&gt;${LOG_HOME}/error.%d{yyyy-MM-dd}.log&lt;/fileNamePattern&gt;
            &lt;!-- 保留的历史Error log文件的最大天数 --&gt;
            &lt;maxHistory&gt;90&lt;/maxHistory&gt;
        &lt;/rollingPolicy&gt;
    &lt;/appender&gt;
    &lt;!-- asynchronousAppenderConfiguration,用于asynchronous处理日志,Improve performance --&gt;
    &lt;appender name="ASYNC_FILE" class=""&gt;
        &lt;!-- asynchronous队列的大小,That is, the maximum number of log events that can be cached --&gt;
        &lt;queueSize&gt;1024&lt;/queueSize&gt;
        &lt;!-- Discard threshold,When the remaining space of the queue is less than this value,Some log events will be discarded,Set as 0 Indicates not to discard --&gt;
        &lt;discardingThreshold&gt;0&lt;/discardingThreshold&gt;
        &lt;!-- 引用前面定义的Main fileAppender,Willasynchronous处理后的日志输出到该 Appender --&gt;
        &lt;appender-ref ref="FILE" /&gt;
    &lt;/appender&gt;
    &lt;!-- LoggerConfiguration部分,用于指定不同包或kind的Log Level和输出目的地 --&gt;
    &lt;!-- against  Bag and its sub-packages,设置Log Level为 INFO --&gt;
    &lt;logger name="" level="INFO" /&gt;
    &lt;!-- against  Bag and its sub-packages,设置Log Level为 WARN --&gt;
    &lt;logger name="" level="WARN" /&gt;
    &lt;!-- against  kind,设置Log Level为 DEBUG,And turn off the log addition --&gt;
    &lt;logger name="" level="DEBUG" additivity="false"&gt;
        &lt;!-- 只Will该kind的日志输出到Main fileAppender --&gt;
        &lt;appender-ref ref="FILE" /&gt;
    &lt;/logger&gt;
    &lt;!-- Root LoggerConfiguration,It's all Logger The father Logger,设置全局的Log Level和输出目的地 --&gt;
    &lt;root level="INFO"&gt;
        &lt;!-- Will日志输出到ConsoleAppender --&gt;
        &lt;appender-ref ref="CONSOLE" /&gt;
        &lt;!-- Will日志asynchronous输出到Main fileAppender --&gt;
        &lt;appender-ref ref="ASYNC_FILE" /&gt;
        &lt;!-- Will ERROR Level log输出到Error logAppender --&gt;
        &lt;appender-ref ref="ERROR_FILE" /&gt;
    &lt;/root&gt;
&lt;/configuration&gt;

6.2 Production environment configuration ()

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!-- Logback Root tag of configuration file,All configuration items must be included --&gt;
&lt;configuration&gt;
    &lt;!-- use springProperty Tags from Spring Get attribute values ​​in context。
         scope="context" Indicates from Spring Context Getting Attributes,
         name="appName" Define attribute name,
         source="" Specify from Spring Get the name in the configuration  attribute value,
         defaultValue="myApp" If no attribute value is obtained,则use默认值 myApp --&gt;
    &lt;springProperty scope="context" name="appName" source="" defaultValue="myApp"/&gt;
    &lt;!-- Define the home directory properties of the log store,The path is /var/log/ Add the name of the application obtained earlier --&gt;
    &lt;property name="LOG_HOME" value="/var/log/${appName}" /&gt;
    &lt;!-- Define the format pattern of log output,Included date and time、Thread name、Log Level、Logger name and log message --&gt;
    &lt;property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:} [%thread] %-5level %logger{36} - %msg%n" /&gt;
    &lt;!-- Asynchronous file output Appender Configuration,Write logs asynchronously to files for performance improvements --&gt;
    &lt;appender name="ASYNC_FILE" class=""&gt;
        &lt;!-- The size of the asynchronous queue,That is, the maximum number of log events that can be cached is 512 --&gt;
        &lt;queueSize&gt;512&lt;/queueSize&gt;
        &lt;!-- Discard threshold,Set as 0 Indicates that log events are not discarded --&gt;
        &lt;discardingThreshold&gt;0&lt;/discardingThreshold&gt;
        &lt;!-- Quote name FILE of Appender,将异步处理后of日志发送到该 Appender --&gt;
        &lt;appender-ref ref="FILE" /&gt;
    &lt;/appender&gt;
    &lt;!-- Main log file Appender Configuration,Used to write logs to files and support scrolling policies --&gt;
    &lt;appender name="FILE" class=""&gt;
        &lt;!-- 指定日志文件of路径,use前面定义of日志主目录 --&gt;
        &lt;file&gt;${LOG_HOME}/&lt;/file&gt;
        &lt;!-- 编码器Configuration,将日志事件转换为指定格式of字符串 --&gt;
        &lt;encoder&gt;
            &lt;!-- use前面定义of日志格式模式 --&gt;
            &lt;pattern&gt;${LOG_PATTERN}&lt;/pattern&gt;
        &lt;/encoder&gt;
        &lt;!-- 滚动策略Configuration,Scroll based on file size and time --&gt;
        &lt;rollingPolicy class=""&gt;
            &lt;!-- 滚动后of文件命名模式,Include date and serial number --&gt;
            &lt;fileNamePattern&gt;${LOG_HOME}/application.%d{yyyy-MM-dd}.%&lt;/fileNamePattern&gt;
            &lt;!-- 单个日志文件of最大大小,More than this size will scroll --&gt;
            &lt;maxFileSize&gt;50MB&lt;/maxFileSize&gt;
            &lt;!-- 保留of历史日志文件of最大天数 --&gt;
            &lt;maxHistory&gt;30&lt;/maxHistory&gt;
            &lt;!-- 所有日志文件of总大小上限 --&gt;
            &lt;totalSizeCap&gt;5GB&lt;/totalSizeCap&gt;
        &lt;/rollingPolicy&gt;
    &lt;/appender&gt;
    &lt;!-- Error log asynchronous output Appender Configuration,Write error logs asynchronously to file --&gt;
    &lt;appender name="ASYNC_ERROR_FILE" class=""&gt;
        &lt;!-- The size of the asynchronous queue,That is, the maximum number of log events that can be cached is 512 --&gt;
        &lt;queueSize&gt;512&lt;/queueSize&gt;
        &lt;!-- Discard threshold,Set as 0 Indicates that log events are not discarded --&gt;
        &lt;discardingThreshold&gt;0&lt;/discardingThreshold&gt;
        &lt;!-- Quote name ERROR_FILE of Appender,将异步处理后of错误日志发送到该 Appender --&gt;
        &lt;appender-ref ref="ERROR_FILE" /&gt;
    &lt;/appender&gt;
    &lt;!-- Error log file Appender Configuration,Specifically used to log error logs and support scrolling policies --&gt;
    &lt;appender name="ERROR_FILE" class=""&gt;
        &lt;!-- 指定Error log fileof路径,use前面定义of日志主目录 --&gt;
        &lt;file&gt;${LOG_HOME}/&lt;/file&gt;
        &lt;!-- 过滤器Configuration,Only allowed ERROR 及以上级别of日志通过 --&gt;
        &lt;filter class=""&gt;
            &lt;!-- Set the filtering level to ERROR --&gt;
            &lt;level&gt;ERROR&lt;/level&gt;
        &lt;/filter&gt;
        &lt;!-- 编码器Configuration,将日志事件转换为指定格式of字符串 --&gt;
        &lt;encoder&gt;
            &lt;!-- use前面定义of日志格式模式 --&gt;
            &lt;pattern&gt;${LOG_PATTERN}&lt;/pattern&gt;
        &lt;/encoder&gt;
        &lt;!-- 滚动策略Configuration,Scroll based on file size and time --&gt;
        &lt;rollingPolicy class=""&gt;
            &lt;!-- 滚动后of文件命名模式,Include date and serial number --&gt;
            &lt;fileNamePattern&gt;${LOG_HOME}/error.%d{yyyy-MM-dd}.%&lt;/fileNamePattern&gt;
            &lt;!-- 单个Error log fileof最大大小,More than this size will scroll --&gt;
            &lt;maxFileSize&gt;50MB&lt;/maxFileSize&gt;
            &lt;!-- 保留of历史Error log fileof最大天数 --&gt;
            &lt;maxHistory&gt;60&lt;/maxHistory&gt;
            &lt;!-- 所有Error log fileof总大小上限 --&gt;
            &lt;totalSizeCap&gt;10GB&lt;/totalSizeCap&gt;
        &lt;/rollingPolicy&gt;
    &lt;/appender&gt;
    &lt;!-- Email Notification Appender Configuration,When an error log appears发送Email Notification --&gt;
    &lt;appender name="EMAIL" class=""&gt;
        &lt;!-- SMTP Server address --&gt;
        &lt;smtpHost&gt;&lt;/smtpHost&gt;
        &lt;!-- SMTP Server Port --&gt;
        &lt;smtpPort&gt;587&lt;/smtpPort&gt;
        &lt;!-- Sender Email Username --&gt;
        &lt;username&gt;user@&lt;/username&gt;
        &lt;!-- Sender's email password --&gt;
        &lt;password&gt;password&lt;/password&gt;
        &lt;!-- Recipient email address --&gt;
        &lt;to&gt;admin@&lt;/to&gt;
        &lt;!-- Sender email address --&gt;
        &lt;from&gt;noreply@&lt;/from&gt;
        &lt;!-- Email Subject,Includes the application name、Logger name and log message --&gt;
        &lt;subject&gt;${appName} - ERROR: %logger{20} - %m&lt;/subject&gt;
        &lt;!-- 邮件内容布局Configuration --&gt;
        &lt;layout class=""&gt;
            &lt;!-- 邮件内容of格式模式,Included date and time、Thread name、Log Level、Logger name、Log messages and exception information --&gt;
            &lt;pattern&gt;%d{yyyy-MM-dd HH:mm:} [%thread] %-5level %logger{36} - %msg%n%ex&lt;/pattern&gt;
        &lt;/layout&gt;
        &lt;!-- 循环缓冲区跟踪器Configuration,用于缓存一定数量of日志事件 --&gt;
        &lt;cyclicBufferTracker class=""&gt;
            &lt;!-- Buffer size,That is, the maximum cache 10 Log Events --&gt;
            &lt;bufferSize&gt;10&lt;/bufferSize&gt;
        &lt;/cyclicBufferTracker&gt;
    &lt;/appender&gt;
    &lt;!-- Root Logger Configuration,It's all Logger of父 Logger,设置全局ofLog Level和输出目of地 --&gt;
    &lt;root level="WARN"&gt;
        &lt;!-- 将日志异步输出到Main log file Appender --&gt;
        &lt;appender-ref ref="ASYNC_FILE" /&gt;
        &lt;!-- 将Error log asynchronous output到Error log file Appender --&gt;
        &lt;appender-ref ref="ASYNC_ERROR_FILE" /&gt;
        &lt;!-- When an error log appears,发送Email Notification --&gt;
        &lt;appender-ref ref="EMAIL" /&gt;
    &lt;/root&gt;
&lt;/configuration&gt;

This is the ultimate guide to Spring Boot Integration Logback: From basic to advanced configuration. For more related Spring Boot Integration Logback configuration content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!