Log4j2 - 寻找一个无垃圾且进行异步日志记录的最小示例

Log4j2 - Seeking a minimal example which is garbage free and does asynchronous logging

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

有没有人有这样的例子,或者他们能看出我所做的错误。

更新: 解决方案是使用 Unbox.box() on the primitive types,这会阻止自动装箱和相关分配。下面的代码已经更新。

代码:

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 

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

上述问题中的代码已更新为正确的代码。

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

我 post 这次更新是因为我在网上找不到任何类似的东西。

代码:

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) );
    }
}