Preface
When the project is progressing, if the first thing is to build a Spring framework, then the second thing is to build a log framework based on Sring. This article is a summary of the blogger's integration of Log4j2 logs when using Spring Boot to build a project during the learning process
1. Common logging frameworks
- : It is the Java native logging framework introduced by JDK in version 1.4
- Log4j: An open source project of Apache that can control the destination of log information transfer is console, files, GUI components, etc.
- LogBack: is an improved version of Log4j
- Log4j2: Log4j2 is no longer just an upgraded version of Log4j, it has been rewritten from beginning to end
2. Introduction to configuration parameters
1. Log level
There are 8 levels in total, from low to high: All < Trace < Debug < Info < Warn < Error < Fatal < OFF
mechanism: If the level of a log information is greater than or equal to the level of the configuration file, record it
- All: The lowest level is used to open all logging
- Trace: Tracing means to advance the program, you can write a trace output
- Debug: Debugging, pointing out fine-grained information events, is very helpful for debugging applications.
- Info: Message highlights the operation process of the application at a coarse-grained level
- Warn: Output warnings and logs at the following levels of warning. Some information is not error information, but you should also give the programmer some prompts.
- Error: Output error message log
- Fatal: Output logs for each critical error that will cause the application to exit
- OFF: The highest level, used to turn off all logging
2. Output form
- CONSOLE (output to console)
- FILE (output to file)
3. Log format
- SimpleLayout: Displayed in simple form
- HTMLLayout: Displayed as HTML table
- PatternLayout: Custom display
3.1 PatternLayout Custom log layout
The Console node, File node, and child node of the RollingFile node, specify the output format, and the default is not set to: %m%n
property:
- pattern: Specify log format
Custom log format:
%d{yyyy-MM-dd HH:mm:ss, SSS}: Log production time, output to milliseconds
%-5level: Output log level, -5 means left alignment and fixed output of 5 characters. If it is insufficient, add 0 on the right.
%p: Log output format
%c: The name of the logger (%logger)
%m: log content, i.e. ("message")
%n: newline character
%C: Java class name (%F)
%L: Number of rows where the log output is located
%M: The method name where the log output is located
%l: The number of lines in which the output statement is located, including class name, method name, file name, and line number
%t: represents the thread name (%thread)
hostName: local machine name
hostAddress: local IP address
3. Log4j2 configuration details
1. Root node Configuration
The root node has two attributes and two child nodes
property:
- status: used to specify the level of the log print log of log4j itself
- monitorinterval: used to specify the monitoring interval time of log4j automatic reconfiguration, unit: s, minimum is 5s
Child nodes:
- Appenders
- Loggers (Suggests that multiple Appenders and Loggers can be defined)
2. Appenders node
Configuration The root node child node, there are three common child nodes: Console, File, and RollingFile
2.1 Console node
The child node of the Appenders node is used to define the Appender output to the console
property:
- name: Used to specify the name of the Appender
- target: Optional value SYSTEM_OUT or SYSTEM_ERR. Generally, only default is set: SYSTEM_OUT
Child nodes:
- PatternLayout: Output format, default value: %m%n
2.2 File nodes
The child node of the Appenders node is used to define the Appender that outputs to the file at the specified location, and is generally used to test the output.
property:
- name: Used to specify the name of the Appender
- fileName: Specify the file name with full path to the destination file of the output log.
Child nodes:
- PatternLayout: Output format, default value: %m%n
- ThresholdFilter: Specify the output level
2.3 RollingFile node
The child node of the Appenders node is used to define the size exceeding the specified size, automatically delete the old and create a new Appender.
property:
- name: Used to specify the name of the Appender
- fileName: Specify the file name with full path to the destination file of the output log.
- filePattern: Specify the name format of the newly created log file
Child nodes:
- ThresholdFilter: Determines whether log events can be output
- PatternLayout: Output format, default value: %m%n
- Policies: Specify the policy of scrolling logs, which is when to create a new log file to output logs
- DefaultRolloverStrategy: Used to specify how many log files are at most in the same folder, start deleting the oldest and creating new log files (through the max attribute)
2.3.1 ThresholdFilter node
The child node of the RollingFile node determines whether the log event can be output. There are three values for the filtering condition: ACCEPT (accept), DENY (reject) or NEUTRAL (neutral)
property:
- level: Specify the level of filtering logs
- onMatch: The default value is NEUTRAL
- onMismatch: The default value is DENY
2.3.2 Policies node
RollingFile node child node, specify the policy for scrolling logs
Child nodes:
- TimeBasedTriggeringPolicy: Time-based scrolling policy, the interval attribute is used to specify how often to scroll, the default is 1hour. modulate = true Used to adjust the time
- SizeBasedTriggeringPolicy: Based on the scrolling policy of the specified file size, the size attribute is used to define the size of each log file.
2.3.3 ThresholdFilter node
3. Loggers node
Configuration The child node of the root node
Child nodes:
- Root: Used to specify the root log of the project. If the Logger is not specified separately, the Root log output will be used by default.
- Logger: used to specify the form of logging separately, such as specifying different log levels for the class under the specified package, etc.
3.1 Root node
Loggers node child node
property:
- level: Specify the log output level
Child nodes:
- appender-ref: used to specify which Appender the log is output to, and specify it through ref
3.2 Logger node
property:
- level: Specify the log output level
- name: used to specify the full package path of the class or class to which the Logger is applicable, inherited from the Root node
Child nodes:
- appender-ref: used to specify which Appender the log is output to, and specify it through ref
4. Log4j2 usage steps
1. Add dependencies
Spring Boot uses logback's log framework by default, so logback needs to be excluded, otherwise an error will occur due to jar dependency conflict.
<!-- web --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> <!--RemoveSpringBootDefault configuration--> <exclusions> <!--The default filter systemlogbacklog--> <exclusion> <groupId></groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- Log4j2 --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>
2. Configuration
Create a new file under resources and write the following content:
<?xml version="1.0" encoding="UTF-8"?> <!--ConfigurationThe one behindstatus,This is for setting uplog4j2The output of the information within itself,Can not be set,When set totracehour,You'll seelog4j2Various internal detailed outputs--> <!--monitorInterval: Log4jAble to automatically detect and modify configurations Files and reconfigurations themselves,Set the interval seconds--> <configuration monitorInterval="5"> <!--Log level and priority sorting: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL --> <!-- Set properties yourself,Pass later${}Come and visit --> <properties> <!--Log storage directory--> <property name="LOG_HOME">log4j2-logs</property> <!--Log Name--> <property name="LOG_NAME">patrick-blog-server</property> <!--Log format-document--> <property name="LOG_FORMAT">[%d{yyyy-MM-dd HH:mm:}] %p %t %c[%L] - %m %n</property> <!--Log format-Console--> <property name="LOG_FORMAT_CONSOLE">%d{yyyy-MM-dd HH:mm:} %highlight{%-5level} [%t] %highlight{%c{1.}.%M(%L)}: %msg%n%throwable</property> <!--Backup directory- 根据年月建立document夹 --> <property name="BACKUP_HOME">${LOG_HOME}/$${date:yyyy-MM}</property> <!--Backup frequency--> <property name="BACK_HZ">%d{yyyy-MM-dd}</property> </properties> <appenders> <!--Console日志--> <console name="console" target="SYSTEM_OUT"> <!--Format of output log--> <PatternLayout pattern="${LOG_FORMAT_CONSOLE}" disableAnsi="false" noConsoleNoAnsi="false"/> <!--Console只输出levelInformation at or above levels(onMatch),Others are directly rejected(onMismatch)--> <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/> </console> <!--document会打印出所有information,thislogThe program will be automatically cleared every time you run it,Depend onappendAttribute determination,适合临hour测试用--> <File name="filelog" fileName="${LOG_HOME}/${LOG_NAME}/" append="false"> <PatternLayout pattern="${LOG_FORMAT}"/> </File> <!-- this会打印出所有ofinfoInformation at the following levels,Each time the size exceedssize,Then thissizeLogs of size will be automatically saved by year-月份建立ofdocument夹下面并进行压缩,As an archive--> <RollingFile name="infoLog" fileName="${LOG_HOME}/${LOG_NAME}/" filePattern="${LOG_HOME}/${LOG_NAME}-INFO-%d{yyyy-MM-dd}_%"> <!--Console只输出levelInformation at or above level(onMatch),Others are directly rejected(onMismatch)--> <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="${LOG_FORMAT}"/> <Policies> <!--intervalThe attribute is used to specify how often to scroll,The default is1 hour--> <TimeBasedTriggeringPolicy interval="1"/> <SizeBasedTriggeringPolicy size="10MB"/> </Policies> <!-- DefaultRolloverStrategyIf the property is not set,则默认为最多同一document夹下7个document开始覆盖--> <DefaultRolloverStrategy max="15"/> </RollingFile> <!-- this会打印出所有ofwarnInformation at the following levels,Each time the size exceedssize,Then thissizeLogs of size will be automatically saved by year-月份建立ofdocument夹下面并进行压缩,As an archive--> <RollingFile name="warnLog" fileName="${LOG_HOME}/${LOG_NAME}/" filePattern="${LOG_HOME}/${LOG_NAME}-WARN-%d{yyyy-MM-dd}_%"> <!--Console只输出levelInformation at or above level(onMatch),Others are directly rejected(onMismatch)--> <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="${LOG_FORMAT}"/> <Policies> <!--intervalThe attribute is used to specify how often to scroll,The default is1 hour--> <TimeBasedTriggeringPolicy interval="1"/> <SizeBasedTriggeringPolicy size="10MB"/> </Policies> <!-- DefaultRolloverStrategyIf the property is not set,则默认为最多同一document夹下7个document开始覆盖--> <DefaultRolloverStrategy max="15"/> </RollingFile> <!-- this会打印出所有oferrorInformation at the following levels,Each time the size exceedssize,Then thissizeLogs of size will be automatically saved by year-月份建立ofdocument夹下面并进行压缩,As an archive--> <RollingFile name="errorLog" fileName="${LOG_HOME}/${LOG_NAME}/" filePattern="${LOG_HOME}/${LOG_NAME}-ERROR-%d{yyyy-MM-dd}_%"> <!--Console只输出levelInformation at or above level(onMatch),Others are directly rejected(onMismatch)--> <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="${LOG_FORMAT}"/> <Policies> <!--intervalThe attribute is used to specify how often to scroll,The default is1 hour--> <TimeBasedTriggeringPolicy interval="1"/> <SizeBasedTriggeringPolicy size="10MB"/> </Policies> <!-- DefaultRolloverStrategyIf the property is not set,则默认为最多同一document夹下7个document开始覆盖--> <DefaultRolloverStrategy max="15"/> </RollingFile> </appenders> <!--LoggerThe form used by nodes to specify the log separately,For example, you need to subscribe for the specified packageclassSpecify different log levels, etc.。--> <!--Then defineloggers,Only definedloggerand introducedappender,appenderIt will take effect--> <loggers> <!--Filter outspringandmybatisSome uselessDEBUGinformation--> <logger name="" level="info" additivity="false"> <AppenderRef ref="console"/> </logger> <!--监控系统information--> <!--ifadditivitySet asfalse,ZeziLogger Only in your ownappenderOutput,Not in the fatherLogger ofappenderOutput。--> <Logger name="" level="info" additivity="false"> <AppenderRef ref="console"/> </Logger> <root level="info"> <!-- 输出到Console --> <appender-ref ref="console"/> <!-- 输出到document --> <appender-ref ref="filelog"/> <appender-ref ref="infoLog"/> <appender-ref ref="warnLog"/> <appender-ref ref="errorLog"/> </root> </loggers> </configuration>
3. Use the lombok tool to simplify creating Logger classes
Using lombok can omit the process of building logger instances and simplify development with @Slf4j annotation
@Slf4j public class LogTest { public static void main(String... args) { ("Something is warning here"); } }
Summarize
This is the article about Spring Boot integrating log4j2 log configuration. For more related Spring Boot integrating log4j2 log configuration content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!