SLF4J integrated logback implementation

slf4j integration logback description

1, References

slf4j official documents: https://www.slf4j.org/docs.html

Official logback documentation: https://logback.qos.ch/documentation.html

2, Integration steps

1. configuration node

First, the configuration node is logback The root node of the XML configuration file, and other nodes are its child nodes. It has three sub attributes, as follows:

  • scan: the default value is true, which means that the current configuration file will be loaded automatically when it is updated.
  • scanPeriod: the time unit for detecting the update of the configuration file. This attribute takes effect only when the scan value is true. The default unit is milliseconds, which can be customized.
  • debug: indicates whether to view the printing inside the logback framework. The default is false.
<!--Example: enable automatic detection of configuration file changes, and the detection interval is 30 seconds. Print the internal log of the log frame-->
<configuration scan="true" scanPeriod="30 seconds" debug="true">
</configuration>

2.appender node

This node is responsible for printing logs, including the printing method and format of logs. It has two attributes, name and class, which are the name of the appender component and the fully qualified name of the corresponding implementation class. Here are some common types of Appenders:

  • ConsoleAppender

    As the name suggests, the function of this component is to print the log on the console and use it in daily development and debugging. It has one child node:

    • encoder: that is, the encoding of log contents, that is, formatting. All of them have a child node pattern.
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> 
        <encoder> 
        	<pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern> 
        </encoder> 
    </appender> 
    
  • FileAppender

    This node is used to output logs to files, which is like a child node:

    • File: the log file name, which can be either a relative path or an absolute path. It is automatically created when the parent directory does not exist
    • Append: whether to append the log to the end of the file. The default is true. When false, the file log will be cleared and rewritten.
    • encoder: the same as the console log component, it is used to format logs.
    • Student: whether it is safe to write. The default is false. If it is true, it means safe writing, which ensures the integrity of the log, but the efficiency is low.
    <appender name="FILE" class="ch.qos.logback.core.FileAppender"> 
        <file>case-concurrent.log</file> 
        <append>true</append> 
        <encoder> 
            <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> 
        </encoder> 
    </appender>
    
  • RollingFileAppender

    Scroll through the log and write the log to a file. Recommended for use in production environments.

    It has three attributes, as follows:

    • File: the name of the file where the log is saved.
    • Append: the append method is the same as FileAppender.
    • Rolling policy: rolling policy, which is detailed below.

    Rolling strategy

    1. TimeBasedRollingPolicy

      Time based rolling strategy, which makes rolling strategy according to time, such as generating log files by day. It is like a child node:

      • fileNamePattern: must be a node. Specify the file name of the generated log file, including the file name and the "% d" converter, ""% d "can contain a Java text. Simpledateformat specifies the time format, such as:% d {yyyy mm}.

        Use% d directly. The default format is yyyy mm DD,

      • maxHistory: optional node. Control the number of reserved log files, and delete old log files when the number of files exceeds the limit.

    2. SizeBasedTriggeringPolicy

      The file size based scrolling strategy triggers the scrolling strategy to generate a new log file and save the log when the log file size exceeds the specified range. Like child nodes:

      • maxFileSize: the maximum log file size. The default is 10MB.
      • Student: when true, FixedWindowRollingPolicy is not supported. TimeBasedRollingPolicy is supported, but there are two limitations: 1. File compression is not supported or allowed, and 2. The file attribute cannot be set and must be left blank.
      • Triggingpolicy: tells RollingFileAppender to activate scrolling appropriately.
    3. FixedWindowRollingPolicy

      The scrolling strategy of renaming files according to the fixed window algorithm is as follows:

      • minIndex: minimum value of window index.
      • maxIndex: the maximum value of window index, which is automatically set to 12 when it exceeds 12.
      • fileNamePattern: must contain "% I". For example, assuming that the minimum and maximum values are 1 and 2 respectively and the naming pattern is mylog%i.log, the archive file mylog1.log will be generated Log and mylog2 log. You can also specify file compression options, for example, mylog%i.log GZ or no log% i.log zip.

      For example, generate a log file every day and keep the log file for 30 days:

      <configuration> 
          <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> 
              <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 
                  <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> 
                  <maxHistory>30</maxHistory> 
              </rollingPolicy> 
              <encoder> 
                  <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> 
              </encoder> 
          </appender> 
      
          <root level="DEBUG"> 
              <appender-ref ref="FILE" /> 
          </root> 
      </configuration>
      

3.logger node

It is used to set the log printing level of a package or a specific class, and specify the appender.

It has a name attribute and two optional attributes, level and addtivity.

  • name: a package or class constrained by this logger
  • Level: set the log printing level, including TRACE, DEBUG, INFO, wrap, ERROR, ALL, OFF, etc. There is also a special value of INHERITED or the synonym NULL, which represents the level at which the superior is enforced. If this property is not set, the current logger will inherit the superior level.
  • addtivity: whether to pass print information to the superior logger. The default is true. It can contain zero or more elements, and the identifier will be added to the logger.

4.root node

It is essentially a logger node. The difference is that it is a top-level logger node and the root node of all logger nodes. There is only one level attribute, and the name attribute is declared as root by default.

  • Level: used to set the printing level, regardless of case: TRACE, DEBUG, INFO, WARN, ERROR, ALL and OFF. It cannot be set to included or the synonym NULL. The default is DEBUG.

Example: common logger configuration

<!--myibatis log configure-->
<logger name="com.apache.ibatis" level="TRACE"/>
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>

5.contextName node

Context node, used to set the name of the context. Each logger node is associated with this context. The default context is default and cannot be modified once set.

<contextName>case-concurrent</contextName>

6.property node

Define attribute k-v key value pairs, similar to HashMap.

It has two attributes, name and value, which are formulated as variable name and variable value respectively. Use ${} when referring to other parts of the configuration file.

<!--Define the storage address of the log file LogBack Relative paths are used in the configuration of-->
<property name="LOG_HOME" value="./logs/" />
<contextName>${LOG_NAME}</contextName>

7.timestamp node

Get the timestamp string, which has two attributes key and datePattern.

  • key: identifies the name of this timestamp
  • datePattern: set the format of the formatted time string, following Java txt. The format of simpledateformat.

For example:

<timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"/> 
<contextName>${bySecond}</contextName> 

3, Logback XML configuration example

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">

    <!--Define the storage address of the log file LogBack Relative paths are used in the configuration of-->
    <property name="LOG_HOME" value="/home" />

    <!--Console log, console output -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--Format output:%d Indicates the date,%thread Represents the thread name,%-5level: The level is displayed 5 characters wide from the left,%msg: Log messages,%n Is a newline character-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>

    <!--File log: generate log files every day -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--The file name of the log file output-->
            <FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--Log file retention days-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--Format output:%d Indicates the date,%thread Represents the thread name,%-5level: The level is displayed 5 characters wide from the left%msg: Log messages,%n Is a newline character-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--Maximum size of log file-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

    <!-- show parameters for hibernate sql For Hibernate customized -->
    <logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" />
    <logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" />
    <logger name="org.hibernate.SQL" level="DEBUG" />
    <logger name="org.hibernate.engine.QueryParameters" level="DEBUG" />
    <logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" />

    <!--myibatis log configure-->
    <logger name="com.apache.ibatis" level="TRACE"/>
    <logger name="java.sql.Connection" level="DEBUG"/>
    <logger name="java.sql.Statement" level="DEBUG"/>
    <logger name="java.sql.PreparedStatement" level="DEBUG"/>

    <!-- Log output level -->
    <root level="DEBUG">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE"/>
    </root>
</configuration>

4, Explain

  1. log level

    The behavior of the Logger is hierarchical: OFF, fat, ERROR, WARN, INFO, DEBUG, ALL or the level you define.
    Log4j recommends using only four levels. The priority from high to low is ERROR, WARN, INFO and DEBUG respectively. The one with high priority will be printed. (logback general)

Added by Karlos94 on Sun, 30 Jan 2022 17:29:30 +0200