Log4j2 profile

Originally designed for auditing purposes, log4j2 is an upgrade of Log4j 1.x that makes some significant improvements by taking some good design from Logback and fixing some problems.

  • Log4j2 is a significant performance surrogate compared to log4J and LogBack.
  • Log4j2 can be automatically reloaded. After configuring parameters for log4j2, you can automatically reload the log4j2 configuration file without restarting the application.
  • Log4j2 can avoid deadlocks.

Log4j2 compared to other frameworks

It is clear that log4j2 performs better than the other logging frameworks, both synchronous and asynchronous, while the other logging frameworks do not.

Springboot integration Log4j2

This document uses only synchronous logs. Asynchronous logs are not described here. In actual cases, only info logs may be printed. Info logs include info-log, WARn-log, error-log, and fatal-log.

Pom depends on

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <! Springboot = log ();
            <exclusions>
                <exclusion>
                    <artifactId>spring-boot-starter-logging</artifactId>
                    <groupId>org.springframework.boot</groupId>
                </exclusion>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <! Add springBoot log4j2 dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
</dependencies>
Copy the code

Application. The properties configuration

logging.config=classpath:log4j2-spring.xml
Copy the code

Log4j2-spring. XML file configuration

<?xml version="1.0" encoding="UTF-8"? >
<! -- Log levels and priorities: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<! If log4j2 is traced, you will see the details of the internal output of log4j2 -->
<! --monitorInterval: Log4j automatically detects changes to configuration files and reconfigures itself, sets the interval -->
<configuration status="WARN" monitorInterval="30">
    <! This configuration will export logs to the specified folder in the tomcat root directory.
    <properties>
        <property name="LOG_HOME">./WebAppLogs/logs</property>
    </properties>
    <! Define all appenders -->
    <appenders>
        <! -- Priority levels are OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
        <! -- Match: Match: DENY: Mismatch: ACCEPT: Match -->
        <! -- DENY, logs are immediately discarded and no longer pass through other filters; NEUTRAL, the next filter in the sequence table passes and then processes the log; ACCEPT, the log will be processed immediately and will not pass through the remaining filters. -->
        <! -- Log output format %d{YYYY-MM-DD HH: MM: SS, SSS} : log production time % P: log output format % C: logger name %m: log content, that is, logger.info("message") %n: Newline %C: Name of the Java class %L: number of the log output line %M: name of the log output method hostName: name of the local machine hostAddress: local IP address -->
        <! -- Configuration of the output console -->
        <console name="Console" target="SYSTEM_OUT">
            <! -- Output log format -->
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{1.} - %m%n"/>
            <! --<PatternLayout pattern="[%d{HH:mm:ss:SSS}] - (%F:%l) - %m%n"/>-->
            <! --<PatternLayout pattern="[%d{HH:mm:ss:SSS}] (%F:%L) %m%n" />-->
        </console>
        <! -- This will print all the info level and below information, each time the size of the log exceeds the size, the size of the log will be automatically saved in the folder created by year and month and compressed, as an archive.
        <! -- TRACE level log; Log files are stored in a separate folder. The date format cannot be a colon or it will not generate because the file name does not allow colons. This appender only outputs trace data to trace.log -->
        <RollingFile name="RollingFileTrace" immediateFlush="true" fileName="${LOG_HOME}/trace.log"
                     filePattern="${LOG_HOME}/trace_%d{yyyy-MM-dd-HH}-%i.log.zip">
            <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
            <! -- DefaultRolloverStrategy default to a maximum of 7 files in the same folder
            <DefaultRolloverStrategy max="20">
                <! Age = 'HH'; age = 'HH'; xd = 'HH'; age = 'HH' -->
                <Delete basePath="${LOG_HOME}" maxDepth="2">
                    <IfFileName glob="trace_*.zip"/>
                    <! FilePattern = filePattern
                    <! -- If filePattern is yyyY-MM-DD-hh: MM :ss, age can also be 5s, indicating that the log survival time is 5s -->
                    <IfLastModified age="168H"/>
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>

        <RollingFile name="RollingFileDebug" immediateFlush="true" fileName="${LOG_HOME}/debug.log"
                     filePattern="${LOG_HOME}/debug_%d{yyyy-MM-dd-HH}-%i.log.zip">
            <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="20">
                <Delete basePath="${LOG_HOME}" maxDepth="2">
                    <IfFileName glob="debug_*.zip"/>
                    <IfLastModified age="168H"/>
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>

        <! -- info Log configuration -->
        <RollingFile name="RollingFileInfo" immediateFlush="true" fileName="${LOG_HOME}/info.log"
                     filePattern="${LOG_HOME}/info_%d{yyyy-MM-dd-HH}-%i.log.zip">
            <! -- Console only outputs messages of level and above (onMatch).
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="20">
                <Delete basePath="${LOG_HOME}" maxDepth="2">
                    <IfFileName glob="info_*.zip"/>
                    <IfLastModified age="168H"/>
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>

        <! -- WARN log configuration -->
        <RollingFile name="RollingFileWarn" immediateFlush="true" fileName="${LOG_HOME}/warn.log"
                     filePattern="${LOG_HOME}/warn_%d{yyyy-MM-dd-HH}-%i.log.zip">
            <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="20">
                <Delete basePath="${LOG_HOME}" maxDepth="2">
                    <IfFileName glob="warn_*.zip"/>
                    <IfLastModified age="168H"/>
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>

        <! -- Error log configuration -->
        <RollingFile name="RollingFileError" immediateFlush="true" fileName="${LOG_HOME}/error.log"
                     filePattern="${LOG_HOME}/error_%d{yyyy-MM-dd-HH}-%i.log.zip">
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="20">
                <Delete basePath="${LOG_HOME}" maxDepth="2">
                    <IfFileName glob="error_*.zip"/>
                    <IfLastModified age="168H"/>
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>
    </appenders>
    <! An appender will not work until logger is defined and appender is appended.
    <loggers>
        <! -- Filter out spring and Mybatis DEBUG messages -->
        <logger name="org.springframework" level="INFO"/>
        <logger name="org.mybatis" level="INFO"/>
        <root level="all">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFileDebug"/>
            <appender-ref ref="RollingFileTrace"/>
            <appender-ref ref="RollingFileInfo"/>
            <appender-ref ref="RollingFileWarn"/>
            <appender-ref ref="RollingFileError"/>
        </root>
    </loggers>
</configuration>
Copy the code

Info-log log4j2-spring.xml configuration file only

<?xml version="1.0" encoding="UTF-8"? >
<! -- Log levels and priorities: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<! If log4j2 is traced, you will see the details of the internal output of log4j2 -->
<! --monitorInterval: Log4j automatically detects changes to configuration files and reconfigures itself, sets the interval -->
<configuration status="WARN" monitorInterval="30">
    <! This configuration will export logs to the specified folder in the tomcat root directory.
    <properties>
        <property name="LOG_HOME">./WebAppLogs/logs</property>
    </properties>
    <! Define all appenders -->
    <appenders>
        <! -- Configuration of the output console -->
        <console name="Console" target="SYSTEM_OUT">
            <! -- Output log format -->
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{1.} - %m%n"/>
            <! --<PatternLayout pattern="[%d{HH:mm:ss:SSS}] - (%F:%l) - %m%n"/>-->
            <! --<PatternLayout pattern="[%d{HH:mm:ss:SSS}] (%F:%L) %m%n" />-->
        </console>
        <! -- This will print all the info level and below information, each time the size of the log exceeds the size, the size of the log will be automatically saved in the folder created by year and month and compressed, as an archive.
        <! -- info Log configuration -->
        <RollingFile name="RollingFileInfo" immediateFlush="true" fileName="${LOG_HOME}/info.log"
                     filePattern="${LOG_HOME}/info_%d{yyyy-MM-dd-HH}-%i.log.zip">
            <! -- Console only outputs messages of level and above (onMatch).
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="20">
                <Delete basePath="${LOG_HOME}" maxDepth="2">
                    <IfFileName glob="info_*.zip"/>
                    <IfLastModified age="168H"/>
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>
    </appenders>
    <! An appender will not work until logger is defined and appender is appended.
    <loggers>
        <! -- Filter out spring and Mybatis DEBUG messages -->
        <logger name="org.springframework" level="INFO"/>
        <logger name="org.mybatis" level="INFO"/>
        <root level="all">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFileInfo"/>
        </root>
    </loggers>
</configuration>
Copy the code

Logging implementation – SLf4J (LogFactory)

public class LogUtil {

    /** * Debug level log output *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void debug(Class clazz, String msg, Object... params) {
        Logger logger = LoggerFactory.getLogger(clazz.getName());
        logger.debug(msg, params);
    }

    /** * Trace log output *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void trace(Class clazz, String msg, Object... params) {
        Logger logger = LoggerFactory.getLogger(clazz.getName());
        logger.trace(msg, params);
    }

    /** * info level log output *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void info(Class clazz, String msg, Object... params) {
        Logger logger = LoggerFactory.getLogger(clazz.getName());
        logger.info(msg, params);
    }

    /** * WARN logs are generated *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void warn(Class clazz, String msg, Object... params) {
        Logger logger = LoggerFactory.getLogger(clazz);
        logger.warn(msg, params);
    }

    /** * Error level log output *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void error(Class clazz, String msg, Object... params) { Logger logger = LoggerFactory.getLogger(clazz); logger.error(msg, params); }}Copy the code

Logging implementation Log4j(LogManager)

public class LogUtilManager {
    /** * Debug level log output *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void debug(Class clazz, String msg, Object... params) {
        Logger logger = LogManager.getLogger(clazz.getName());
        logger.debug(msg, params);
    }

    /** * Trace level log output *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void trace(Class clazz, String msg, Object... params) {
        Logger logger = LogManager.getLogger(clazz.getName());
        logger.trace(msg, params);
    }

    /** * info level log output *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void info(Class clazz, String msg, Object... params) {
        Logger logger = LogManager.getLogger(clazz.getName());
        logger.info(msg, params);
    }

    /** * WARN logs are generated *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void warn(Class clazz, String msg, Object... params) {
        Logger logger = LogManager.getLogger(clazz);
        logger.warn(msg, params);
    }

    /** * Error level log output *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void error(Class clazz, String msg, Object... params) {
        Logger logger = LogManager.getLogger(clazz);
        logger.error(msg, params);
    }

    /** * fatal log *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void fatal(Class clazz, String msg, Object... params) { Logger logger = LogManager.getLogger(clazz); logger.fatal(msg, params); }}Copy the code

Calls to both implementations

void testLog(a) {
    LogUtil.info(ConfigApplicationTests.class, "this is logfactory info log");
    LogUtilManager.info(ConfigApplicationTests.class, "this is logmanager info log");
}
Copy the code

Log output

conclusion

This article summarizes the springboot integration log4j2, of course, the actual business situation also has logback+ SLF4J and other ways to achieve log4J2 in all aspects of excellent performance.

Refer to the article

  • [1]. A chat log4j2 log4j2.xml.www.cnblogs.com/hafiz/p/617 configuration file…
  • [2]. Log4j2 log configuration file, Log4j2. The XML file configuration. www.cnblogs.com/hyyq/p/7171…
  • [3]. Log4j website. Logging.apache.org/log4j/2.x/i…