首页 > 解决方案 > Log4j2 - 寻找一个无垃圾并进行异步日志记录的最小示例

问题描述

我正在尝试构建一个使用 log4j2 并且既无垃圾又利用异步日志记录的程序的最小示例。我相信我已经遵循了他们文档中讨论的所有准则,但我无法达到零(稳态)分配率。此处附加的工作为每条日志消息分配大约 60 个字节。

有没有人有这样的例子,或者相反,他们可以看到我所做的错误。

更新:解决方案是Unbox.box()在原始类型上使用,这会阻止自动装箱和相关的分配。下面的代码已更新。

代码:

public class Example {

    static private final Logger logger = LogManager.getLogger(Example.class);

    public static void main(String[] args) throws Exception {
        int count = Integer.parseInt(args[0]);
        System.gc();
        Thread.sleep(10000);

        for(int i = 0; i < count; i++) {
            logSomething();
        }
    }

    private static void logSomething() {
        logger.info("{} occurred at {}, here is some useful info {}, here is some more {}.",
                "AN_EVENT_I_WANT_TO_LOG", box(System.currentTimeMillis()), "ABCD", box(1234L));
    }
}

Log4J2 配置:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <File name="File" fileName="/dev/null" append="false" immediateFlush="false" >
            <PatternLayout pattern="%d %p %c{1.} [%t] %m %ex %map{} %n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="File"/>
        </Root>
    </Loggers>
</Configuration>

(相关)JVM 参数:

-Dlog4j2.garbagefreeThreadContextMap=true 
-Dlog4j2.enableThreadlocals=true 
-Dlog4j2.enableDirectEncoders=true 
-Dlog4j2.asyncLoggerWaitStrategy=yield 
-Dlog4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector 

标签: javagarbage-collectionlog4j2

解决方案


解决方案是手动装箱原始值,使用Unbox.box(). 这阻止了自动装箱和相关的分配。

上述问题中的代码已使用正确的代码进行了更新。

更新: 在下面的代码中,我扩展了解决方案以说明使用消息对象的无垃圾异步日志记录。准确地说,这意味着我可以将可重用的消息传递给记录器(因此无需分配这些对象),无需任何额外分配即可更新消息,无需分配即可格式化消息,底层记录器不会这样做任何进一步的分配,并且将其交给异步记录器是安全的(它将在传递给它的那一刻写入上下文,而logger.info()不是在异步记录器最终处理它时)。

我发布此更新是因为我在网上找不到类似的东西。

代码:

public class ExtendedExample {

    static class ApplicationEvent {
        long identifier;
        String detail;
        long timestamp;

        public ApplicationEvent initialize(long identifier, String detail, long timestamp) {
            this.identifier = identifier;
            this.detail = detail;
            this.timestamp = timestamp;
            return this;
        }
    }

    static private final Logger logger = LogManager.getLogger();
    public static void main(String[] args) throws Exception {
        int count = Integer.parseInt(args[0]);
        System.gc();
        Thread.sleep(10000);

        final ApplicationEvent event = new ApplicationEvent();
        for(int i = 0; i < count; i++) {
            event.initialize(i, "ABCD_EVENT", System.currentTimeMillis());
            onApplicationEvent(event);
        }
    }


    private static class ApplicationEventLogMessage extends ReusableObjectMessage {

        private final String eventType = ApplicationEvent.class.getSimpleName();
        private long eventTimestamp;
        private String eventDetail;
        private long eventIdentifier;

        private final StringBuilderFormattable formattable = new StringBuilderFormattable() {
            @Override
            public void formatTo(StringBuilder buffer) {
                buffer.append('{')
                        .append("eventType").append('=').append(eventType).append(", ")
                        .append("eventTimestamp").append('=').append(eventTimestamp).append(", ")
                        .append("eventDetail").append('=').append(eventDetail).append(", ")
                        .append("eventIdentifier").append('=').append(eventIdentifier)
                        .append('}');
            }
        };

        ReusableObjectMessage prepare(ApplicationEvent applicationEvent){
            // It is very important that we call set(), every time, before we pass this to the logger -
            // as the logger will clear() it.
            set(formattable);
            eventTimestamp = applicationEvent.timestamp;
            eventDetail = applicationEvent.detail;
            eventIdentifier = applicationEvent.identifier;
            return this;
        }

    }


    final static ApplicationEventLogMessage reusableEventLogMessage = new ApplicationEventLogMessage();
    private static void onApplicationEvent(ApplicationEvent applicationEvent) {
        logger.info( reusableEventLogMessage.prepare(applicationEvent) );
    }
}

推荐阅读