In Log4J, why %C in ConversionPattern prints '?' (question mark) with AsyncAppender?

混江龙づ霸主 提交于 2019-12-17 19:39:17

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/9713429/in-log4j-why-c-in-conversionpattern-prints-question-mark-with-asyncappen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!