Log4J 2 异步记录器和线程

Log4J 2 Async Logger and Threads

我正在尝试使所有 Log4J 2 记录器与 IMAP Disruptor 异步。我正确设置了干扰器依赖项,在 IntelliJ 中,我在 VM 选项下设置了以下系统 属性。

-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

我的log4j2.xml文件是这个。

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="trace">
<Appenders>
    <Console name="Console-Appender" target="SYSTEM_OUT">
        <PatternLayout>
            <pattern>
                [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
            </pattern>>
        </PatternLayout>
    </Console>
    <File name="File-Appender" fileName="logs/xmlfilelog.log" >
        <PatternLayout>
            <pattern>
                [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
            </pattern>
        </PatternLayout>
    </File>
</Appenders>
<Loggers>
    <Logger name="guru.springframework.blog.log4j2async" level="debug">
        <AppenderRef ref="File-Appender"/>
    </Logger>
    <Root level="debug">
        <AppenderRef ref="Console-Appender"/>
    </Root>
</Loggers>
</Configuration>

我的记录器 class 有这个代码。

package guru.springframework.blog.log4j2async;

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

public class Log4J2AsyncLogger {

private static Logger logger = LogManager.getLogger();
public Log4J2AsyncLogger(){
    logger.info("Logger created by Thread Id:"+Thread.currentThread().getId());
}
public void performSomeTask(){
        logger.debug("This is a debug message sent by Thread Id:" + Thread.currentThread().getId());
        logger.info("This is a info message sent by Thread Id:" + Thread.currentThread().getId());
        logger.warn("This is a warn message sent by Thread Id:" + Thread.currentThread().getId());
        logger.error("This is a error message sent by Thread Id:" + Thread.currentThread().getId());
        logger.fatal("This is a fatal message sent by Thread Id:" + Thread.currentThread().getId());
 }
}

我希望输出具有不同线程 ID 的日志消息。但是,控制台和文件输出都是:

[INFO ] 2016-03-25 11:41:01.189 [main] Log4J2AsyncLogger - System property Log4jContextSelector: org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
[INFO ] 2016-03-25 11:41:01.189 [main] Log4J2AsyncLogger - Logger created by Thread Id:1
[DEBUG] 2016-03-25 11:41:01.189 [main] Log4J2AsyncLogger - This is a debug message sent by Thread Id:1
[INFO ] 2016-03-25 11:41:01.189 [main] Log4J2AsyncLogger - This is a info message sent by Thread Id:1
[WARN ] 2016-03-25 11:41:01.189 [main] Log4J2AsyncLogger - This is a warn message sent by Thread Id:1
[ERROR] 2016-03-25 11:41:01.189 [main] Log4J2AsyncLogger - This is a error message sent by Thread Id:1
[FATAL] 2016-03-25 11:41:01.189 [main] Log4J2AsyncLogger - This is a fatal message sent by Thread Id:1

在记录器 class 中,我尝试使用具有 1000 个循环的 for 循环来记录消息,但仍然是同一个主线程在执行所有工作。我做错了什么?

Log4j 在调用线程(您的应用程序线程)中创建消息的快照。它将在单独的后台线程中写入磁盘,但这不会影响消息内容。

后台线程的线程名称或 ID 从不显示在日志中。这是设计使然。