spring boot的log4j2异步日志配置

1、log4j2异步配置

一、启动位置设置web

System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");

二、引入异步日志依赖spring

<dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <version>3.3.7</version>
        </dependency>

注意版本须要3以上apache

三、日志配置文件多线程

<Appenders>
        <RollingRandomAccessFile name="file" fileName="${LOG_HOME}/${FILE_NAME}.log"
                                 filePattern="${LOG_HOME}/${FILE_NAME}_%d{yyyy-MM-dd}-%i.log"
                                 immediateFlush="false">
            <PatternLayout pattern="${LOG_PATTERN}"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1"/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="50"/>
        </RollingRandomAccessFile>

        <RollingRandomAccessFile name="errorLog" fileName="${LOG_HOME}/error/${FILE_NAME}-error.log"
                                 filePattern="${LOG_HOME}/error/${FILE_NAME}-error-%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="${LOG_PATTERN}"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="50 MB"/>
            </Policies>
            <Filters>
                <!-- 只记录error级别信息 -->
                <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
            <!-- 指定天天的最大压缩包个数,默认7个,超过了会覆盖以前的 -->
            <DefaultRolloverStrategy max="50"/>
        </RollingRandomAccessFile>
    </Appenders>  

    <root level="info" includeLocation="true">
        <appender-ref ref="file" />
        <appender-ref ref="errorLog" />
    </root>

注意仍是使用<root>标签,而不是<asyncRoot>,asyncRoot标签仅为混合同步异步使用。app

增长includeLocation="true",immediateFlush="false"框架

 

以上三步,便可实现log4j2异步日志,缺一不可dom

2、spring boot改log4j2

一、若引入了spring-boot-starter-web,则须要去除spring boot的默认日志框架logback异步

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions><!-- 去掉默认配置 -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

二、添加log4j2async

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

3、logId实现

ThreadContext.put("logId", "logId");

ThreadContext.remove("logId");

在接受rpc或http请求的地方添加logId,请求结束删除。spring-boot

这个方法没法实现多线程同一个logId,而且使用MDC的方式对log4j2无效

多线程logId实现还待研究,但愿留言交流。