github linkedin
Async logging with Log4j2
2019-10-28

Finally I got some time to play around with Log4j2 and the async logging support. Async logging promises high throughput and minimal logging latency, the numbers on this page are impressive.

So, how to get async logging running?

First, add the LMAX disruptor library on your classpath:

<dependency>
    <groupId>com.lmax</groupId>
    <artifactId>disruptor</artifactId>
    <version>3.4.2</version>
    <scope>runtime</scope>
</dependency>

Now you have to switch all the loggers to async by setting a JVM property:

-Dlog4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

and that’s it.

When trying this in an empty Java project, you will need some Log4j2 configuration. Put this into src/main/resources/log4j2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%date{ISO8601_OFFSET_DATE_TIME_HHCMM} %thread{10} %-5level %logger{36} - %highlight{%message%xException%n}"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

This gives you nice messages with ISO-8601 formatted dates (including timezones), thread names and colored messages (see this documentation for details of these %fields).

Sometimes you have some libraries in use which don’t use Log4j2 for logging, but use SLF4J instead. Wouldn’t it be great if you could route these log messages to your Log4j2 loggers? The developers of Log4j2 have you covered, just add this on your classpath:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j18-impl</artifactId>
    <version>${log4j.version}</version>
</dependency>

Happy logging!


Back to posts