Springboot+logback detailed configuration

  1. Add dependencies
    Springboot3.0.2 is used here

rely

<dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.32</version>
</dependency>
`` 

application.yml placement

spring:
  application:
    name: chapter002
  profiles:
    active: dev 
  1. Detailed configuration of logback
    logback-spring.xml
    yml file
# You can also use a custom name,for examplelogback-config.xml,Just need to be inapplication.ymlJust specify it in the file:
logging: 
    config: classpath:logback-config.xml 

logback-spring.xmlDetailed configuration,The meaning and expression of each item will be introduced in detail later.
<?xml version="1.0" encoding="UTF-8"?>
<!-- Log levels are divided from low to highTRACE < DEBUG < INFO < WARN < ERROR < FATAL,If set toWARN,then lower thanWARNNone of the information will be output -->
<!-- scan:When this property is set totruehour,If the configuration document changes,will be reloaded,The default value istrue -->
<!-- scanPeriod:Set the time interval for monitoring whether the configuration document is modified,If no time unit is given,The default unit is milliseconds。
                         whenscanfortruehour,This property takes effect。The default time interval is1minute。 -->
<!-- debug:When this property is set totruehour,will print outlogbackInternal log information,View in real timelogbackOperating status。The default value isfalse。 -->
<configuration scan="true" scanPeriod="10 seconds">
​
    <!-- Log name,The default is taken from spring.application.name -->
    <springProperty name="contextName" source="spring.application.name"/>
    <!-- Operating environment -->
    <springProperty name="envName" source="spring.profiles.active"/>
​
    <!-- property:Specify variables,nameThe value is the name of the variable,valueThe value of is the value defined by the variable。The defined value will be inserted intologgerin context。After definition,Can make“{}”to use variables -->
    <!-- Log storage directory,Use project name,This way in multiple services,Logs can be stored in directories based on service names. -->
    <property name="log.path" value="/data/server/{contextName}/logs"/>
​
    <!--0. Log format and color rendering -->
    <!-- Rendering classes that color logs depend on -->
    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
    <conversionRule conversionWord="wex"
                    converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
    <conversionRule conversionWord="wEx"
                    converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
    <!--
        Console color log format
        Log interpretation:
        %clr([{contextName},{envName:-dev}]){yellow}:Output project name and project usage environment(yellow)
        %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint}:Output date,Format:yyyy-MM-dd HH:mm:ss.SSS
        %clr(%5p):Output log format。and align5Bit。in the case ofINFO、WARNThis four-character,By default, a space is added to the far left(infois blue,warnis light red,errorFor bold red,debugfor black)
        %clr({PID:- }){magenta}:outputPID(magenta)。ps:{PID:- } this {} Expression of usage,havePIDthen displayPID,If not, it will be displayed-
        [%15.15t]:Output thread name。If the recorded thread character length is less than15(First)Then use spaces to pad on the left,If the character length is greater than15(the second),then truncate excess characters from the beginning
        %clr(%-50.50(%logger{50})){cyan}:
            %-50.50():If recordedloggerCharacter length is less than50(First)Then fill it on the right with spaces,If the character length is greater than50(the second),then truncate excess characters from the beginning
            %logger{50}:Output log name Generally, the class name or package name of the log is used as the log name.
            {cyan}:Output color(blue)
        %msg%n":Log output content+newline(%n)
     -->
    <property name="console.log.pattern"
              value="%clr([{contextName},{envName:-dev}]){yellow} %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr({PID:- }){magenta} %clr(---){faint} [%15.15t] %clr(%-50.50(%logger{50})){cyan} : %msg%n"/>
    <!--  file log format。ps:No colors set in log file,Otherwise, the color part will haveESC[0:39emWaiting for garbled characters- -->
    <property name="log.pattern"
              value="[{contextName},{envName:-dev}] %d{yyyy-MM-dd HH:mm:ss.SSS} %5p {PID:- } --- [%15.15t] %-50.50(%logger{50}) : %msg%n"/>
​
    <!--1. output to console-->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>{console.log.pattern}</Pattern>
            <!-- Set character set -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>
​
    <!--2. output to document-->
    <!-- 2.0 Enter alllevellog ,Depends on project needs,Can be deleted-->
    <appender name="allLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- Current log output path、file name -->
        <file>{log.path}/all.log</file>
        <!--Log output format-->
        <encoder>
            <pattern>{log.pattern}</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!--Historical log archiving strategy-->
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- History log: Archive file name,If the directory is divided,Want to add aux Otherwise the log file cannot be generated on time,%iIndicates serial number,Can't be missing here,Because if a file reaches a specified size,Then we must follow%ito generate another file in the sequence -->
            <!--Save log policy according to %d{yyyy-MM-dd} save %d{yyyy-MM-dd}:Save by day %d{yyyy-MM-dd HH}:Save by hour-->
            <fileNamePattern>{log.path}/%d{yyyy-MM, aux}/all/all.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <!--Maximum size of a single file-->
            <maxFileSize>100MB</maxFileSize>
            <!-- <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> -->
            <!--     <maxFileSize>100MB</maxFileSize> -->
            <!-- </timeBasedFileNamingAndTriggeringPolicy> -->
            <!--Number of days to retain log files-->
            <maxHistory>7</maxHistory>
            <!--Used to specify the upper limit size of the log file,reached this value,Old logs will be deleted-->
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
    </appender>
​
    <!-- 2.1 levelfor DEBUG log,Time rolling output  -->
    <appender name="debugLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- Current log output path、file name -->
        <file>{log.path}/debug.log</file>
        <!--Log output format-->
        <encoder>
            <pattern>{log.pattern}</pattern>
            <charset>UTF-8</charset>
        </encoder>
​
        <!--Historical log archiving strategy-->
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- History log: Archive file name,If the directory is divided,Want to add aux Otherwise the log file cannot be generated on time,%iIndicates serial number,Can't be missing here,Because if a file reaches a specified size,Then we must follow%ito generate another file in the sequence -->
            <fileNamePattern>{log.path}/%d{yyyy-MM, aux}/debug/debug.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <!--Maximum size of a single file-->
            <maxFileSize>100MB</maxFileSize>
            <!--Number of days to retain log files-->
            <maxHistory>7</maxHistory>
            <!--Used to specify the upper limit size of the log file,reached this value,Old logs will be deleted-->
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
​
        <!-- This log document only recordsdebuglevel  levelfilter-->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>debug</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
​
    <!-- 2.2 levelfor INFO log,Time rolling output  -->
    <appender name="infoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- Current log output path、file name -->
        <file>{log.path}/info.log</file>
        <!--Log output format-->
        <encoder>
            <pattern>{log.pattern}</pattern>
            <charset>UTF-8</charset>
        </encoder>
​
        <!--Historical log archiving strategy-->
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- History log: Archive file name,If the directory is divided,Want to add aux Otherwise the log file cannot be generated on time,%iIndicates serial number,Can't be missing here,Because if a file reaches a specified size,Then we must follow%ito generate another file in the sequence -->
            <fileNamePattern>{log.path}/%d{yyyy-MM, aux}/info/info.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <!--Maximum size of a single file-->
            <maxFileSize>100MB</maxFileSize>
            <!--Number of days to retain log files-->
            <maxHistory>7</maxHistory>
            <!--Used to specify the upper limit size of the log file,reached this value,Old logs will be deleted-->
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
​
        <!-- This log document only recordsinfolevel  levelfilter-->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>info</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
​
    <!-- 2.3 levelfor WARN log,Time rolling output  -->
    <appender name="warnLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- Current log output path、file name -->
        <file>{log.path}/warn.log</file>
        <!--Log output format-->
        <encoder>
            <pattern>{log.pattern}</pattern>
            <charset>UTF-8</charset>
        </encoder>
​
        <!--Historical log archiving strategy-->
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- History log: Archive file name,If the directory is divided,Want to add aux Otherwise the log file cannot be generated on time,%iIndicates serial number,Can't be missing here,Because if a file reaches a specified size,Then we must follow%ito generate another file in the sequence -->
            <fileNamePattern>{log.path}/%d{yyyy-MM, aux}/warn/warn.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <!--Maximum size of a single file-->
            <maxFileSize>100MB</maxFileSize>
            <!--Number of days to retain log files-->
            <maxHistory>7</maxHistory>
            <!--Used to specify the upper limit size of the log file,reached this value,Old logs will be deleted-->
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
​
        <!-- This log document only recordswarnlevel  levelfilter-->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>warn</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
​
    <!-- 2.4 levelfor ERROR log,Time rolling output  -->
    <appender name="errorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- Current log output path、file name -->
        <file>{log.path}/error.log</file>
        <!--Log output format-->
        <encoder>
            <pattern>{log.pattern}</pattern>
            <charset>UTF-8</charset>
        </encoder>
​
        <!--Historical log archiving strategy-->
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- History log: Archive file name,If the directory is divided,Want to add aux Otherwise the log file cannot be generated on time,%iIndicates serial number,Can't be missing here,Because if a file reaches a specified size,Then we must follow%ito generate another file in the sequence -->
            <fileNamePattern>${log.path}/%d{yyyy-MM, aux}/error/error.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <!--Maximum size of a single file-->
            <maxFileSize>100MB</maxFileSize>
            <!--Number of days to retain log files-->
            <maxHistory>7</maxHistory>
            <!--Used to specify the upper limit size of the log file,reached this value,Old logs will be deleted-->
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
​
        <!-- This log document only recordserrorlevel  levelfilter-->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>error</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
​
    <!-- document Asynchronous log(async) -->
    <appender name="asyncAppLog" class="ch.qos.logback.classic.AsyncAppender"
              immediateFlush="false" neverBlock="true">
        <!-- 0:No log loss.20:If the queue's80%Full,will be discardedTRACT、DEBUG、INFOlevel logging -->
        <discardingThreshold>0</discardingThreshold>
        <!-- Change the default queue depth,This value affects performance.The default value is256 -->
        <queueSize>1024</queueSize>
        <!-- The caller will not be blocked when the queue is full.-->
        <neverBlock>true</neverBlock>
        <!-- add additionalappender,Only one can be added -->
        <appender-ref ref="allLog"/>
    </appender>
​
    <!--
        Since there will still be unprinted log content in the queue,,So you need to wait for a while,Waiting for the queue to be processed。
        The unit isms。If the queue is large,The queue has a lot of content,This value can be set larger。If the log in the queue has not been processed after this time,,The logs in the queue will be discarded
     -->
    <shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook">
        <delay>2000</delay>
    </shutdownHook>
​
    <!--
        <logger>Used to set the log printing level of a certain package or a specific class、 and specify<appender>。
        <logger>only onenameAttributes, an optionalleveland an optionaladdtivityAttributes。
        name:used to specify thisloggerA certain package or a specific class that is constrained。
        level:Used to set the print level,Case-insensitive:TRACE, DEBUG, INFO, WARN, ERROR, ALL and OFF,
              There is also a special valueINHERITEDor synonymsNULL,Represents the level of enforcement superior。
              If this property is not set,So currentlyloggerWill inherit the level of the superior。
        addtivity:Whether to go to superiorsloggerPass printing information。The default istrue。
        <logger name="org.springframework.web" level="info"/>
        <logger name="org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor" level="INFO"/>
    -->
​
    <!--
        rootThe node is a required node,Used to specify the most basic log output level,only onelevelAttributes
        level:Used to set the print level,Case-insensitive:TRACE, DEBUG, INFO, WARN, ERROR, ALL and OFF,
        cannot be set toINHERITEDor synonymsNULL。The default isDEBUG
        Can contain zero or more elements,identify thisappenderwill be added to thislogger。
    -->
​
    <!-- 4. final strategy Different log strategies can be formulated according to the environment.。Notice,here allLog not hererootMedium statement,above asyncAppLog statement(Asynchronous processing)-->
    <!-- 4.1 development environment:print console,Others can be printed to files<appender-ref>Comment -->
    <springProfile name="dev">
        <root level="info">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="debugLog"/>
            <appender-ref ref="infoLog"/>
            <appender-ref ref="warnLog"/>
            <appender-ref ref="errorLog"/>
            <appender-ref ref="asyncAppLog"/>
        </root>
    </springProfile>
​
    <!-- 4.2 Production Environment:output to document
    <springProfile name="pro">
        <root level="info">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="debugLog"/>
            <appender-ref ref="infoLog"/>
            <appender-ref ref="warnLog"/>
            <appender-ref ref="errorLog"/>
            <appender-ref ref="asyncAppLog"/>
        </root>
    </springProfile> -->
​
</configuration>
simple request,Print logs at each level: 
public void logbackDemo(){
    log.debug("debugLog example");
    log.info("infoLog example");
    log.warn("warnLog example");
    log.error("errorLog example");
}