Log4J 2异步记录器和线程

时间:2016-03-25 06:49:52

标签: java logging log4j log4j2

我试图使所有Log4J 2记录器与IMAP Disruptor异步。我正确设置了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>

我的记录器类有这段代码。

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

在logger类中,我尝试使用带有1000个循环的for循环来记录消息,但仍然是相同的主线程正在完成所有工作。我做错了什么?

1 个答案:

答案 0 :(得分:3)

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

后台线程的线程名称或ID永远不会显示在日志中。这是设计的。