log4j2笔记 #02# 启用异步日志

参考

Making All Loggers Asynchronous

将原本的log4j2同步日志转化为“完全异步日志模式”。官方文档:

This is simplest to configure and gives the best performance. To make all loggers asynchronous, add the disruptor jar to the classpath and set the system property log4j2.contextSelector to org.apache.logging.log4j.core.async.AsyncLoggerContextSelector.

Log4j-2.9 and higher require disruptor-3.3.4.jar or higher on the classpath. Prior to Log4j-2.9, disruptor-3.0.0.jar or higher was required.
document ...

第一步,添加相应的disruptor库

各个依赖包的版本需要对应。如下:

        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j-impl -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.8.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-web -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-web</artifactId>
            <version>2.8.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.lmax/disruptor -->
        <!-- Asynchronous Loggers internally use the Disruptor, a lock-free
        inter-thread communication library, instead of queues, resulting in
        higher throughput and lower latency.-->
        <dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <version>3.4.2</version>
        </dependency>
pom.xml

第二步,设置系统属性log4j2.contextSelector

一种简便的方式是在相应classpath下创建一个叫log4j2.component.properties的文件(maven项目直接放在main/resources就好),内容如下:

Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
log4j2.component.properties

PS. Log4jContextSelector的第一个字母必须大写

第三步,检验!

首先你需要允许log4j2输出自身的debug信息,log4j2.xml:

<Configuration status="DEBUG">

然后启动你的web项目,在ide或者catalina.out里观察debug信息,类似下面这样就说明成功:

原文地址:https://www.cnblogs.com/xkxf/p/10028777.html