preface

Using Logback, you can customize console log output, print different logs to different files at different levels, archive logs, and delete them regularly.

For an application, a good logging system is of great help in tracing problems, as well as finding and resolving problems online, so let’s configure logback logging.

Spring-boot-starter-web is installed by default when we initialize the Spring Boot project. In addition, Spring Boot uses logback log management by default, so we only need to configure it out of the box.

1. Configure poM

Pom.xml added configuration

<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.3. RELEASE</version>
        <relativePath/>
        <! -- lookup parent from repository -->
    </parent>
    <groupId>com.alex</groupId>
    <artifactId>knowledge</artifactId>
    <version>1.0.0</version>
    <name>knowledge</name>
    <description>knowledge share project for Spring Boot</description>
    
    <properties>
        <! -- Configure Java version -->
        <java.version>1.8</java.version>
    </properties>
    
    <dependencies>
    
        <! Spring Boot logback logback logback
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>
    
</project>
Copy the code

2. Create logback-spring. XML file under resource

Attribute Description In the logback configuration file Logback has five log levels by default. The log levels are as follows: trace< debug < info < warn < error

SpringBootThe default log level isinfo,warn,errorIf other levels of logging are used, you can configure them in the configuration <configuration>: used to configure logBack scan: indicates whether the configuration file will be reloaded if it is changed. The default value is true. ScanPeriod: indicates the interval for checking whether the configuration file is changed. This attribute takes effect when scan is true. Debug: If this parameter is set to true, internal logback logs are displayed to view the logback running status in real time. The default value is false<include>Resource: indicates the resource path<contextName>: each logger is associated with a logger context. The default contextName is default, but it can be set to another name to distinguish between applications. Once set, the log contextName cannot be changed<property>Name: specifies the name of the variable. Value: specifies the value of the variable<appender>: log output policy Name: indicates the policy name class: indicates the policy. Ch. Qos. Logback. Core. ConsoleAppender is corresponding to the console output of strategy; Ch. Qos. Logback. Core. Rolling. RollingFileAppender is corresponding to the output file strategy<filter>: can output the specified log output level above the log output, below the log output level will not output the class: what kind of filters, ch. Qos. Logback. Classic. Filter. The filter system at ThresholdFilter for<level>: Indicates the log output level<encoder>: Sets the format of log output. Charset: specifies the code of log output<pattern>: Indicates the format of the log output<file>: Indicates the log output path and file name<rollingPolicy>: Sets the log cutting policy. Class: sets the log cutting policy<fileNamePattern>: Defines the log cutting mode and archives daily logs into a file<timeBasedFileNamingAndTriggeringPolicy>: Defines log cutting files<maxFileSize>: specifies the upper limit on the size of a log file at which old logs will be deleted<maxHistory>: indicates the number of days in which logs are saved to prevent logs from filling up the disk space<logger>: Specifies the log printing level of a package or a specific class. Name: specifies a package or a specific class. Level: specifies the log output level<level>: specifies the log output level. Value: specifies the log output level<appender-ref>: refers to the custom log output policy<appender>Ref: references the log output policy<root>: specifies the basic log output level. Level: specifies the log output level<appender-ref>: refers to the custom log output policy<appender>Ref: references the log output policy<springProfile>Name: Specifies the name of the environment to be used. Multiple environments are used separately. The current environment must be specified in the application.yml file via spring. Pro: Disable the following configuration when the pro environment is used<root>: The value is the same as that of root<logger>: The value is the same as that of rootCopy the code

logback-spring.xml

<?xml version="1.0" encoding="UTF-8"? >
<! -- Log levels are TRACE < DEBUG < INFO < WARN < ERROR < FATAL. If set to WARN, messages lower than WARN will not be printed -->
<! -- scan: When this property is set to true, the configuration file will be reloaded if it changes. The default value is true -->
<! -- scanPeriod: sets the interval for checking whether the configuration file has been modified. If no time unit is given, the default unit is milliseconds. This attribute takes effect when scan is true. The default interval is 1 minute. -->
<! -- debug:When the value is set to true, internal logback logs are displayed to view the running status of logback in real time. The default value is false. -->
<configuration scan="true" scanPeriod="10 seconds">

    <contextName>logback</contextName>
    <! The value of name is the name of the variable, and the value of value is the value defined by the variable. The defined values are inserted into the Logger context. After you define variables, you can make "${}" to use them. -->
    <property name="log.path" value="./logs"/>
    <property name="log_pattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level --- [%thread] %logger{50} - %msg%n"/>
    <property name="log_fileNamePattern" value="-%d{yyyy-MM-dd}.%i.log"/>
    <property name="log_maxFileSize" value="100MB"/>
    <property name="log_maxHistory" value="15"/>

    <! -- Output to console -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <! The log appender is configured for development purposes only. The console outputs logs with a log level greater than or equal to this level.
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
        <encoder charset="UTF-8">
            <pattern>${log_pattern}</pattern>
        </encoder>
    </appender>


    <! -- Output to file -->

    <! -- DEBUG log -->
    <appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <! -- The path and name of the log file being recorded -->
        <file>${log.path}/log-debug.log</file>
        <! Log file output format -->
        <encoder>
            <pattern>${log_pattern}</pattern>
            <charset>UTF-8</charset> <! -- Set character set -->
        </encoder>
        <! -- Logger scroll policy, by date, by size -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <! -- Log Archive -->
            <fileNamePattern>${log.path}/log-debug-${log_fileNamePattern}</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log_maxFileSize}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <! -- Log file retention days -->
            <maxHistory>${log_maxHistory}</maxHistory>
        </rollingPolicy>
        <! -- This log file only records debug level -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>debug</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>

    </appender>

    <! -- Log level = INFO -->
    <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <! -- The path and name of the log file being recorded -->
        <file>${log.path}/log_info.log</file>
        <! Log file output format -->
        <encoder>
            <pattern>${log_pattern}</pattern>
            <charset>UTF-8</charset> <! -- Set character set -->
        </encoder>
        <! -- Logger scroll policy, by date, by size -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <! -- Log Archive -->
            <fileNamePattern>${log.path}/log-info-${log_fileNamePattern}</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log_maxFileSize}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <! -- Log file retention days -->
            <maxHistory>${log_maxHistory}</maxHistory>
        </rollingPolicy>
        <! -- This log file only records info level -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>info</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <! Log level = WARN -->
    <appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <! -- The path and name of the log file being recorded -->
        <file>${log.path}/log_warn.log</file>
        <! Log file output format -->
        <encoder>
            <pattern>${log_pattern}</pattern>
            <charset>UTF-8</charset> <! -- Set character set -->
        </encoder>
        <! -- Logger scroll policy, by date, by size -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <! -- Log Archive -->
            <fileNamePattern>${log.path}/log-warn-${log_fileNamePattern}</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log_maxFileSize}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <! -- Log file retention days -->
            <maxHistory>${log_maxHistory}</maxHistory>
        </rollingPolicy>
        <! This log file records only logs of warn level -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>warn</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <! -- Log level = ERROR -->
    <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <! -- The path and name of the log file being recorded -->
        <file>${log.path}/log_error.log</file>
        <! Log file output format -->
        <encoder>
            <pattern>${log_pattern}</pattern>
            <charset>UTF-8</charset> <! -- Set character set -->
        </encoder>
        <! -- Logger scroll policy, by date, by size -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <! -- Log Archive -->
            <fileNamePattern>${log.path}/log-error-${log_fileNamePattern}</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log_maxFileSize}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <! -- Log file retention days -->
            <maxHistory>${log_maxHistory}</maxHistory>
        </rollingPolicy>
        <! -- This log file only records ERROR levels -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
    

    <! Development environment: Print console -->
    <springProfile name="dev">
        <logger name="com.nmys.view" level="debug"/>
    </springProfile>

    <root level="info">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="DEBUG_FILE"/>
        <appender-ref ref="INFO_FILE"/>
        <appender-ref ref="WARN_FILE"/>
        <appender-ref ref="ERROR_FILE"/>
    </root>

    <! -- Test environment: Output to file -->
    <springProfile name="test">
        <root level="info">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="DEBUG_FILE"/>
            <appender-ref ref="INFO_FILE"/>
            <appender-ref ref="ERROR_FILE"/>
            <appender-ref ref="WARN_FILE"/>
        </root>
    </springProfile>

    <! -- Production environment: Output to file -->
    <springProfile name="pro">
        <root level="info">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="DEBUG_FILE"/>
            <appender-ref ref="INFO_FILE"/>
            <appender-ref ref="ERROR_FILE"/>
            <appender-ref ref="WARN_FILE"/>
        </root>
    </springProfile>


</configuration>
Copy the code

Four different levels of logs are generated as shown below:

🆗 Without further ado, well, that concludes this little chapter;

Code repository address: Click to enter