Create and Configure Log4j2 Async Logger

Project structure

In this example we will configure a Log4j2 Async Logger. Asynchronous logging can improve your application’s performance by executing the I/O operations in a separate thread. Asynchronous Loggers internally use the Disruptor, a lock-free inter-thread communication library, instead of queues. Some drawback of using Log4j2 Async Logger is Error Handling. If a problem arrises during the logging process and an exception is thrown, the asynchronous logger has more difficulty to signal this problem to the application. You can however configure a custom ExceptionHandler, but this may still not cover all cases. If logging is a part of your business logic, for example when you use log4j as an audit logging framework you should use a synchronously logger.

Note: you can combine synchronous and asynchronous loggers together.
+--src
|   +--main
|       +--java
|           +--com
|               +--memorynotfound
|                   +--logging
|                       |--Log4j2Example.java
|       +--resources
|           |--log4j2.xml
pom.xml

Maven dependencies

In order to use the Log4j2 Async Logger we need to add the disruptor. This dependency will make sure that the latency is kept to a minimum.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.memorynotfound.logging.log4j</groupId>
    <artifactId>async-logger</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <name>LOG4J2 - ${project.artifactId}</name>

    <properties>
        <log4j.version>2.1</log4j.version>
        <disruptor.version>3.3.0</disruptor.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <version>${disruptor.version}</version>
        </dependency>
    </dependencies>

</project>

Log4j2 Async Logger Log4j2.xml Configuration

Create a log4j2.xml file and put it into the resources folder.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns="http://logging.apache.org/log4j/2.0/config">

    <Appenders>
        <File name="FILE" fileName="logfile.log" append="true">
            <PatternLayout pattern="%-5p | %d{yyyy-MM-dd HH:mm:ss} | [%t] %C{2} (%F:%L) - %m%n"/>
        </File>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%-5p | %d{yyyy-MM-dd HH:mm:ss} | [%t] %C{2} (%F:%L) - %m%n"/>
        </Console>
    </Appenders>

    <Loggers>
        <Logger name="com.memorynotfound" level="debug"/>

        <Root level="info">
            <AppenderRef ref="STDOUT"/>
            <AppenderRef ref="FILE"/>
        </Root>
    </Loggers>

</Configuration>

Testing Log4j2 Async Logger Configuration

package com.memorynotfound.logging;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Log4j2Example {

    private static final Logger LOG = LogManager.getLogger(Log4j2Example.class);

    public static void main(String... args){
        LOG.debug("This will be printed on debug");
        LOG.info("This will be printed on info");
        LOG.warn("This will be printed on warn");
        LOG.error("This will be printed on error");
        LOG.fatal("This will be printed on fatal");

        LOG.info("Appending string: {}.", "Hello, World");
    }
}

Output

As said in the note we override the root logger with a package logger equal to DEBUG as such, all levels greater or equal than debug will be printed.

DEBUG | 2015-01-31 11:01:11 | [main] logging.Log4j2Example (Log4j2Example.java:11) - This will be printed on debug
INFO  | 2015-01-31 11:01:11 | [main] logging.Log4j2Example (Log4j2Example.java:12) - This will be printed on info
WARN  | 2015-01-31 11:01:11 | [main] logging.Log4j2Example (Log4j2Example.java:13) - This will be printed on warn
ERROR | 2015-01-31 11:01:11 | [main] logging.Log4j2Example (Log4j2Example.java:14) - This will be printed on error
FATAL | 2015-01-31 11:01:11 | [main] logging.Log4j2Example (Log4j2Example.java:15) - This will be printed on fatal
INFO  | 2015-01-31 11:01:11 | [main] logging.Log4j2Example (Log4j2Example.java:17) - Appending string: Hello, World.

References

You may also like...

  • Fabio Frumento

    You forgot the -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

    • zhang yangyang

      Can you tell me how to configure this ? thanks!