SpringBoot uses log4j2 configuration


Log interface (slf4j)

slf4j is a specification, standard and interface formulated for all logging frameworks. It is not a specific implementation of a framework, because the interface cannot be used independently and needs to be used in conjunction with specific logging framework implementations (such as log4j and logback).

The interface is used to customize the specification and can have multiple implementations. When used, it is interface oriented (the imported packages are slf4j packages rather than specific packages in a log framework), that is, it interacts directly with the interface and does not use the implementation directly, so it can change the implementation at will without changing the log related code in the code.


Log implementation (log4j, logback, log4j2)

Log4j: an open source project of Apache, which can control the destination of log information transmission is console, files, GUI components, etc., and can control the output format of each log. These can be flexibly configured through a configuration file without modifying the application code. Although the maintenance has been stopped, most enterprises use log4j at present.

Logback: logback is also designed by the author of log4j. It has better features. It is a logging framework used to replace log4j and is the native implementation of slf4j.

Log4j2:log4j2 is an improved version of log4j 1.x and logback. It is said that some new technologies (lock free asynchrony, etc.) are adopted, which improves the throughput and performance of logs by 10 times compared with log4j 1.x. it also solves some deadlock bug s, and the configuration is more simple and flexible.


Configuration process

springboot uses the logging framework of logback by default, so you need to configure and exclude logback in pom. It should be noted here that logback is actually used in more than one place, so it should be uniformly excluded in the starter, and then log4j2 should be introduced.

POM documents involved

        <exclusion><!-- springboot The default is to use logback Of the log framework -->
<dependency> <!-- introduce log4j2 rely on -->  

Log4j2 configuration file, named log4j2.xml by default. The program will load automatically if it is named log4j2-xx.xml. You need to introduce this configuration file into the SpringBoot configuration file application.properties and add a line: logging.config=classpath:log4j2-xx.xml


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

<Configuration status="WARN" monitorInterval="1800">
    <!--Variable configuration-->
        <!--apply name-->
        <property name="APP_NAME">sky-hello</property>
        <!--Log storage path-->
        <property name="LOG_PATH">./logs/${APP_NAME}</property>
        <!--Log backup path-->
        <property name="LOG_BACKUP_PATH">${LOG_PATH}/backup</property>
        <!--Log output format-Console-->
        <property name="PATTERN_CONSOLE">%d{yyyy-MM-dd HH:mm:ss.SSS} | %blue{%traceId} | %highlight{%-5p} | %magenta{${sys:PID}} | %yellow{%t} | %cyan{%l} : %msg%n</property>
        <!--Log output format-file-->
        <property name="PATTERN_FILE">%d{yyyy-MM-dd HH:mm:ss.SSS} | %traceId | %-5p | ${sys:PID} | %t | %l : %msg%n</property>

    <!--Define log output destination, content, format, etc-->
        <!--Archived documents
            1. fileName: Log storage path
            2. filePattern: Historical log archive path. among%d{yyyy-MM-dd}Indicates that the time unit of the log is day,log4j2 automatic recognition  zip And other suffixes, indicating that the historical log needs to be compressed
        <RollingFile name="RollingFile" fileName="${LOG_PATH}/${APP_NAME}.log" filePattern="${LOG_BACKUP_PATH}/$${date:yyyy-MM}/${APP_NAME}-%d{yyyy-MM-dd}_%i.log.zip">
            <!--Format of output log, Do not set default to:%m%n-->
            <PatternLayout pattern="${PATTERN_FILE}"/>
            <!--Output only level And above( onMatch),Other direct rejection( onMismatch)-->
            <ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
            <!--Archive settings-->
                <!--Archive at intervals:
                    1. interval=time interval, Unit by filePattern of%d Date format assignment, The configuration here represents archiving once a day
                    2. modulate="true" Yes or no interval Taking the mold determines the time point of the next trigger
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
                <!-- According to the size of log file: size Indicates the maximum size of the current log file size,Supported by: KB/MB/GB-->
                <SizeBasedTriggeringPolicy size="50MB"/>
            <!-- Historical log configuration: If this attribute is not set, it defaults to starting to overwrite up to 7 files in the same folder-->
            <DefaultRolloverStrategy max="30"/>

        <!--Error information is archived separately-->
        <RollingFile name="RollingFileError" fileName="${LOG_PATH}/${APP_NAME}-error.log" filePattern="${LOG_BACKUP_PATH}/$${date:yyyy-MM}/${APP_NAME}-error-%d{yyyy-MM-dd}_%i.log.zip">
            <PatternLayout pattern="${PATTERN_FILE}"/>
            <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
                <SizeBasedTriggeringPolicy size="50MB"/>

    <!--Loggers to configure-->

        Attention points:
        1. logger Node is used to specify the form of log separately, for example, for the class Specify different log levels, etc:
           (1). name: Used to specify the logger The applicable class or the full path of the package where the class is located,Inherited from Root node.
           (2). AppenderRef: Associated Appender, Only defined logger And introduced appender,appender Will take effect
           (3). additivity: logEvent Transitivity of. true LogEvent Pass to parent after processing Logger Print. false LogEvent After processing, it will no longer be passed up to the parent Logger(Solve the problem of log duplicate output)
           (4). logger Configured level Must be higher than or equal to Appenders in ThresholdFilter Configured filtering level, Otherwise, information will be lost
        2. root Configure the root node of the log

        <!-- Synchronization log configuration-->
        <logger name="com.sky.hello.mapper" level="debug" additivity="false">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="RollingFile"/>
            <AppenderRef ref="RollingFileError"/>

        <root level="info">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="RollingFile"/>
            <AppenderRef ref="RollingFileError"/>




Used in code

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final Logger log = LoggerFactory.getLogger(this.getClass());


Tags: Spring

Posted by calmchess on Fri, 29 Jul 2022 21:57:02 +0530