Search Tutorials


Log4j AsyncAppender Basic Example | JavaInUse



Log4j AsyncAppender Basic Example



For any application logging in an invaluable tool. If any error occurs when the application is running it needs to logged with enough information to point to the line of code. Also application performance is measured using the logs.
However adding logging affects the performance of the application. The logging is usually a threadsafe mechanism where only a single thread can write to logs at a time. A Singleton pattern is usually used to implement logger.
In a traditional synchronous log model, the caller cannot execute further unless the log service returns successfully. All calls are blocked until the record is persisted or acknowledged by the log service. That clearly results in an overhead, especially if an application is designed to code numerous log messages. Imagine a source file consisting of a large number (sometimes hundreds) of log statements.
Asynchronous logging can improve your application's performance by executing the I/O operations in a separate thread. The AsyncAppender lets users log events asynchronously. The AsyncAppender will collect the events sent to it and then dispatch them to all the appenders that are attached to it. You can attach multiple appenders to an AsyncAppender. The AsyncAppender uses a separate thread to serve the events in its buffer.

In this tutorial we implement an example for org.apache.log4j.AsyncAppender.
Create the log4j.xml as follows-
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
	debug="true">
	<appender name="CONSOLEAPP" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d %-5p [%t]  - %m%n" />
		</layout>
	</appender>
	<appender name="ASYNCAPP" class="org.apache.log4j.AsyncAppender">
		<appender-ref ref="CONSOLEAPP" />
	</appender>
	<logger name="com.apress.logging.log4j" additivity="false">
		<level value="debug" />
		<appender-ref ref="ASYNCAPP" />
		<appender-ref ref="CONSOLEAPP" />
	</logger>
	<root>
		<priority value="debug" />
		<appender-ref ref="ASYNCAPP" />
		<appender-ref ref="CONSOLEAPP" />
	</root>
</log4j:configuration>
	 
Create the AsyncLoggingExample.java for testing async appender as follows-
package com.javainuse;

import org.apache.log4j.*;

public class AsyncLoggingExample {

    private static Logger logger = Logger.getLogger(AsyncLoggingExample.class);
    private AsyncAppender asyncAppender = null;

    public AsyncLoggingExample() {

        try {
            logger.setAdditivity(false);
	asyncAppender = (AsyncAppender) Logger.getRootLogger().getAppender("ASYNCAPP");
            asyncAppender.setBufferSize(4);
        }
        catch (Exception e) {
            System.out.println("error: " + e.toString());
        }

    }

    public void doLogging() {
        logger.info("AsyncLoggingExample 1");
        logger.info("AsyncLoggingExample 2");
        logger.info("AsyncLoggingExample 3");
        logger.info("AsyncLoggingExample 4");
        logger.info("AsyncLoggingExample 5");
    }

    public static void main(String args[]) {
        BasicConfigurator.configure();
        AsyncLoggingExample AsyncLoggingExample = new AsyncLoggingExample();
        AsyncLoggingExample.doLogging();
    }
}
The logging now runs a synchronously, so there is less overhead on the application.

See Also

Per4j tutorial: Getting started with Per4j
Using Java Reflections API to map Object Elements
Difference between Spy and Mock in Mockito
Difference between Mock thenCallRealMethod() and Spy in Mockito
Checking the specified class contains a field matching the specified name using Java Reflections
Getting Started with JMS Messaging- ActiveMQ Hello World Tutorial
Getting Name of Current Method inside a method in Java