Log4j2日志记录框架的使用教程与简单实例

1, Log4j2 use of tutorials

1.1 Introduction

Although the Log4j version 1.x has been widely used in many applications, but due to memory leaks and other bug appears, the code is difficult to maintain, and the need to use the old version of jdk and other disadvantages, already comes to an end in August 2015. Its alternatives, SLF4J, Logback, Log4j2 logging framework do a lot of the necessary improvements.

There have been many in the history of the diary framework, such as:

Log4j: the Apache Log4j is a Java-based logging tool. It is made Ceki Gülcü's first, now it is a project of the Apache Software Foundation. Log4j is one of several Java logging framework.

Log4j2: the Apache Log4j 2 is an upgrade apache development of a Log4j.

Commons Logging: the project belongs to the Apache Foundation, the log is a set of Java interfaces, before calling Jakarta Commons Logging, later renamed the Commons Logging.

Slf4j: similar to the Commons Logging, is a simple Java logging facade, to realize itself has no log. (Simple Logging Facade for Java, abbreviation Slf4j).

Logback: to achieve a set of log components (Slf4j camp).

Jul (Java Util Logging): Since the official journal Java1.4 achieved.

1.2 Installation

Use Log4j2日志记录框架需要引入的 jar package as in development:

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

As used herein, Maven installation, pom.xml configuration file as follows:

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

<dependencies>
    <!-- Log4j2日志记录框架 -->
    <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 files

In the src root directory of the project, create log4j2.xml profile. Configuration information is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!-- log4j2 配置文件 -->
<!-- 日志级别 trace<debug<info<warn<error<fatal -->
<configuration status="debug">
    <!-- 自定义属性 -->
    <Properties>
        <!-- 日志格式(控制台) -->
        <Property name="pattern1">[%-5p] %d %c - %m%n</Property>
        <!-- 日志格式(文件) -->
        <Property name="pattern2">
            =========================================%n 日志级别:%p%n 日志时间:%d%n 所属类名:%c%n 所属线程:%t%n 日志信息:%m%n
        </Property>
        <!-- 日志文件路径 -->
        <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 logging level from low to high into TRACE <DEBUG <INFO <WARN <ERROR <FATAL, if set to WARN, the information will not be lower than the WARN output. For Loggers in level definitions apply.

The following is Appender configuration, as will be appreciated Appender log output destination, where the configuration of a Console Appender type, is output to the console. Console PatternLayout node defines the format when the output log.

Log4j provides conversion mode:

% M output code specified in the message.

% P output priority, i.e. DEBUG, INFO, WARN, ERROR, FATAL.

% R output from the application starts to output the log information on the number of milliseconds spent.

Category% c output belongs, where usually the full name of the class.

% T thread name of the output generated log events.

Output% n Enter a newline, Windows platform "\ r \ n", Unix platform "\ n".

Date or time% d log output time points, the default format is ISO8601, you can specify the format Thereafter, as:% d {dd MMM yyyy HH: mm: ss, SSS}, similar output: 02 Nov 2012 14:34 : 02,781).

% L occurrence position output log events, including category names, place of threads, and the number of lines in the code, such as: Testlog.main (TestLog.java:10).

 File name where output is generated% F log messages.

% L output line number code.

NDC% x output and associated with the current thread (nested diagnostic context), applications like java servlets multi-client multi-threaded.

%% outputs a "%" character.

Finally Logger configuration, here is configured with only a Root Logger.

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, Log4j2 Detailed profiles log4j2.xml

To reprint the following: Ahao chat dry written "chat log4j2 profile log4j2.xml"

2.1 Configuration whole solution

1. The storage location of the configuration file name as well as in the project

log4j 2.x versions are no longer supported image file configuration .properties suffix in 1.x, 2.x version of the configuration file extension can only be ".xml", ". json" or ".jsn". Profile system selection priority (oldest first) as follows:

(1) file name or log4j2-test.json log4j2-test.jsn under .classpath.

(2) file named log4j2-test.xml under .classpath.

(3) .classpath under the file name or log4j2.jsn of log4j2.json.

(4) .classpath under the file named log4j2.xml.

We generally use log4j2.xml named default. If you want to test locally, you can put log4j2-test.xml into the classpath, and formal environments log4j2.xml, then the deployment package when not packed log4j2-test.xml can be.

2. The default default profile

<?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. The node configuration file parsing    

(1) Configuration root node has two attributes: status and monitorinterval, there are two child nodes: Appenders and Loggers is (Appender show can be defined, and a plurality Logger).

        status is used to specify the level of log4j own print log.

        Monitoring interval monitorinterval log4j specifies automatic reconfiguration unit is s, the minimum is 5s.

(2) Appenders node , there are three common seed node: Console, RollingFile, File.

        Console node is used to define the output Appender console.

        name: Name of Appender.

        target: SYSTEM_OUT or SYSTEM_ERR, generally set the default: SYSTEM_OUT.

        PatternLayout: output format is not set by default:% m% n.

        File nodes Appender used to define the location to the specified file.

        name: Name of Appender.

        fileName: specify the output file name of the destination log file with full path.

        PatternLayout: output format is not set by default:% m% n.

        RollingFile node used to define more than the specified size are automatically deleted in the new Appender old creation.

        name: Name of Appender.

        fileName: specify the output file name of the destination log file with full path.

        PatternLayout: output format is not set by default:% m% n.

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

        Policies: Specifies the log rolling strategy is when to create a new log file output log.

        TimeBasedTriggeringPolicy: Policies child node, based on a rolling strategy time, interval attribute is used to specify how often rolling once, the default is 1 hour. modulate = true is used to adjust the time: for example, now is the morning 3 am,interval is 4, then rolling in the first 4am, followed by 8 am,12am ... instead of 7am.

        SizeBasedTriggeringPolicy: Policies child node, based on a rolling policy specifies the file size, size attribute is used to define the size of each log file.

        DefaultRolloverStrategy: used to specify the start deleting the oldest when the same folder with up to several log files, create new (by max attribute).

(3) Loggers node, there are two common: Root and Logger.

        Root node to the root log specified item, if no separate Logger, it will use the default log output Root.

        level: the log output levels, a total of eight levels, from low to high in accordance with: All <Trace <Debug <Info <Warn <Error <Fatal <OFF.

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

       Logger node specifies a separate log form, for example, to specify a different logging level as the class specified in the packet.

        level: the log output levels, a total of eight levels, from low to high in accordance with: All <Trace <Debug <Info <Warn <Error <Fatal <OFF.

        name: Logger used to specify the class or package applies the full path to where the class inherits from the Root node.

        AppenderRef: Logger child node, is used to specify the log output to Appender which, if not specified, the default will be inherited from the Root If specified, then the output will be specified in Appender this Appender and Root in this case us. Logger may be provided to additivity = "false" is output only from the Appender defined.

(4) on the log level.

        Eight levels, from low to high in accordance with: All <Trace <Debug <Info <Warn <Error <Fatal <OFF.

        All: the lowest level, to open all logging.

        Trace: a track, is to promote the program, you can write trace output, so the trace should be particularly large, but that's okay, we can not let him set the minimum log level output.

        Debug: fine-grained information about the event pointed to debug an application is very helpful.

        Info: Message in a coarse-grained level to highlight the process of running the application.

        Warn: Warnings and warn the output level of the log.

        Error: error message log output.

        Fatal: The output of each event will lead to serious error log to exit the application.

        OFF: the highest level for close all logging.

The program will print higher than or equal to the set level log, the log level is set higher, the less printed journal .

4. Compare the complete configuration template log4j2.xml

A configuration template:

<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出-->
<!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
<configuration status="WARN" monitorInterval="30">
    <!--先定义所有的appender-->
    <appenders>
        <!--这个输出控制台的配置-->
        <console name="Console" target="SYSTEM_OUT">
            <!--输出日志的格式-->
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </console>
        <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用-->
        <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>
        <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
        <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">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(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属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
            <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>
    <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
    <loggers>
        <!--过滤掉spring和mybatis的一些无用的DEBUG信息-->
        <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">

    <!--全局参数-->
    <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>
        <!-- 定义输出到控制台 -->
        <Console name="console" target="SYSTEM_OUT" follow="true">
            <!--控制台只输出level及以上级别的信息-->
            <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout>
                <Pattern>${pattern}</Pattern>
            </PatternLayout>
        </Console>
        <!-- 同一来源的Appender可以定义多个RollingFile,定义按天存储日志 -->
        <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>
            <!-- 日志保留策略,配置只保留七天 -->
            <DefaultRolloverStrategy>
                <Delete basePath="${logDir}/" maxDepth="1">
                    <IfFileName glob="dust-server_*.log" />
                    <IfLastModified age="7d" />
                </Delete>
            </DefaultRolloverStrategy>
        </RollingFile>
    </Appenders>
</Configuration>

2.2 custom configuration file location

Find log4j2 default configuration file in the classpath, you can modify the location of the configuration file. In 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 a web project, in web.xml added:

<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 a few find online, write a good tutorial:

Learning materials 1: "Detailed log4j2 (on) - From Fundamentals to combat"

Learning materials 2: "Detailed log4j2 (lower) - Async / MongoDB / Flume Appender according to the log file output level to distinguish"

Learning materials 3: "chat log4j2 profile log4j2.xml"

 

Simple Example 3, Log4j2 of

(1) preparation of pom.xml profile, introducing Log4j2 jar package file, 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日志记录框架 -->
        <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 log4j2.xml profile. Configuration information is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!-- log4j2 配置文件 -->
<!-- 日志级别 trace<debug<info<warn<error<fatal -->
<configuration status="debug">
    <!-- 自定义属性 -->
    <Properties>
        <!-- 日志格式(控制台) -->
        <Property name="pattern1">[%-5p] %d %c - %m%n</Property>
        <!-- 日志格式(文件) -->
        <Property name="pattern2">
            =========================================%n 日志级别:%p%n 日志时间:%d%n 所属类名:%c%n 所属线程:%t%n 日志信息:%m%n
        </Property>
        <!-- 日志文件路径 -->
        <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;

/**
 * 日志功能测试类
 * @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");
    }
}

Results of the:


 

 

Published 357 original articles · won praise 210 · Views 1.66 million +

Guess you like

Origin blog.csdn.net/pan_junbiao/article/details/104313938
Recommended