In Log4J, why %C in ConversionPattern prints '

2019-01-18 23:55发布

I have a trouble when using %C in ConversionPattern with AsyncAppender.

My Lo4J configuration is:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy/MM/dd HH:mm:ss,SSS} %C{1} - %m%n" />
        </layout>
    </appender>
    <appender name="async_console" class="org.apache.log4j.AsyncAppender">
        <param name="BufferSize" value="1000" />
        <appender-ref ref="console" />
    </appender>
    <root>
        <level value="debug" />
        <!--
        <appender-ref ref="console" />
        -->
        <appender-ref ref="async_console" />
    </root>
</log4j:configuration>

And my test code is:

@Test
public void testAsync() {
    DOMConfigurator
            .configure("src/test/resources/learningtest/log4j/log4j_test_async.xml");
    Logger log = Logger.getLogger(getClass());
    log.debug("Hello, world!");
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

The result of the test code is:

2012/03/15 11:51:22,570 ? - Hello, world!

Without AsynAppender, it works fine:

2012/03/15 11:51:06,002 Log4jTest - Hello, world!

With %c (category), it works fine, too.

What am I missing?

Please let me know.

Thanks in advance :-)

Reference:

http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

标签: log4j
1条回答
唯我独甜
2楼-- · 2019-01-19 00:42

When using "%C" or "%M", log4J uses Throwable.getStackTrace to get the stackTrace and use this information to get the caller class and method. The problem is that when using an AsyncAppender, the Throwable is created in another thread and the stackTrace does not contain the caller method.

查看更多
登录 后发表回答