Configure logback log for spring boot

Configure logback log for spring boot

As mentioned in the previous introduction to spring boot, the default log print of spring boot is logback, so configuring logback log will be very simple, but there are also some points to pay attention to.

Requirements for this configuration log

  1. Log needs console printing and file printing.
  2. Among them, the file printing is saved to their respective files according to the log level.
  3. File log a log every day and keep it for 30 days.
  4. The file log can freely specify the saving path, printing format, etc.
  5. The console print can specify the print format and freely add or delete some logs.

Through the introduction in the previous article, we know that the default log of Spring boot is logback, so as long as the following dependencies are introduced, the jar package of logback log will be automatically introduced.

<!-- Spring Boot Web rely on -->
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

The jar packages required for separate spring projects to use logback logs are as follows:

<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-classic</artifactId>
	<version>1.1.9</version>
</dependency>

<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-core</artifactId>
	<version>1.1.9</version>
</dependency>
<!--because logback Log needs to be connected with slf4j Use together, as follows: jar Package needs to be imported-->
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-api</artifactId>
	<version>1.7.22</version>
</dependency>1234567891011121314151617

Again, the spring boot project does not need to introduce the above three jar packages, but has been automatically introduced.

The following are the configuration steps:

  • The configuration of logback logs in spring boot needs to be under src/main/resources and application.properties at the same level. A logback XML file is generally named logback-spring.xml. Many people on the Internet suggest this name. I don't see any difference, so I configure it according to what they say to avoid unnecessary errors.
  • logback-spring.xml is configured as console printing and file printing according to my requirements. Directly copy the following contents, name them and put them in the above position. The specific contents are as follows:
<?xml version="1.0" encoding="UTF-8"?>  
<configuration scan="true" scanPeriod="60 seconds">  
    <!-- All say spring boot The log needs to be introduced, but I always print two logs after I introduce it, so I remove it and it will not affect the use -->
    <!-- <include resource="org/springframework/boot/logging/logback/base.xml"/> -->
    <!-- Console settings -->  
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">  
        <encoder>  
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>  
        </encoder>  
    </appender>  
    <!-- INFO -->  
    <appender name="infoAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- File path, note LOG_PATH Is the default,
            Its configuration corresponds to application.properties Inside logging.path value-->  
        <file>${LOG_PATH}/info/info.log</file>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!-- File name -->  
            <fileNamePattern>info/info-%d{yyyy-MM-dd}.log  
            </fileNamePattern>  
            <!-- Maximum number of saved history files -->  
            <MaxHistory>30</MaxHistory>  
        </rollingPolicy>  
        <encoder>  
            <pattern>${FILE_LOG_PATTERN}</pattern>  
        </encoder>  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>INFO</level>  
            <onMatch>ACCEPT</onMatch>    
            <onMismatch>DENY</onMismatch>    
        </filter>  
    </appender>

    <!-- DEBUG -->  
    <appender name="debugAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- File path, note LOG_PATH Is the default,
            Its configuration corresponds to application.properties Inside logging.path value-->  
        <file>${LOG_PATH}/debug/debug.log</file>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!-- File name -->  
            <fileNamePattern>debug/debug-%d{yyyy-MM-dd}.log</fileNamePattern>  
            <!-- Maximum number of saved history files -->  
            <MaxHistory>30</MaxHistory>  
        </rollingPolicy>  
        <encoder>  
            <pattern>${FILE_LOG_PATTERN}</pattern>  
        </encoder>  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>DEBUG</level>  
            <onMatch>ACCEPT</onMatch>    
            <onMismatch>DENY</onMismatch>    
        </filter>  
    </appender> 
     <!-- WARN -->  
    <appender name="warnAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- File path, note LOG_PATH Is the default,
            Its configuration corresponds to application.properties Inside logging.path value-->   
        <file>${LOG_PATH}/warn/warn.log</file>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!-- File name -->  
            <fileNamePattern>warn/warn-%d{yyyy-MM-dd}.log  
            </fileNamePattern>  
            <!-- Maximum number of saved history files -->  
            <MaxHistory>30</MaxHistory>  
        </rollingPolicy>  
        <encoder>  
            <pattern>${FILE_LOG_PATTERN}</pattern>  
        </encoder>  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>WARN</level>  
            <onMatch>ACCEPT</onMatch>    
            <onMismatch>DENY</onMismatch>    
        </filter>  
    </appender> 

    <!-- ERROR -->  
    <appender name="errorAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">  
        <!-- File path, note LOG_PATH Is the default,
            Its configuration corresponds to application.properties Inside logging.path value-->  
        <file>${LOG_PATH}/error/error.log</file>  
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
            <!-- File name -->  
            <fileNamePattern>error/error-%d{yyyy-MM-dd}.log  
            </fileNamePattern>  
            <!-- Maximum number of saved history files -->  
            <MaxHistory>30</MaxHistory>  
        </rollingPolicy>  
        <encoder>  
            <pattern>${FILE_LOG_PATTERN}</pattern>  
        </encoder>  
        <filter class="ch.qos.logback.classic.filter.LevelFilter">  
            <level>ERROR</level>  
            <onMatch>ACCEPT</onMatch>    
            <onMismatch>DENY</onMismatch>    
        </filter>  
    </appender>
      <logger name="org.springframework" additivity="false">
        <level value="ERROR" />
        <appender-ref ref="STDOUT" />
        <appender-ref ref="errorAppender" />
    </logger>

    <!-- Due to startup, the following two packages are printed debug There are many level logs, so it is adjusted to ERROR-->
    <logger name="org.apache.tomcat.util" additivity="false">
        <level value="ERROR"/>
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="errorAppender"/>
    </logger>

    <!-- default spring boot Import hibernate A lot of dependent packages will be started hibernate Relevant contents shall be removed directly -->
    <logger name="org.hibernate.validator" additivity="false">
        <level value="ERROR"/>
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="errorAppender"/>
    </logger>
    <root level="DEBUG">
         <appender-ref ref="STDOUT"/>  
         <appender-ref ref="infoAppender"/>
         <appender-ref ref="debugAppender"/>
          <appender-ref ref="warnAppender"/>
         <appender-ref ref="errorAppender"/>
    </root> 
</configuration>

Among them, you should note that there are many variables in the form of "${}", which are actually the default names of logback logs, such as ${LOG_PATH},${CONSOLE_LOG_PATTERN},${FILE_LOG_PATTERN}, etc. these variables only need to add the following configuration in the default configuration file of spring boot, application.properties:

1) The following is the location of log output. Note that log is used in logback-spring.xml_ Path to get the value

logging.path=d:/logs/springBoot

2) The following is the location of the log configuration file

logging.config=classpath:logback-spring.xml

3) The following is the format setting of the console print log. Note that console is used in logback-spring.xml_ LOG_ Pattern to get

logging.pattern.console=[%d{yyyy-MM-dd HH:mm:ss}] -- [%-5p]: [%c] -- %m%n

4) The following is the format setting of file print log. Note that file is used in logback-spring.xml_ LOG_ Pattern can be obtained

logging.pattern.file=[%d{yyyy-MM-dd HH:mm:ss}] -- [%-5p]: [%c] -- %m%n

Add the above four configurations to complete the log configuration. To say more, why is the log configuration name in the application.properties file different from that in ${}? You need to look at the introduction of base.xml at the top of logback-spring.xml. You can find this file. Its location is in the following jar package:

spring-boot-1.5.1.RELEASE.jar

Find the following location:

org.springframework.boot.logging.logback

You will see four XML files: base.xml, console-appender.xml, etc. open file.appender.xml as follows:

In other words, the log configuration file in spring boot has been written to death, but it has to be written according to its requirements in application.properties, so I think this is also the disadvantage of spring boot. There are too many hidden configurations. If you know, it is very simple, but if you don't know, it will waste a lot of time and configure a lot of useless things.

Through these four spring boot log xml files, you should also know why you did not configure the log in the previous entry spring boot, but printed the log. This should be the internal log.

In addition, let's talk about the print control of logs. For example, if there are some print logs I don't want, I can configure the logback-spring.xml file and add a logger tag. For example:

[2021-06-05 19:14:23] -- [INFO ]: [org.I0Itec.zkclient.ZkClient] -- zookeeper state changed (SyncConnected)
[2021-06-05 19:14:23] -- [DEBUG]: [org.I0Itec.zkclient.ZkClient] -- Leaving process event
[2021-06-05 19:14:23] -- [DEBUG]: [org.I0Itec.zkclient.ZkClient] -- State is SyncConnected123

I don't need to print the above three logs now, so I need additional configuration, because they come from org.I0Itec.zkclient.ZkClient class, and the printed contents are DEBUG and INFO levels respectively. For log printing, just increase the log printing level of this class (the logs from low to high are TRACE, DEBUG, INFO, WARN and ERROR), Therefore, as long as the log level of this class is configured above WARN, the above content will not be printed. The configuration method is as follows:

 <logger name="org.I0Itec.zkclient.ZkClient" additivity="false">
        <level value="ERROR" />
        <appender-ref ref="STDOUT" />
        <appender-ref ref="errorAppender" />
</logger>

Of which:

name indicates the print location of the log, which can be seen from the above.
Setting the additivity to false means that the log printing settings (console printing or file printing and other specific settings) will not be passed to the root tag, that is, if they are set in the logger, they will be printed, which has nothing to do with root.
level value = 'error' means that this type of log will be printed only when the level is set to error level.
When the last two lines represent the error level, the console and error file will be printed, and the log will be printed at the same time.

Notes for configuring logback logs:

  1. Logback and log4j should not be put together, which will conflict. The main jar packages are slf4j-log4j12.jar and logback-classic.jar. The design of these two jar packages is anti-human. There is a class, both of which will exist. As long as these two jar packages are introduced at the same time, you will see a series of conflicting red characters when starting spring boot. Therefore, as long as you use logback logs, In addition to excluding the main jar packages of log4j, don't forget to exclude slf4j-log4j12.jar. For specific exclusion methods, you can select the pom.xml of maven project, find the Dependency Hierarchy on the right, find the jar package to be excluded, right-click and select Exclude Maven Artifact, and then save it.

  2. If you don't write the logback-spring.xml file of logback as I did, you don't need to configure all four lines in the application.properties file. If you copy mine directly, you need to configure it.

  3. Logback doesn't seem to be commonly used as log4j. Many third-party jar packages use log4j. For example, dubbo and zookeeper of Alibaba are the default log4j. Therefore, when introducing third-party jars, you use logback. Pay special attention to whether they use log4j by default. If so, slf4j-log4j12.jar can be excluded. We'll talk about spring boot+dubbo later.

Tags: Java Spring Spring Boot Back-end

Posted on Fri, 26 Nov 2021 19:14:09 -0500 by sdotsen