Introduction of Logback

Logback is a stable, efficient and fast Java logging framework. As an improved version of Log4J, Logback has more features and performance improvements than LOG4J. For details, see the official documentation.

Logback is divided into three modules

  • Logback-core: Core module that serves as the basis for classic and Access modules
  • Logback-classic: The SLF4J API is implemented and used with SLF4J to easily switch to other logging frameworks
  • Logback-access: Integrates with Servlet containers (such as Tomcat and Jetty) and provides an HTTP access logging interface

Logback load

Logback starts loading and looks for configuration files in the following order

  1. In the System configuration file System Properties to find whether there is logback. ConfigurationFile corresponds to the value
  2. Find logback.groovy in your classpath (Logback supports both groovy and XML configurations)
  3. Look for logback-test.xml in classpath
  4. Look for logback.xml in classpath

If any configuration exists, no further scanning is performed and the configuration file is used for initialization. If no configuration file is found, Logback creates a configuration that outputs logs to the console.

Logback configuration

The root node configuration

Configuration is the root node of the configuration file and has three properties:

  • Debug: The default value is false. If this parameter is set to true, internal logback logs are displayed to view the logback running status in real time.
  • Scan: The default value is true. If this value is set to true, the configuration file will be reloaded if it is changed.
  • ScanPeriod: This attribute takes effect only when scan is true. Set the interval for scanning for changes in configuration files. The default unit is milliseconds. The default interval is 1 minute (60 seconds)

Configuration code:

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

Sets the contextName contextName

Each logger is associated with a Logger context, and the default context name is “default.” However, it can be set to a different name using <contextName> to distinguish between records for different applications. Once set, it cannot be modified.

Configuration code:

<contextName>new context name</contextName>
Copy the code

Set variable property

Property is a tag that defines a variable and can be accessed with ${variable name}. It has three properties:

  • Name: variable name
  • Value: indicates the value of a variable
  • File: Specifies the path of the configuration file. If multiple configuration information exists, it can be directly written to the configuration file and imported through file
  • Resource: Performs the same functions as file, except that it can import configuration files directly from the classpath path

Configuration code:

<! -- name value form --> <property name="APP_Name" value="MyApp"/>
<contextName>${APP_Name}</contextName>  
Copy the code
<! Properties: APP_Name=MyApp LOG_PATH=logs <property file="src/main/java/config/variables.properties" />
<contextName>${APP_Name}</contextName> 
Copy the code
<! Properties: APP_Name=MyApp LOG_PATH=logs <property resource="variables.properties" />
<contextName>${APP_Name}</contextName> 
Copy the code

Configuration Sub nodes Logger and root

Logger sets the log level and location (appender specified) for a class or package. It has three properties:

  • Name: specifies the package name or class name
  • Level: indicates the output log level. If this level is not set, the current logger inherits the latest non-empty level. Root has a default level of DEBUG
  • Additivity: Whether to pass logs to superiors. Default is true

A logger can assign more than one appender-ref to a logger by setting its child node appender-ref:

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>[%d{HH:mm:ss.SSS}] [%5level] [%thread] %logger{36} %msg%n</Pattern>
            <charset>UTF-8</charset>
        </encoder>
</appender>
<logger name="X" level="INFO" additivity="false">
        <appender-ref ref="STDOUT"/>
</logger>
<logger name="X.Y" additivity="false">
    <appender-ref ref="STDOUT"/>
</logger>
Copy the code

Root is a special logger. It is the root node of all loggers. Since it has been named root and has no parent level, there is only one attribute, level.

<root level="DEBUG">
    <appender-ref ref="STDOUT"/>
    <appender-ref ref="ASYNC"/>
</root>
Copy the code

Level inheritance Example 1:

logger name level The actual level
root DEBUG DEBUG
X Is not set DEBUG
X.Y Is not set DEBUG
X.Y.Z Is not set DEBUG

Example 1 only root sets one log output level. X, X.Y, and X.Y.Z loggers do not set the log output level. Therefore, they inherit the level of root, that is, DEBUG

Level inheritance Example 2:

logger name level The actual level
root ERROR ERROR
X INFO INFO
X.Y DEBUG DEBUG
X.Y.Z WARN WARN

Example 2 all loggers have a log level set, and hierarchy inheritance does not work.

Level inheritance Example 3:

logger name level The actual level
root DEBUG DEBUG
X INFO INFO
X.Y Is not set INFO
X.Y.Z WARN WARN

Example 3 X.Y does not set the log level and inherits the value of the nearest logger X that has a log level up.

Level inheritance Example 4:

logger name level The actual level
root DEBUG DEBUG
X INFO INFO
X.Y Is not set INFO
X.Y.Z Is not set INFO

Example 4 X.Y and X.Y.Z do not set the log level and inherit the value of the latest logger X that has the log level up.

Configuration Appender of the child node

Appender is the logging component and has two properties (both must be configured when used) :

  • Name: Sets the name of the appender for later loggers to reference
  • Class: set the full path name of the class of appender, example: ch. Qos. Logback. Core. ConsoleAppender

Appenders can contain zero or one layout, zero or more Encoder elements, and zero or more filter elements. In addition to these three elements, you can also contain any number of elements that correspond to the JavaBean property of the appender class, such as: file specifies the log file name.

  • Layout: Formats logs
  • Encoder: Encoder has been introduced since version 0.9.19. The previous version uses layout. Logback strongly recommends using Encoder instead of Layout
  • Filter: Filters logs

Appenders are commonly used in the following ways:

  1. ConsoleAppender: Output to the console, or more specifically to system. out or System.err, the former being the default target.
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%msg%n</pattern>
    </encoder>
    <target>
        System.err
    </target>
</appender>
Copy the code
  1. FileAppender: Output to a file whose object is specified by file. If the file already exists, append or empty the file based on the value of the Append property.
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>testFile.log</file>
    <append>true</append> <! --set immediateFlush to false for much higher logging throughput -->
    <immediateFlush>true</immediateFlush> <! -- encoders are assigned thetype
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
</appender>
Copy the code
  1. RollingFileAppender: Inherits from FileAppender and provides a rollingrecord function, first logging to a specified file and then logging to another file when a condition is triggered. There are two important child nodes, rollingPolicy and triggeringPolicy
  • RollingPolicy: Specifies the behavior of the RollingFileAppender when rolling occurs, such as the ability to switch log files
  • TriggeringPolicy: Specifies when RollingFileAppender triggers scrolling.
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logFile.log</file> <! Make the scroll strategy according to the time, responsible for both the scroll and the trigger scroll. --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <! --> <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> <! </maxHistory> <totalSizeCap>3GB</totalSizeCap> </rollingPolicy> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>mylog.txt</file> <! -- Roll policy based on file size and time --> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <! --> <fileNamePattern>mylog-%d{YYYY-MM-DD}.%i. xt</fileNamePattern> <! A maximum of 100MB for each log file is reserved for 60 days. </maxFileSize> <maxHistory>60</maxHistory> <totalSizeCap>20GB</totalSizeCap> </rollingPolicy> <encoder> <pattern>%msg%n</pattern> </encoder> </appender>Copy the code
  1. AsyncAppender: Logs asynchronously. It only acts as a scheduler, so it must reference another appender to log output.
  • DiscardingThreshold: By default, when the remaining capacity of the blocking queue is 20%, it discards events of TRACE, DEBUG, and INFO and reserves only those of WARN and ERROR. Set to 0 to preserve all events.
  • QueueSize: indicates the maximum capacity of a blocked queue. By default, queueSize is 256.
  • Appender-ref: Indicates which specific appender AsyncAppender uses for logging output.
<! -- asynchronous output --> <appender name ="ASYNC" class= "ch.qos.logback.classic.AsyncAppender"> <! --> <discardingThreshold>0</discardingThreshold> <! Change the default queue depth, which affects performance. The default value is 256 --> <queueSize>256</queueSize> <! Appender-ref = appender-ref = appender-ref = appender-ref = appender-ref = appender-ref ="FILE"/>  
</appender>
     
<logger name="X" level="DEBUG">
    <appender-ref ref="ASYNC" />
</logger>
Copy the code