The introduction

This document describes the common configuration of LogBack and provides examples to explain the meaning and usage of each tag attribute based on the complete configuration file. This document implements the log splitting and saving functions applicable to production, and provides complete running effects

Logback Configures the label

This section describes some common logback tags. The structure of common logback configuration tags is as follows:

  • configurationThe label

Configuration Provides three configuration items

<configuration scan="true" scanPeriod="60 seconds" debug = "true">
Copy the code

Scan =”true” indicates that dynamic loading is enabled. ScanPeriod is used to set the dynamic loading time. If scan or scanPeriod is not specified, scan=”true” scanPeriod=”60 seconds” by default and debug =”true” is configured to enable debug logs of logback

  • propertyThe label

Property is used to declare variables

<property name="CHARSET" value="UTF-8"/>
Copy the code

Logback also supports reading configuration items from spring configuration files, which can be read using springProperty

    <springProperty scope="context" name="springAppName"
                    source="spring.application.name" />
Copy the code
  • appenderThe label

An appender is a component that outputs log events

 <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${PATTERN}</pattern>
            <charset>${CHARSET}</charset>
        </encoder>
    </appender>
Copy the code

ConsoleAppender appends log events to the console FileAppender outputs log events to a file RollingFileAppender rotates the log file and, when the log file meets the criteria, outputs the log to another file

  • loggerThe label

Logger sets the level of a package or class and specifies an appender

  <logger name="errorLogger" additivity ="true" level="ERROR">
     <appender-ref ref="errorAppender" />
 </logger>
Copy the code

The additivity statement passes prints to the parent logger, which defaults to true; Appender-ref specifies the log output component. You can configure more than one

  • rootThe label
<root level="INFO">
     <appender-ref ref="STDOUT"/>
 </root>
Copy the code

The root tag is the parent of all loggers, and if the subordinate appender specifies additivity=”true”, the output of the subordinate appender is reflected in the appender declared in root

practice

Go straight to a full available configuration

  
      
<configuration>

   <springProperty scope="context" name="springAppName"
                   source="spring.application.name" />
   <springProperty scope="context" name="springActive"
                   source="spring.profiles.active" />
   <property name="CHARSET" value="UTF-8"/>
   <property name="SAVE_PATH" value="/data/logs/${springAppName}"/>
   <property name="PATTERN" value="% d {MM - dd yyyy - HH: MM: ss. The SSS} {trackId} % 5 level % X 15.15 t] [% % class. {39} % method [L] % : % m % n"/>
   <if condition='property("springActive").equals("prod")'>
       <then>
           <property name="maxHistory" value="Seven"/>
       </then>
       <else>
           <property name="maxHistory" value="3"/>
       </else>
   </if>
   <property name="maxFileSize" value="200MB"/>
   
   <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
       <encoder>
           <pattern>${PATTERN}</pattern>
           <charset>${CHARSET}</charset>
       </encoder>
   </appender>
   
   <appender name="digestAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
       <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
           <level>INFO</level>
       </filter>
       <file>${SAVE_PATH}/${springAppName}-digest.log</file>
       <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
           <fileNamePattern>${SAVE_PATH}/digest/${springAppName}-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
           <maxHistory>${maxHistory}</maxHistory>
           <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
               <maxFileSize>${maxFileSize}</maxFileSize>
           </timeBasedFileNamingAndTriggeringPolicy>
       </rollingPolicy>
       <encoder>
           <pattern>${PATTERN}</pattern>
           <charset>UTF-8</charset>
       </encoder>
       <append>true</append>
   </appender>
   
   <appender name="bizAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
       <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
           <level>INFO</level>
       </filter>
       <file>${SAVE_PATH}/${springAppName}-biz.log</file>
       <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
           <fileNamePattern>${SAVE_PATH}/biz/${springAppName}-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
           <maxHistory>${maxHistory}</maxHistory>
           <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
               <maxFileSize>${maxFileSize}</maxFileSize>
           </timeBasedFileNamingAndTriggeringPolicy>
       </rollingPolicy>
       <encoder>
           <pattern>${PATTERN}</pattern>
           <charset>UTF-8</charset>
       </encoder>
       <append>true</append>
   </appender>
   
    <appender name="statAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
       <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
           <level>INFO</level>
       </filter>
       <file>${SAVE_PATH}/${springAppName}-stat.log</file>
       <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
           <fileNamePattern>${SAVE_PATH}/stat/${springAppName}-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
           <maxHistory>${maxHistory}</maxHistory>
           <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
               <maxFileSize>${maxFileSize}</maxFileSize>
           </timeBasedFileNamingAndTriggeringPolicy>
       </rollingPolicy>
       <encoder>
           <pattern>${PATTERN}</pattern>
           <charset>${CHARSET}</charset>
       </encoder>
       <append>true</append>
   </appender>
   
   <appender name="errorAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
       <file>${SAVE_PATH}/${springAppName}-error.log</file>
       <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
           <fileNamePattern>${SAVE_PATH}/error/${springAppName}-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
           <maxHistory>${maxHistory}</maxHistory>
           <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
               <maxFileSize>${maxFileSize}</maxFileSize>
           </timeBasedFileNamingAndTriggeringPolicy>
       </rollingPolicy>
       <encoder>
           <pattern>${PATTERN}</pattern>
           <charset>${CHARSET}</charset>
       </encoder>
       <filter class="ch.qos.logback.classic.filter.LevelFilter">
           <level>ERROR</level>
           <onMatch>ACCEPT</onMatch>
           <onMismatch>DENY</onMismatch>
       </filter>
       <append>true</append>
   </appender>
   
    <logger name="digestLogger" additivity ="true">
       <appender-ref ref="digestAppender" />
   </logger>
   <logger name="bizLogger" additivity ="true">
       <appender-ref ref="bizAppender" />
   </logger>
   <logger name="statLogger" additivity ="true">
       <appender-ref ref="statAppender" />
   </logger>
   <logger name="errorLogger" additivity ="true" level="ERROR">
       <appender-ref ref="errorAppender" />
   </logger>
     <logger name = "cn.sleeper" level = "DEBUG"/>

<root level="INFO">
       <appender-ref ref="STDOUT"/>
   </root>
</configuration>
   
Copy the code

explain

The above configuration

  • SpringProperty gets the application name from the Spring configuration file to name the log, and the spring.profiles.active parameter to distinguish the runtime environment

  • Property defines CHARSET to specify the day code, SAVE_PATH to specify the path for storing log files, PATTERN to specify the log format, maxHistory to specify the number of days for storing log files, maxFileSize to specify the maximum size of each log file. It should be mentioned that the logback uses

     <dependency>
             <groupId>org.codehaus.janino</groupId>
             <artifactId>janino</artifactId>
             <version>2.6.1</version>
     </dependency>
    Copy the code
  • appender

Appender type is ConsoleAppender, which is used as console output, with log format and code type specified. Bizderappender type is RollingFileAppender. (3) digestAppenderappender type is RollingFileAppender and (4) statAppenderappender type is RollingFileAppender. ErrorAppenderappender is of type RollingFileAppender and is used as an exception log. Each of these appenders defines the

log printing level. Use TimeBasedRollingPolicy to define log file rotation policy, specify log file name, maximum retention time, maximum file size, use

to define log format, log code, ErrorAppender uses LevelFilter to filter ERROR logs. ErrorAppender processes all ERROR logs. Non-info logs are filtered out. Other appenders use ThresholdFilter to filter logs below the configured INFO level

  • logger

For each defined appender, a logger is defined and appender-ref is associated to facilitate log splitting in code. Additivity =”true” means that logs are fed back to root, which is the console appender Logger declares additivity=”true”, which is not only recorded by < Logger > itself in an appender file, but also printed to the console

  • root

Level defines the print level appender-ref specifies the output to console to ConsoleAppender

The effect

In combination with the configuration file above, we defined multiple loggers, so we need to wrap the log layer so that the corresponding appender component can be called when we call it

public interface LogApi {
    Logger dlog = LoggerFactory.getLogger("digestLogger");
    Logger blog = LoggerFactory.getLogger("bizLogger");
    Logger slog = LoggerFactory.getLogger("statLogger");
    Logger elog = LoggerFactory.getLogger("errorLogger");
}
Copy the code

Use LogApi to print log tests

@RestController
@RequestMapping("/test")
public class LogController  {
    @GetMapping
    public void log(a) {

        blog.trace("Test service log trace");
        blog.debug("Test service log debug");
        blog.info("Test service log info");
        blog.warn("Test business log WARN");
        blog.error("Test business log error");

        elog.trace("Test exception log trace");
        elog.debug("Test Exception Log Debug");
        elog.info("Test exception log info");
        elog.warn("Test exception log WARN");
        elog.error("Test exception log error");

        slog.trace("Test statistics log trace");
        slog.debug("Test Statistics Log debug");
        slog.info("Test statistics log info");
        slog.warn("Test statistics log WARN");
        slog.error("Test statistics log error");

        dlog.trace("Test Summary log trace");
        dlog.debug("Test Summary log debug");
        dlog.info("Test Summary log info");
        dlog.warn("Test summary log WARN");
        dlog.error("Test summary log error"); }}Copy the code

Console output Generated directory structure bizdirectory

For testing purposes, 2KB split is defined, so files larger than 2KB will be placed in the configured directory and new files will be generated

logTest-biz.log logTest-error.log

This example code has been uploaded to github.com/chenxuancod…