Simple use of Logback log configuration

Introduction to Logback

Logback is another open source logging component designed by the founder of log4j. logback is currently divided into three modules: logback-core, logback-classic and logback-access. logback-core is the base module for the other two modules. logback-classic is an improved version of log4j. In addition, logback-classic fully implements the SLF4J API so that you can easily switch to other logging systems such as log4j or JDK14 Logging. The logback-access access module integrates with the servlet container to provide the function of accessing logs through Http.

Advantages of Logback

  1. Fast execution speed and small initial memory load;
  2. The SLF4J API is natively implemented, and no conversion is required;
  3. Simple configuration, and can adapt to a variety of environments;
  4. Expired logs can be deleted regularly;
  5. More powerful filters that don't have to generate a lot of logs by changing the log level;
  6. Can recover from IO errors;
  7. ....
    There are many other advantages of logback, and I will not list them one by one here. For details, you can view the official Api documentation.
    Address: https://logback.qos.ch/documentation.html

Logback configuration instructions

Regarding the configuration instructions of this piece, I will simply list some of the more commonly used configurations for explanation. If you want to know more, please see the official documentation.

Logback's Hierarchical Description

Simple hierarchical structure, there are actually more, just for reference.

configuration  
    root
    logger                     
    property                        
    appender 
        layout 
        rollingPolicy
           Pattern
           fileNamePattern
           maxFileSize
           maxHistory
           totalSizeCap

Specific instructions

The configuration root node generally has three attributes, scan, scanPeriod and debug.

  • scan: Whether to load automatically, the default is true.
  • scanPeriod: Monitor the modification time interval, the default is one minute.
  • debug: Whether to check the logback running status, the default is true.

So if we want to use this, we can configure it as follows:

<configuration  scan="true" scanPeriod="30 seconds" debug="true">
...
</configuration>

root and logger subnodes to specify the log level of the input.

  • root : This is the level that specifies the main log.
  • logger : This is the level of the specified custom log.

    Note : The log level specified by root is the log output by the class, for example:

  private static Logger LOG = LoggerFactory.getLogger(logbackTest.class);

The log level specified by logger is a custom level, for example:

private static Logger LOG2 = LoggerFactory.getLogger("oneInfo");

Their usage is as follows:

<logger name="oneInfo" level="DEBUG" additivity="false">
       <appender-ref ref="ONE_INFO" />
    </logger>
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE" />
    </root>

Note 2 : level is the level of log output, and additivity indicates whether to print the log on the console.

The property child node is generally used to define variable values. There are two attributes name and value. Similar to the key and value of Map in Java.

  • name: the name of the variable
  • value: the value of the variable

The usage is as follows:

<property name="LOG_HOME" value="logs/pcm"/>

Note: The file path specified by value will be automatically generated in the same level directory of the project, and there is no need to create it manually.

The appender child node, the component responsible for writing logs. There are two attributes, name and class.

  • name: custom name.
  • class: The fully qualified name corresponding to the custom name, which is the method used to output the log.

This is very important, and it can be said to be the core of logback. Simple usage is as follows:

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
</appender>

Description : Define a STDOUT name to output on the console.

Layout and Pattern are generally used together.

  • layout: formatted log information;
  • Pattern :layout child node, which defines the format of the output information;

    Simple usage is as follows:

<layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level - %msg%n
            </Pattern>
</layout>

Explanation : %d in the pattern in the pattern represents the output time format, %thread represents the output thread name, %-5level represents the character width, %msg represents the output information, and %n represents a newline.

rollingPolicy, fileNamePattern, maxFileSize, maxHistory, and totalSizeCap are generally used to roll logs, that is, log cutting management.

  • rollingPolicy: Determines the log rolling behavior, generally used for log cutting.
  • fileNamePattern: A necessary node, generally used to specify the path of the log file and the generation format.
  • maxFileSize: The maximum value of a single log file, after which it will be cut.
  • maxHistory: The maximum number of days to keep log files, that is, the expiration time.
  • totalSizeCap : The maximum size of the overall log file, after which no logs will be generated.

Simple usage is as follows:

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/mylog-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>
            <maxFileSize>10MB</maxFileSize>
            <maxHistory>31</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
    </appender>

Note : The configuration meaning of this section is that a log file is generated every day. If it exceeds 10M, the log will be cut, and one will be added to the name of the log file. The log file will be kept for a maximum of 31 days, and the maximum log file will be 10G in total.

Logback Instructions for Use

After a brief description of the logback log configuration file, let's simply use logback.
The use of logback.xml requires three jar packages, namely slf4j-api, logback-core, and logback-classic.
The mavan configuration is as follows:

<dependency>
     <groupId>org.slf4j</groupId>
     <artifactId>slf4j-api</artifactId>
     <version>1.7.25</version>
    </dependency>


    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>1.2.3</version>
    </dependency>

After successfully adding the dependency package in maven, let's write a simple demo to test it.
Define three log logs, one main log and two custom logs.
The overall configuration is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<configuration  scan="true" scanPeriod="30 seconds" debug="true">
    <property name="LOG_HOME" value="logs/pcm"/>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level - %msg%n
            </Pattern>
        </layout>
    </appender>
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/mylog-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>
            <maxFileSize>10MB</maxFileSize>
            <maxHistory>31</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level - %msg%n
            </Pattern>
        </layout>
    </appender>

    <appender name="ONE_INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- rollover daily -->
            <fileNamePattern>${LOG_HOME}/oneInfo/%d{yyyy-MM-dd}/oneInfo.%i.txt</fileNamePattern>
            <maxFileSize>10MB</maxFileSize>
            <maxHistory>31</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level - %msg%n
            </Pattern>
        </layout>
    </appender>

    <appender name="TWO_INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- rollover daily -->
            <fileNamePattern>${LOG_HOME}/twoInfo/%d{yyyy-MM-dd}/twoInfo.%i.txt</fileNamePattern>
            <maxFileSize>10MB</maxFileSize>
            <maxHistory>31</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level - %msg%n
            </Pattern>
        </layout>
    </appender>

    <logger name="oneInfo" level="DEBUG" additivity="false">
       <appender-ref ref="ONE_INFO" />
    </logger>
    <logger name="twoInfo" level="WARN" additivity="true">
       <appender-ref ref="TWO_INFO" />
    </logger>

    <root level="INFO">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE" />
    </root>

</configuration>

Then output in console output and in file respectively.
The java code example is as follows:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
* Title: logbackTest
* Description:
* logback日志测试 
* Version:1.0.0  
* @author pancm
* @date 2018年1月24日
 */
public class logbackTest {
    private static Logger LOG = LoggerFactory.getLogger(logbackTest.class);
    private static Logger LOG2 = LoggerFactory.getLogger("oneInfo");
    private static Logger LOG3 = LoggerFactory.getLogger("twoInfo");

    public static void main(String[] args) {
        test();
    }

    private static void test(){

        LOG.debug("主程序的debug");
        LOG.info("主程序的info");
        LOG.warn("主程序的warn");
        LOG.error("主程序的error");

        LOG2.debug("oneInfo的debug");
        LOG2.info("oneInfo的info");
        LOG2.warn("oneInfo的warn");
        LOG2.error("oneInfo的error");

        LOG3.debug("twoInfo的debug");
        LOG3.info("twoInfo的info");
        LOG3.warn("twoInfo的warn");
        LOG3.error("twoInfo的error");
    }

The output is as follows:

write picture description here

The log generation directory:
write picture description here

Description of the output result:

  • LOG: Because the set printing level is info, the debug level will not be printed.
  • LOG2: Because the custom configuration is set to additivity=”false”, it is not printed on the console. So none of them will be printed, but logs above the debug level can be viewed in logs/pcm/oneInfo.
  • LOG3: Because the custom configuration is set to additivity=”true”, it can be printed on the console. Therefore, two warning-level logs will be printed, and the logs can also be viewed in logs/pcm/oneInfo.

other

Reference:
https://logback.qos.ch/documentation.html
https://www.cnblogs.com/warking/p/5710303.html

At this point, the simple explanation of the logback log in this article is over, thank you for reading!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325478002&siteId=291194637