01 About the log level

Eight levels are listed in ascending order: All < Trace < Debug < Info < Warn < Error < Fatal < OFF.

  1. All: indicates the lowest level. It is used to enable All logging.

  2. Trace: it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace.

  3. Debug: Indicates fine-grained information events that are very helpful for debugging applications.

  4. Info: Messages highlight the execution of the application at a coarse-grained level.

  5. Warn: Logs of warning and lower levels are generated.

  6. Error: Logs of Error information are output.

  7. Fatal: logs every critical error event that will cause the application to exit.

  8. OFF: indicates the highest level. It is used to disable all logging.

The program prints logs at or higher than the specified log level. The higher the log level is, the less logs are printed.

02 Remove the Logback dependency of spring-boot

As multiple logging components together will cause conflicts, it is necessary to exclude the original Spring-boot-Web dependency pop. XML from the logback dependency of Spring-boot and add the exclusion label

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
	<exclusions>
		<exclusion>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-logging</artifactId>
		</exclusion>
	</exclusions>
</dependency>
Copy the code

03 Adding log4j2 dependency

No need to set the version automatically matches the current Spring-Boot version

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
Copy the code

04 Parsing configuration file nodes

4.1 Configuration of the root node

Appenders and Loggers(indicating that multiple Appenders and Loggers can be defined) have two attributes: Status and MonitorInterval and two child nodes: Appenders and Loggers(indicating that multiple Appenders and Loggers can be defined)

Status: specifies the level of log4J itself to print logs monitorInterval: specifies the monitoring interval that log4J automatically reconfigures, in seconds. The minimum value is 5sCopy the code

4.2 Appenders node

There are three common sub-nodes: Console, RollingFile, and File.

The Console node defines an Appender for output to the Console.#

Name: Appender name target: SYSTEM_OUT or SYSTEM_ERR, default: system_out.patternLayout: output format, default: %m%nCopy the code

The 4.2.2 File node is used to define the Appender of the output File to the specified location.

FileName: specifies the name of the destination log file with the full path. PatternLayout: Output format, not set Default: %m%n.Copy the code

The 4.2.3 RollingFile node is used to define an Appender that automatically removes old files and creates new ones when they exceed the specified size.

FileName: specifies the name of the destination log file with the full path. PatternLayout: Output format, not set Default: %m% N. filePattern: Specifies the name format of the new log file. Policies: Specifies the rolling log policy, that is, when to create a log file and export logs. TimeBasedTriggeringPolicy: Policies child nodes, rolling strategy based on time, the interval attribute is used to specify how long scroll, the default is 1 hour. Ulate = True modulate= True modulate= True modulate=true modulate=true modulate= True Rather than 7 am. SizeBasedTriggeringPolicy: Policies child nodes, rolling strategy based on the specified file size, the size attribute is used to define the size of each log file. DefaultRolloverStrategy: Used to specify the maximum number of log files in a folder to start deleting the oldest and creating new ones (via the Max attribute).Copy the code

4.3 the Loggers node

There are two common types: Root and Logger.

4.3.1 the Root node

Used to specify the Root log for the project. If Logger is not specified separately, the Root log output is used by default

Level: log output level. There are eight log output levels in ascending order: All < Trace < Debug < Info < Warn < Error < Fatal < off. AppenderRef: Root’s child node that specifies to which Appender the log is exported.

4.3.2 Logger node

Used to specify the form of logging separately, for example, to specify different logging levels for classes under specified packages.

Level: indicates the log output level. There are eight log output levels in ascending order: All < Trace < Debug < Info < Warn < Error < Fatal < off. name: Used to specify the class or package path to which this Logger belongs, inherited from the Root node. AppenderRef: Logger’s child node that specifies to which Appender the log should be exported. If this is not specified, it inherits from Root by default. If specified, it will output in both the specified Appender and Root’s Appender, and we can set Logger additivity=”false” to output only in our custom Appender.

05 configuration log4j2

Place the log4j2.xml configuration file in the resource directory such as the complete log configuration file below

<? The XML version = "1.0" encoding = "utf-8"? > <! -- Log levels and priorities: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL --> <! --Configuration status, this is used to set the internal output of log4j2. You do not need to set this value. If you set it to trace, you will see the internal output of log4j2. --monitorInterval: Log4j can automatically detect changes to configuration files and reconfiguration itself, set the interval of seconds --> < Configuration Status ="WARN" monitorInterval="30"> <! Define all appenders first --> <appenders> <! <console name=" console "target="SYSTEM_OUT"> <! - the format of the output log - > < PatternLayout pattern = "[% d {HH: mm: ss: SSS}] [p] % % l - % m % n" / > < / console > <! -- The file will print out all the information, and the log will be automatically cleared every time the program runs, as determined by the append property, which is also useful, --> <File name="log" fileName="log/test.log" append="false"> <PatternLayout pattern="%d{HH:mm: ss.sss} %-5level %class{36} %L %M - %msg%xEx%n"/> </File> <! -- This will print all the info level and below information, each time the size of the log exceeds the size, the size of the log will be automatically saved in the folder created by year to month and compressed. As archive - > < RollingFile name = "RollingFileInfo" fileName = "${sys: user home} / IdeaProjects/logs/info. The log" filePattern="${sys:user.home}/IdeaProjects/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log"> <! -- The console outputs only messages of level and above (onMatch), --> <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Policies> <! - roll once a day - > < TimeBasedTriggeringPolicy interval = "1" modulate = "true" / > <! - or log up to 10 KB rolling a - > < SizeBasedTriggeringPolicy size = "10 k" / > < / Policies > < / RollingFile > < RollingFile name="RollingFileWarn" fileName="${sys:user.home}/IdeaProjects/logs/warn.log" filePattern="${sys:user.home}/IdeaProjects/logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log"> <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Policies> <! - roll once a day - > < TimeBasedTriggeringPolicy interval = "1" modulate = "true" / > <! - or log up to 10 KB rolling a - > < SizeBasedTriggeringPolicy size = "10 k" / > < / Policies > <! -- DefaultRolloverStrategy if not set, the default value is a maximum of 7 files in the same folder. </RollingFile> <RollingFile name="RollingFileError" fileName="${sys:user.home}/IdeaProjects/logs/error.log" filePattern="${sys:user.home}/IdeaProjects/logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log"> <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Policies> <! - roll once a day - > < TimeBasedTriggeringPolicy interval = "1" modulate = "true" / > <! - or log up to 10 KB rolling a - > < SizeBasedTriggeringPolicy size = "10 k" / > < / Policies > < / RollingFile > < / appenders > <! Then define logger. The appenders will only work if logger is defined and appenders are introduced --> <loggers> <! <logger name="org. springFramework "level="INFO"/> <logger name="org.mybatis" level="INFO"/> <root level="all"> <appender-ref ref="Console"/> <appender-ref ref="RollingFileInfo"/> <appender-ref ref="RollingFileWarn"/> <appender-ref ref="RollingFileError"/> </root> </loggers> </configuration>Copy the code