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-starter
orspring-boot-starter-web
Logback 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:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- Attribute definition --> <property name="LOG_HOME" value="./logs" /> <!-- definitionappender --> <appender name="CONSOLE" class=""> <!-- encoderdefinition日志输出格式 --> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- definitionlogger --> <logger name="" level="DEBUG" /> <!-- rootloggerConfiguration --> <root level="INFO"> <appender-ref ref="CONSOLE" /> </root> </configuration>
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:
<configuration scan="true" scanPeriod="30 seconds" debug="false"> <!-- Configuration content --> </configuration>
Best Practices:
- The development environment can be enabled
scan
To dynamically adjust the configuration - The production environment should be closed
scan
anddebug
To avoid performance overhead - Turn on only when diagnosing a problem
packagingData
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:
<!-- Direct definition --> <property name="LOG_HOME" value="/var/logs/myapp" /> <!-- Get from system environment variable --> <property name="LOG_HOME" value="${LOG_DIR:-./logs}" /> <!-- Load from external file --> <property file="conf/" /> <!-- existSpring BootUsed in --> <springProperty scope="context" name="appName" source="" />
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
<appender name="UNIQUE_NAME" class="APPENDER_CLASS"> <!-- Filter configuration --> <filter class="" /> <!-- layout/Encoder configuration --> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} %msg%n</pattern> </encoder> <!-- Other unique configurations --> </appender>
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:
<filter class=""> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <!-- Actions when matching --> <onMismatch>DENY</onMismatch> <!-- 不Actions when matching --> </filter>
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:
<!-- Configure log levels for specific packages --> <logger name="" level="DEBUG" /> <!-- Configure log levels for specific classes and disable themadditivity --> <logger name="" level="TRACE" additivity="false"> <appender-ref ref="SPECIAL_APPENDER" /> </logger>
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
<appender name="ERROR_FILE" class=""> <filter class=""> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <!-- Other configurations --> </appender>
ThresholdFilter: Threshold filtering
<appender name="WARN_FILE" class=""> <filter class=""> <level>WARN</level> </filter> <!-- Other configurations --> </appender>
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:
<!-- Only whenMDCExist inuserIdShown only when --> <pattern>%d{yyyy-MM-dd} [%thread] %mdc{userId:-} %-5level %logger{36} - %msg%n</pattern>
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
- examine
fileNamePattern
Date mode in - Ensure that the log volume meets the rolling conditions
- Check file permissions
Solution:
<!-- Make sure the trigger policy is configured --> <rollingPolicy class=""> <fileNamePattern>logs/app-%d{yyyy-MM-dd}.%</fileNamePattern> <maxFileSize>50MB</maxFileSize> <!-- Must be configured --> <maxHistory>30</maxHistory> </rollingPolicy>
Question 2: The log file is too large
- Adjustment
maxFileSize
andmaxHistory
- use
totalSizeCap
Limit 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:
<encoder> <pattern>%msg%n</pattern> <charset>UTF-8</charset> <!-- Identify the character set --> </encoder>
6. Complete configuration example
6.1 Development environment configuration ()
<?xml version="1.0" encoding="UTF-8"?> <!-- LogbackRoot tag of configuration file,All configuration elements must be included in this tag --> <configuration> <!-- Attribute definition section,pass <property> Tag definition reusable properties,Convenient to reference in configuration files --> <!-- Define the home directory for log file storage --> <property name="LOG_HOME" value="/var/logs/myapp" /> <!-- Define the format pattern of log output,Included date and time、Thread name、Log Level、Logger name and log message --> <property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:} [%thread] %-5level %logger{36} - %msg%n" /> <!-- ConsoleAppenderConfiguration,用于Will日志输出到Console --> <appender name="CONSOLE" class=""> <!-- 编码器Configuration,Convert log events to strings of specified format --> <encoder> <!-- Use the log format pattern defined earlier --> <pattern>${LOG_PATTERN}</pattern> </encoder> <!-- 过滤器Configuration,Only allowed指定级别及以上的日志pass --> <filter class=""> <!-- Set the filtering level to WARN,That is, only output WARN Logs at or above levels --> <level>WARN</level> </filter> </appender> <!-- Main fileAppenderConfiguration,Used to output logs to files,And support rolling policy --> <appender name="FILE" class=""> <!-- Specify the path to the log file,Use the log home directory defined earlier --> <file>${LOG_HOME}/</file> <!-- 编码器Configuration,Convert log events to strings of specified format --> <encoder> <!-- Use the log format pattern defined earlier --> <pattern>${LOG_PATTERN}</pattern> </encoder> <!-- 滚动策略Configuration,Scroll based on file size and time --> <rollingPolicy class=""> <!-- Scrolled file naming mode,Include date and serial number --> <fileNamePattern>${LOG_HOME}/application.%d{yyyy-MM-dd}.%</fileNamePattern> <!-- Maximum size of a single log file,More than this size will scroll --> <maxFileSize>50MB</maxFileSize> <!-- Maximum number of days of historical log files retained --> <maxHistory>30</maxHistory> <!-- The maximum total size of all log files --> <totalSizeCap>5GB</totalSizeCap> </rollingPolicy> </appender> <!-- Error logAppenderConfiguration,Specially used for recording ERROR Level log --> <appender name="ERROR_FILE" class=""> <!-- 指定Error log文件的路径,Use the log home directory defined earlier --> <file>${LOG_HOME}/</file> <!-- 编码器Configuration,Convert log events to strings of specified format --> <encoder> <!-- Use the log format pattern defined earlier --> <pattern>${LOG_PATTERN}</pattern> </encoder> <!-- 过滤器Configuration,Only allowed ERROR Level logpass --> <filter class=""> <!-- Set the filtering level to ERROR --> <level>ERROR</level> <!-- 当Log Level匹配时,允许pass --> <onMatch>ACCEPT</onMatch> <!-- 当Log Level不匹配时,拒绝pass --> <onMismatch>DENY</onMismatch> </filter> <!-- 滚动策略Configuration,Roll based on time --> <rollingPolicy class=""> <!-- Scrolled file naming mode,Included dates --> <fileNamePattern>${LOG_HOME}/error.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- 保留的历史Error log文件的最大天数 --> <maxHistory>90</maxHistory> </rollingPolicy> </appender> <!-- asynchronousAppenderConfiguration,用于asynchronous处理日志,Improve performance --> <appender name="ASYNC_FILE" class=""> <!-- asynchronous队列的大小,That is, the maximum number of log events that can be cached --> <queueSize>1024</queueSize> <!-- 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 --> <discardingThreshold>0</discardingThreshold> <!-- 引用前面定义的Main fileAppender,Willasynchronous处理后的日志输出到该 Appender --> <appender-ref ref="FILE" /> </appender> <!-- LoggerConfiguration部分,用于指定不同包或kind的Log Level和输出目的地 --> <!-- against Bag and its sub-packages,设置Log Level为 INFO --> <logger name="" level="INFO" /> <!-- against Bag and its sub-packages,设置Log Level为 WARN --> <logger name="" level="WARN" /> <!-- against kind,设置Log Level为 DEBUG,And turn off the log addition --> <logger name="" level="DEBUG" additivity="false"> <!-- 只Will该kind的日志输出到Main fileAppender --> <appender-ref ref="FILE" /> </logger> <!-- Root LoggerConfiguration,It's all Logger The father Logger,设置全局的Log Level和输出目的地 --> <root level="INFO"> <!-- Will日志输出到ConsoleAppender --> <appender-ref ref="CONSOLE" /> <!-- Will日志asynchronous输出到Main fileAppender --> <appender-ref ref="ASYNC_FILE" /> <!-- Will ERROR Level log输出到Error logAppender --> <appender-ref ref="ERROR_FILE" /> </root> </configuration>
6.2 Production environment configuration ()
<?xml version="1.0" encoding="UTF-8"?> <!-- Logback Root tag of configuration file,All configuration items must be included --> <configuration> <!-- 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 --> <springProperty scope="context" name="appName" source="" defaultValue="myApp"/> <!-- Define the home directory properties of the log store,The path is /var/log/ Add the name of the application obtained earlier --> <property name="LOG_HOME" value="/var/log/${appName}" /> <!-- Define the format pattern of log output,Included date and time、Thread name、Log Level、Logger name and log message --> <property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:} [%thread] %-5level %logger{36} - %msg%n" /> <!-- Asynchronous file output Appender Configuration,Write logs asynchronously to files for performance improvements --> <appender name="ASYNC_FILE" class=""> <!-- The size of the asynchronous queue,That is, the maximum number of log events that can be cached is 512 --> <queueSize>512</queueSize> <!-- Discard threshold,Set as 0 Indicates that log events are not discarded --> <discardingThreshold>0</discardingThreshold> <!-- Quote name FILE of Appender,将异步处理后of日志发送到该 Appender --> <appender-ref ref="FILE" /> </appender> <!-- Main log file Appender Configuration,Used to write logs to files and support scrolling policies --> <appender name="FILE" class=""> <!-- 指定日志文件of路径,use前面定义of日志主目录 --> <file>${LOG_HOME}/</file> <!-- 编码器Configuration,将日志事件转换为指定格式of字符串 --> <encoder> <!-- use前面定义of日志格式模式 --> <pattern>${LOG_PATTERN}</pattern> </encoder> <!-- 滚动策略Configuration,Scroll based on file size and time --> <rollingPolicy class=""> <!-- 滚动后of文件命名模式,Include date and serial number --> <fileNamePattern>${LOG_HOME}/application.%d{yyyy-MM-dd}.%</fileNamePattern> <!-- 单个日志文件of最大大小,More than this size will scroll --> <maxFileSize>50MB</maxFileSize> <!-- 保留of历史日志文件of最大天数 --> <maxHistory>30</maxHistory> <!-- 所有日志文件of总大小上限 --> <totalSizeCap>5GB</totalSizeCap> </rollingPolicy> </appender> <!-- Error log asynchronous output Appender Configuration,Write error logs asynchronously to file --> <appender name="ASYNC_ERROR_FILE" class=""> <!-- The size of the asynchronous queue,That is, the maximum number of log events that can be cached is 512 --> <queueSize>512</queueSize> <!-- Discard threshold,Set as 0 Indicates that log events are not discarded --> <discardingThreshold>0</discardingThreshold> <!-- Quote name ERROR_FILE of Appender,将异步处理后of错误日志发送到该 Appender --> <appender-ref ref="ERROR_FILE" /> </appender> <!-- Error log file Appender Configuration,Specifically used to log error logs and support scrolling policies --> <appender name="ERROR_FILE" class=""> <!-- 指定Error log fileof路径,use前面定义of日志主目录 --> <file>${LOG_HOME}/</file> <!-- 过滤器Configuration,Only allowed ERROR 及以上级别of日志通过 --> <filter class=""> <!-- Set the filtering level to ERROR --> <level>ERROR</level> </filter> <!-- 编码器Configuration,将日志事件转换为指定格式of字符串 --> <encoder> <!-- use前面定义of日志格式模式 --> <pattern>${LOG_PATTERN}</pattern> </encoder> <!-- 滚动策略Configuration,Scroll based on file size and time --> <rollingPolicy class=""> <!-- 滚动后of文件命名模式,Include date and serial number --> <fileNamePattern>${LOG_HOME}/error.%d{yyyy-MM-dd}.%</fileNamePattern> <!-- 单个Error log fileof最大大小,More than this size will scroll --> <maxFileSize>50MB</maxFileSize> <!-- 保留of历史Error log fileof最大天数 --> <maxHistory>60</maxHistory> <!-- 所有Error log fileof总大小上限 --> <totalSizeCap>10GB</totalSizeCap> </rollingPolicy> </appender> <!-- Email Notification Appender Configuration,When an error log appears发送Email Notification --> <appender name="EMAIL" class=""> <!-- SMTP Server address --> <smtpHost></smtpHost> <!-- SMTP Server Port --> <smtpPort>587</smtpPort> <!-- Sender Email Username --> <username>user@</username> <!-- Sender's email password --> <password>password</password> <!-- Recipient email address --> <to>admin@</to> <!-- Sender email address --> <from>noreply@</from> <!-- Email Subject,Includes the application name、Logger name and log message --> <subject>${appName} - ERROR: %logger{20} - %m</subject> <!-- 邮件内容布局Configuration --> <layout class=""> <!-- 邮件内容of格式模式,Included date and time、Thread name、Log Level、Logger name、Log messages and exception information --> <pattern>%d{yyyy-MM-dd HH:mm:} [%thread] %-5level %logger{36} - %msg%n%ex</pattern> </layout> <!-- 循环缓冲区跟踪器Configuration,用于缓存一定数量of日志事件 --> <cyclicBufferTracker class=""> <!-- Buffer size,That is, the maximum cache 10 Log Events --> <bufferSize>10</bufferSize> </cyclicBufferTracker> </appender> <!-- Root Logger Configuration,It's all Logger of父 Logger,设置全局ofLog Level和输出目of地 --> <root level="WARN"> <!-- 将日志异步输出到Main log file Appender --> <appender-ref ref="ASYNC_FILE" /> <!-- 将Error log asynchronous output到Error log file Appender --> <appender-ref ref="ASYNC_ERROR_FILE" /> <!-- When an error log appears,发送Email Notification --> <appender-ref ref="EMAIL" /> </root> </configuration>
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!