The use of log4j2 in the project

download address of log4j2

Apache's log component official website: http://logging.apache.org/
log4j2 download (provided windows download address, other versions or linux versions please go to the official website): http://mirrors.tuna.tsinghua.edu.cn /apache/logging/log4j/2.11.2/apache-log4j-2.11.2-bin.zip
There are many jar packages after decompression, only two

log4j-api-2.11.2.jar
log4j-core-2.11.2.jar

Use of log4j2 in maven project

  1. Create a maven project
    Insert picture description here2. Add dependencies (search in the maven warehouse and log4j2 official documents)
    <dependencies>
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.11.2</version>
      </dependency>
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.11.2</version>
      </dependency>
    </dependencies>
  1. Add configuration file (add log4j2.xml in the resources directory)

 Here is a simple configuration file. Compared with the previous log4j configuration file, the structure is clearer. The following is just the configuration of an appender and a root logger.

<?xml version="1.0" encoding="utf-8" ?>
<!--
    status属性:查看log4j的装配过程,值为OFF表示关闭,值为debug等日志级别为查看日志过程
-->
<configuration status="OFF">
    <!--定义附加器,需要在appender标签中定义-->
    <Appenders>
        <!--
            name属性:定义追加器的标识名称
            target:定义输出日志形式    SYSTEM_OUT/SYSTEM_ERR
        -->
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[log4j2-demo]  %-d{yyyy-MM-dd HH-mm-ss.SSS} [%-5p] %C:%L  %m%n"/>
        </Console>
    </Appenders>
    
    <Loggers>
        <!-- 定义根日志 -->
        <!-- level : 指定根日志的日志输出级别 -->
        <Root level="info">
            <!-- 引用日志追加器,和上面定义的追加器的名称一样-->
            <AppenderRef ref="console"/>
        </Root>
    </Loggers>

</configuration>
  1. Runtime class
public class log4j2demo {
    
    

    public static void main(String[] args) {
    
    
        Logger logger = LogManager.getLogger(log4j2demo.class);

        logger.fatal("this is fatal message");
        logger.error("this is error message");
        logger.warn("this is warn message");
        logger.info("this is info message");
        logger.debug("this is debug message");
        logger.trace("this is trace message");
    }
}

4. Running results If
configuration is wrong or not configured, press 默认的配置output, similar results are as follows

ERROR StatusLogger No Log4j 2 configuration file found. Using default configuration (logging only errors to the console).......
10:39:49.129 [main] FATAL com.emptycloud.blog.log4j2demo - this is fatal message
10:39:49.133 [main] ERROR com.emptycloud.blog.log4j2demo - this is error message

correct

[log4j2-demo]  2019-02-15 11-22-39.810 [FATAL] com.emptycloud.blog.log4j2demo:19  this is fatal message
[log4j2-demo]  2019-02-15 11-22-39.815 [ERROR] com.emptycloud.blog.log4j2demo:20  this is error message
[log4j2-demo]  2019-02-15 11-22-39.815 [WARN ] com.emptycloud.blog.log4j2demo:21  this is warn message
[log4j2-demo]  2019-02-15 11-22-39.815 [INFO ] com.emptycloud.blog.log4j2demo:22  this is info message

More complete configuration file introduction

<?xml version="1.0" encoding="utf-8" ?>
        <!--
            status属性:查看log4j的装配过程,值为OFF表示关闭,值为debug等日志级别为查看日志创建过程(正常情况下只有debug和trace级别日志显示)
            monitorInterval : 配置文件更改后重新加载,不用重启应用,单位秒
        -->
<configuration status="warn" monitorInterval="600">
<!--全局属性声明,方便后面使用${
    
    属性名称} 进行引用-->
<properties>
    <!-- /代表的是盘符根目录, 还有诸如 .代表当前当前项目路径 ,我们可以使用@ 名称@从pom.xml中动态获取这些值 -->
    <property name="LOG_HOME">/log</property>
    <property name="DEBUG_FILE_NAME">debug</property>
    <property name="ERROR_FILE_NAME">error</property>
</properties>

<!--定义附加器,需要在appender标签中定义-->
<Appenders>
    <!--
        name属性:定义追加器的标识名称
        target:定义输出日志形式    SYSTEM_OUT/SYSTEM_ERR
    -->
    <Console name="console" target="SYSTEM_OUT">
        <!--
            ThresholdFilter:指定追加器过滤日志的级别
            level:设定级别
            onmatch:匹配符合条件的日志输出
            onMismatch:拒绝不符合条件
        -->
        <ThresholdFilter level="warn" onmatch="ACCEPT" onMismatch="DENY"/>
        <PatternLayout pattern="[log4j2-demo]  %-d{yyyy-MM-dd HH-mm-ss.SSS} [%-5p] %C:%L  %m%n"/>
    </Console>

    <!--
        File : 文件追加器
        append :决定新产生的日志是追加还是覆盖(true为追加(默认))
        FileName : 决定日志文件的名称和位置
    -->
    <File name="file" FileName="${LOG_HOME}/file.log" append="true">
        <ThresholdFilter level="error" onmatch="ACCEPT" onMismatch="DENY"/>
        <PatternLayout pattern="[log4j2-demo] %-d{yyyy-MM-dd HH-mm-ss.SSS} [%-5p] %c:%L %m%n"/>
    </File>

    <!--
        以天//时为单位打印日志
        filePattern指定封存日志文件的格式
    -->
    <RollingFile name="rollingFile" fileName="${LOG_HOME}/rollfile.log"
                 filePattern="${LOG_HOME}/$${date:yyyy-MM}/rollfile-%d{yyyy-MM-dd}.log">
        <!--
            间隔时间备份策略
            modulate为true表示以0点为边界进行时间偏移计算,
            例:每隔4个小时进行日志封存,当前时间为3点,那么1个小时后进行一次日志封存(将之前的日志放置到filePattern指定的封存位置)
            interval:间隔时间(其单位有filePattern中-dd HH%d{
    
    yyyy-MM}的最小单位来决定,)
        -->
        <TimeBasedTriggeringPolicy modulate="true" interval="1"/>
        <PatternLayout pattern="[log4j3-demo] %-d{yyyy-MM-dd HH-mm-ss.SSS} [%-5p] %c:%L %m%n"/>
        <ThresholdFilter level="debug" onmatch="ACCEPT" onMismatch="DENY"/>
    </RollingFile>

    <!--
        以大小为策略进行日志封存,%i用于记录封存文件的生成先后顺序(),.zip/.gz等指定压缩格式
        immediateFlush:log4j2接收到日志事件时,是否立即将日志刷到磁盘。默认为true-->
    <RollingFile name="sizedRollFile" fileName="${LOG_HOME}/sizerollfile.log" immediateFlush="true"
                 filePattern="${LOG_HOME}/$${date:yyyy-MM-dd}/sizerollfile-%d{yyyy-MM-dd HH}-%i.log.zip">
        <PatternLayout pattern="[log4j2-demo] %-d{yyyy-MM-dd HH:mm:ss.SSS} [%-5p] %c:%L %m%n"/>
        <!-- 当有多个策略时,使用Policies 标签-->
        <Policies>
            <TimeBasedTriggeringPolicy />
            <!--基于大小的触发策略,size指定大小-->
            <SizeBasedTriggeringPolicy size="10 kB"/>
        </Policies>
        <Filters>
            <thresholdFilter level="debug" onmatch="ACCEPT" onMismatch="DENY"/>
        </Filters>
        <!--
            控制生成的封存文件数量的一种策略,max控制filePattern 中的%i ,不指定默认为7,
            (就是你只能看见7个封存的文件,多余的你可以理解为覆盖掉了)
            这虽然也是一种策略,但是放置在策略标签之外
        -->
        <DefaultRolloverStrategy max="20" />
    </RollingFile>
</Appenders>

<Loggers>
    <!-- 定义根日志 -->
    <!--
        level : 指定根日志的日志输出级别,ThresholdFilter生效其设置的日志级别输出取决于此
        例:如果跟记录器的日志级别设置成error,那么追加器也不会输出error级别一下的日志
    -->
    <Root level="debug">
        <!-- 引用日志追加器,和上面定义的追加器的名称一样-->
        <AppenderRef ref="console"/>
        <AppenderRef ref="file"/>
        <AppenderRef ref="rollingFile"/>
        <AppenderRef ref="sizedRollFile"/>
    </Root>

    <!--
        Logger:定义其他记录器,和根记录器存在继承关系, 一般用于设置单独的包的日志打印级别
        additivity : 设定是否继承父记录器的追加器
    -->

    <Logger name="com.emptyCloud.blog" level="debug" additivity="false">
        <AppenderRef ref="console"/>
    </Logger>
</Loggers>

</configuration>

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_40182873/article/details/87194625