Spring boot integrates log4j2 logging framework switching

1, Foreword

The first thing to understand is: SpringBoot - the bottom layer is the Spring framework, which uses JCL (commons logging) by default‘ SpringBoot uses SLF4j and logback. SLF4j is just a facade log. It only defines the interface and does not implement it. This is also to meet the polymorphic log implementation. Common logback, log4j and log4j2 are the implementation of SLF4j. Logback is another open-source log component designed by the founder of log4j, and log4j2 is an upgraded version of log4j.

The default implementation of the springboot log framework is logback. Today, I will introduce how to switch the springboot log framework to log4j2.

2, Modify pom file

1. Add dependency

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
            <version>1.3.8.RELEASE</version>
 </dependency>

2. Remove the logback dependency

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>logback-classic</artifactId>
                    <groupId>ch.qos.logback</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>log4j-over-slf4j</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
</dependency>

In this step, it is recommended to check carefully. Many other dependent packages also inherit or rely on this logback log package, which needs to be excluded under their corresponding dependencies. Otherwise, it is easy to start the springboot. It defaults to the original logback package. I went into the pit in person and checked it for a long time. idea has corresponding plug-ins or functions and depends on global search.

3, New log4j2.0 XML configuration file

Then add log4j2.0 in the src/resource directory of the project XML log configuration file:

<?xml version="1.0" encoding="UTF-8"?>
 2  <!--Log level and prioritization: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
 3  <!--Configuration hinder status,This is used to set log4j2 The internal information output can not be set when it is set to trace You'll see log4j2 Various internal detailed outputs-->
 4  <!--monitorInterval: Log4j It can automatically detect and modify the configuration file and reconfigure itself, and set the interval seconds-->
 5  <configuration status="WARN" monitorInterval="30">
 6      <!--Define all first appender-->
 7      <appenders>
 8      <!--Configuration of this output console-->
 9          <console name="Console" target="SYSTEM_OUT">
10          <!--Format of output log-->
11              <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
12          </console>
13      <!--The file will print out all the information, this log The program will be emptied automatically every time it is run, and the append Attribute decision, which is also very useful and suitable for temporary testing-->
14      <File name="log" fileName="log/test.log" append="false">
15         <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
16      </File>
17      <!-- This will print out all the information info And below, each time the size exceeds size,Then this size Logs of size are automatically saved by year-The folder created in the month is compressed as an archive-->
18          <RollingFile name="RollingFileInfo" fileName="${sys:user.home}/logs/info.log"
19                       filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
20              <!--Console output only level And above( onMatch),Other direct rejection( onMismatch)-->        
21              <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
22              <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
23              <Policies>
24                  <TimeBasedTriggeringPolicy/>
25                  <SizeBasedTriggeringPolicy size="100 MB"/>
26              </Policies>
27          </RollingFile>
28          <RollingFile name="RollingFileWarn" fileName="${sys:user.home}/logs/warn.log"
29                       filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
30              <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
31              <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
32              <Policies>
33                  <TimeBasedTriggeringPolicy/>
34                  <SizeBasedTriggeringPolicy size="100 MB"/>
35              </Policies>
36          <!-- DefaultRolloverStrategy If the property is not set, it defaults to up to 7 files in the same folder. Here, 20 files are set -->
37              <DefaultRolloverStrategy max="20"/>
38          </RollingFile>
39          <RollingFile name="RollingFileError" fileName="${sys:user.home}/logs/error.log"
40                       filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
41              <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
42              <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
43              <Policies>
44                  <TimeBasedTriggeringPolicy/>
45                  <SizeBasedTriggeringPolicy size="100 MB"/>
46              </Policies>
47          </RollingFile>
48      </appenders>
49      <!--Then define logger,Only defined logger And introduced appender,appender Will take effect-->
50      <loggers>
51          <!--Filter out spring and mybatis Some useless DEBUG information-->
52          <logger name="org.springframework" level="INFO"></logger>
53          <logger name="org.mybatis" level="INFO"></logger>
54          <root level="all">
55              <appender-ref ref="Console"/>
56              <appender-ref ref="RollingFileInfo"/>
57              <appender-ref ref="RollingFileWarn"/>
58              <appender-ref ref="RollingFileError"/>
59          </root>
60      </loggers>
61  </configuration>

4, Modify application Properties file
Add configuration:

logging.config = classpath:log4j2.xml

In this way, log4j2 will be loaded automatically when springboot starts Log configuration in XML file

Note: log4j and lockback can be configured Properties file, log4j2 seems to only support xml file configuration. After personal testing, it seems that log4j2 if it is a properties file, the configuration in the file cannot be read.

Start the project to see if it is based on your configured log4j2 The log printed by the log specification configured by the XML file.
If log4j2 related logs appear, the configuration is successful. If logback related log information still appears, it has not been configured. It is necessary to check whether there are other pom dependent packages that also depend on the default logback package. The exclusion needs to be excluded. The weak country is sure to exclude them. The above steps can switch to the log4j2 log framework.

Keywords: Java log4j log4j2

Added by dimitar on Tue, 04 Jan 2022 04:29:04 +0200