A tutorial and a simple example of Log4j2 logging framework

1. Log4j2 tutorial

1.1 INTRODUCTION

The 1.x version of Log4j has been widely used in many applications, but due to memory leaks and other bug s, the code is difficult to maintain, as well as the disadvantages of using the old version of jdk, it was finished in August 2015. Its substitutes, SLF4J, Logback and Log4j2, have made many necessary improvements to the log framework.

There are many diary frameworks in history, such as:

Log4j: Apache Log4j is a Java based logging tool. It was initiated by Ceki G ü lc ü and is now a project of the Apache Software Foundation. Log4j is one of several Java logging frameworks.

Log4j2: Apache Log4j 2 is an upgrade product of log4j developed by apache.

Commons Logging: the project of Apache foundation is a set of Java logging interface, formerly known as Jakarta Commons Logging, and later renamed Commons Logging.

Slf4j: similar to Commons Logging, it is a set of simple java log facade, and has no log implementation. (Simple Logging Facade for Java, slf4j for short).

Logback: the implementation of a set of log components (Slf4j camp).

Jul(Java Util Logging): the official logging implementation since Java 1.4.

1.2 installation

The following jar packages need to be introduced to use the Log4j2 logging framework in development:

log4j-api-2.13.0.jar
log4j-core-2.13.0.jar

Here, Maven is used for installation. The pom.xml configuration file is as follows:

<properties>
    <logging.log4j.version>2.13.0</logging.log4j.version>
</properties>

<dependencies>
    <!-- Log4j2 Logging framework -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>${logging.log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>${logging.log4j.version}</version>
    </dependency>
</dependencies>

1.3 configuration file

In the src root directory of the project, create the log4j2.xml configuration file. The configuration information is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!-- log4j2 configuration file -->
<!-- log level trace<debug<info<warn<error<fatal -->
<configuration status="debug">
    <!-- Custom properties -->
    <Properties>
        <!-- Log format(Console) -->
        <Property name="pattern1">[%-5p] %d %c - %m%n</Property>
        <!-- Log format(file) -->
        <Property name="pattern2">
            =========================================%n Log level:%p%n Log time:%d%n Class name:%c%n Thread:%t%n Log information:%m%n
        </Property>
        <!-- log file path -->
        <Property name="filePath">logs/myLog.log</Property>
    </Properties>

    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="${pattern1}"/>
        </Console>
        <RollingFile name="RollingFile" fileName="${filePath}"
                     filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout pattern="${pattern2}"/>
            <SizeBasedTriggeringPolicy size="5 MB"/>
        </RollingFile>
    </appenders>
    <loggers>
        <root level="debug">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFile"/>
        </root>
    </loggers>
</configuration>

The log level from low to high is trace < debug < info < WARN < error < fatal. If it is set to WARN, the information below WARN will not be output. The same applies to the definition of level in Loggers.

The following is the appendix configuration, which can be understood as the output destination of the log. Here, an appendix of type Console is configured, that is, output to the Console. The PatternLayout in the Console node defines the format when the log is output.

Conversion mode provided by Log4j:

%m outputs the message specified in the code.

%p output priority, that is, debug, info, warn, error, fat.

%r input the number of milliseconds from the start of the application to the output of the log information.

%c output belongs to the category, usually the full name of the class.

%Tput the name of the thread that generated the log event.

%N output a carriage return line feed character, Windows platform is "\ r\n", Unix platform is "\ n".

%D output the date or time of the log time point. The default format is ISO8601. You can also specify the format after it, such as:% d{dd MMM yyyy HH:mm:ss,SSS}. The output is similar to: 02 Nov 2012 14:34:02781).

%l the location of the output log event, including the category name, the thread occurred, and the number of lines in the code, such as: Testlog.main(TestLog.java:10).

The name of the file where the% F output log message was generated.

%Line number in the L output code.

%x output and the NDC (nested diagnostic environment) associated with the current thread, such as java servlets multi client multi thread applications.

%%Output a "%" character.

Finally, there is the configuration of the Logger. There is only one Root Logger configured here.

1.4 test code

public static void main(String[] args)
{
    Logger logger = LogManager.getLogger(LogFunction.class);
    logger.trace("trace level");
    logger.debug("debug level");
    logger.info("info level");
    logger.warn("warn level");
    logger.error("error level");
    logger.fatal("fatal level");
}

 

2. Details of Log4j2 configuration file log4j2.xml

The following content is reprinted to: prepared by ah Hao chat Talk about log4j2 configuration file log4j2.xml

2.1 complete configuration solution

1. About the name of the configuration file and its storage location in the project

Log4j version 2.x no longer supports the file configuration mode like the. properties suffix in 1.x. the suffix name of configuration file in 2.x version can only be ". XML", "JSON" or ". jsn". The priority (from first to last) of the system selection profile is as follows:

(1) A file named log4j2-test.json or log4j2-test.jsn under. Classpath.

(2) The file named log4j2-test.xml under. Classpath.

(3) A file named log4j2.json or log4j2.jsn under. Classpath.

(4) A file named log4j2.xml under. Classpath.

We usually use log4j2.xml for naming by default. If you want to test locally, you can put log4j2-test.xml in the classpath, and the formal environment uses log4j2.xml, so you don't need to pack log4j2-test.xml when you pack and deploy.

2. Default configuration file

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    </Console>
</Appenders>
<Loggers>
    <Root level="error">
        <AppenderRef ref="Console" />
    </Root>
</Loggers>
</Configuration>

3. Profile node analysis

(1) The root node Configuration has two properties: status and monitorinterval. There are two child nodes: Appenders and loggers (indicating that multiple Appenders and loggers can be defined).

status is used to specify the level of print logs for log4j itself.

monitorinterval is used to specify the monitoring interval time of log4j automatic reconfiguration. The unit is s, and the minimum is 5s.

(2) The Appenders node has three common sub nodes: Console, RollingFile, and File.

The Console node is used to define the Appender output to the Console.

Name: Specifies the name of the Appender.

target: system out or system err. Generally, only the default: system out is set.

PatternLayout: output format, not set default to:% m%n.

The File node is used to define the Appender of the File output to the specified location.

Name: Specifies the name of the Appender.

fileName: Specifies the fileName with full path to the destination file of the output log.

PatternLayout: output format, not set default to:% m%n.

The RollingFile node is used to define the automatic deletion of old and new Appender s beyond the specified size.

Name: Specifies the name of the Appender.

fileName: Specifies the fileName with full path to the destination file of the output log.

PatternLayout: output format, not set default to:% m%n.

filePattern: Specifies the name format of the new log file.

Policies: Specifies the rolling log policy, that is, when to create a new log file to output the log.

Timebasedtriggingpolicy: a child node of Policies. It is a time-based scrolling policy. The interval attribute is used to specify how often to scroll. The default value is 1 hour. modulate=true is used to adjust the time: for example, it's 3am in the morning, interval is 4, so the first roll is 4am, then 8am, 12am... Instead of 7am.

Sizebased triggingpolicy: a child node of Policies. Based on the rolling policy of specified file size, the size attribute is used to define the size of each log file.

Defaultrollover strategy: used to specify that when there are at most several log files in the same folder, delete the oldest one and create a new one (through the max attribute).

(3) There are two common types of Loggers: Root and Logger.

The Root node is used to specify the Root log of the project. If the Logger is not specified separately, the Root log output will be used by default.

Level: log output level, with a total of 8 levels, from low to high: All < trace < debug < Info < Warn < error < fatal < OFF.

AppenderRef: the child node of Root, which specifies which Appender the log is output to.

The Logger node is used to specify the form of logs separately, such as specifying different log levels for the class es under the specified package.

Level: log output level, with a total of 8 levels, from low to high: All < trace < debug < Info < Warn < error < fatal < OFF.

name: used to specify the full path of the applicable class or package of the Logger, inherited from the Root node.

AppenderRef: the sub node of the Logger, which is used to specify which Appender the log is output to. If it is not specified, it will inherit from Root by default. If it is specified, it will be output in both the specified Appender and the Root's Appender. At this time, we can set the additivity="false" of the Logger to output only in the custom Appender.

(4) About log level.

There are 8 levels, from low to high: All < trace < debug < info < warn < error < fatal < OFF.

All: lowest level, used to turn on all logging.

Trace: it's trace. If the program is pushed forward, you can write a trace output, so there should be many traces, but it doesn't matter. We can set the minimum log level to prevent it from outputting.

Debug: pointing out that fine-grained information events are very helpful for debugging an application.

Info: the message highlights the running process of the application at a coarse-grained level.

Warn: output warnings and logs below warn.

Error: output error information log.

Fatal: output the log that each serious error event will cause the application to exit.

OFF: the highest level, used to turn OFF all logging.

The program will print logs higher than or equal to the set level. The higher the set log level, the less logs will be printed out.

4. Relatively complete log4j2.xml configuration template

Configuration template 1:

<?xml version="1.0" encoding="UTF-8"?>
<!--Log level and priority sorting: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration Hinder status,This is used to set log4j2 The internal information output of itself can not be set when it is set to trace When you see log4j2 Various internal detailed output-->
<!--monitorInterval: Log4j It can automatically detect and modify the configuration file and reconfigure itself, and set the interval in seconds-->
<configuration status="WARN" monitorInterval="30">
    <!--Define all first appender-->
    <appenders>
        <!--Configuration of this output console-->
        <console name="Console" target="SYSTEM_OUT">
            <!--Format of output log-->
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </console>
        <!--The file will print out all the information, this log Every time the program is run, it will be automatically cleared by append Attribute determination, which is also very useful, suitable for temporary testing-->
        <File name="log" fileName="log/test.log" append="false">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </File>
        <!-- This will print all info And below, each time the size exceeds size,Then this size Size logs are automatically saved by year-The folder created in the month is compressed as an archive-->
        <RollingFile name="RollingFileInfo" fileName="${sys:user.home}/logs/info.log"
                     filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <!--Console output only level And above( onMatch),Other direct rejection( onMismatch)-->
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        </RollingFile>
        <RollingFile name="RollingFileWarn" fileName="${sys:user.home}/logs/warn.log"
                     filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
            <!-- DefaultRolloverStrategy If the property is not set, the default value is at most 7 files in the same folder. Here, 20 files are set -->
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
        <RollingFile name="RollingFileError" fileName="${sys:user.home}/logs/error.log"
                     filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        </RollingFile>
    </appenders>
    <!--Then define logger,Only defined logger And introduced appender,appender It will take effect.-->
    <loggers>
        <!--Filter out spring and mybatis Some useless DEBUG information-->
        <logger name="org.springframework" level="INFO"></logger>
        <logger name="org.mybatis" level="INFO"></logger>
        <root level="all">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFileInfo"/>
            <appender-ref ref="RollingFileWarn"/>
            <appender-ref ref="RollingFileError"/>
        </root>
    </loggers>
</configuration>

Configuration template II:

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

    <!--Global parameter-->
    <Properties>
        <Property name="pattern">%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n</Property>
        <Property name="logDir">/data/logs/dust-server</Property>
    </Properties>

    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="console"/>
            <AppenderRef ref="rolling_file"/>
        </Root>
    </Loggers>

    <Appenders>
        <!-- Define output to console -->
        <Console name="console" target="SYSTEM_OUT" follow="true">
            <!--Console output only level And above-->
            <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout>
                <Pattern>${pattern}</Pattern>
            </PatternLayout>
        </Console>
        <!-- From the same source Appender Multiple can be defined RollingFile,Define daily log storage -->
        <RollingFile name="rolling_file"
                     fileName="${logDir}/dust-server.log"
                     filePattern="${logDir}/dust-server_%d{yyyy-MM-dd}.log">
            <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout>
                <Pattern>${pattern}</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1"/>
            </Policies>
            <!-- Log retention policy, configured for seven days only -->
            <DefaultRolloverStrategy>
                <Delete basePath="${logDir}/" maxDepth="1">
                    <IfFileName glob="dust-server_*.log" />
                    <IfLastModified age="7d" />
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>
    </Appenders>
</Configuration>

2.2 custom profile location

log4j2 finds the configuration file in classpath by default, and you can modify the location of the configuration file. In a non web project:

public static void main(String[] args) throws IOException
{
    File file = new File("D:/log4j2.xml");
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    final ConfigurationSource source = new ConfigurationSource(in);
    Configurator.initialize(null, source);

    Logger logger = LogManager.getLogger("mylog");
}

If it is a web project, add:

<context-param>
    <param-name>log4jConfiguration</param-name>
    <param-value>/WEB-INF/conf/log4j2.xml</param-value>
</context-param>

<listener>
    <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>

Recommended tutorial

I recommend some good learning tutorials I found on the Internet:

Learning materials 1: Detailed explanation of log4j2 (I) - from foundation to actual combat

Learning materials 2: Detailed explanation of log4j2(2) - Async/MongoDB/Flume Appender distinguishes file output by log level

Learning materials 3: Talk about log4j2 configuration file log4j2.xml

 

3. A simple example of Log4j2

(1) Write pom.xml configuration file and introduce the jar package file of Log4j2. The complete configuration is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.pjb</groupId>
    <artifactId>log4j2-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <logging.log4j.version>2.13.0</logging.log4j.version>
    </properties>

    <dependencies>
        <!-- Log4j2 Logging framework -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${logging.log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${logging.log4j.version}</version>
        </dependency>
    </dependencies>

</project>

(2) In the src root directory of the project, create the log4j2.xml configuration file. The configuration information is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!-- log4j2 configuration file -->
<!-- log level trace<debug<info<warn<error<fatal -->
<configuration status="debug">
    <!-- Custom properties -->
    <Properties>
        <!-- Log format(Console) -->
        <Property name="pattern1">[%-5p] %d %c - %m%n</Property>
        <!-- Log format(file) -->
        <Property name="pattern2">
            =========================================%n Log level:%p%n Log time:%d%n Class name:%c%n Thread:%t%n Log information:%m%n
        </Property>
        <!-- log file path -->
        <Property name="filePath">logs/myLog.log</Property>
    </Properties>

    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="${pattern1}"/>
        </Console>
        <RollingFile name="RollingFile" fileName="${filePath}"
                     filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout pattern="${pattern2}"/>
            <SizeBasedTriggeringPolicy size="5 MB"/>
        </RollingFile>
    </appenders>
    <loggers>
        <root level="debug">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFile"/>
        </root>
    </loggers>
</configuration>

(3) Create a log function test class (LogFunction.java).

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Log function test class
 * @author pan_junbiao
 **/
public class LogFunction
{
    public static void main(String[] args)
    {
        Logger logger = LogManager.getLogger(LogFunction.class);
        logger.trace("trace level");
        logger.debug("debug level");
        logger.info("info level");
        logger.warn("warn level");
        logger.error("error level");
        logger.fatal("fatal level");
    }
}

Execution result:


 

 

357 original articles published, 210 praised, 1.66 million visitors+
His message board follow

Tags: log4j xml Apache Java

Posted on Fri, 14 Feb 2020 05:43:19 -0500 by dave_biscuits