I am learning about Log4j currently and the book I am using is explaining AsyncAppenders. I set a buffer size to be 128 (LoggingEvents). The book explains that no messages will be printed until the buffer size is reached, however my program prints the logging messages regardless of the buffer size.
Why is this the case? I would appreciate any other pointers about AsyncAppenders if anyone has knowledge about using them :)
Log4j.xml
<?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="ASYNC" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="CONSOLE"/>
<param name="BufferSize" value="128"/>
</appender>
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%t] - %m%n"/>
</layout>
</appender>
<logger name="org.example.christopher" additivity="false">
<level value="debug"/>
<appender-ref ref="ASYNC"/>
</logger>
<root>
<priority value="debug"/>
</root>
</log4j:configuration>
Java code
package org.example.christopher;
import org.apache.log4j.*;
import org.apache.log4j.xml.DOMConfigurator;
public class AsyncLogging{
private static Logger logger = Logger.getLogger(AsyncLogging.class.getPackage().getName());
private AsyncAppender asyncAppender = null;
private ConsoleAppender consoleAppender = null;
public AsyncLogging(){
try{
logger.setAdditivity(false);
asyncAppender = (AsyncAppender) logger.getAppender("ASYNC");
asyncAppender.setBufferSize(128);
}
catch (Exception e){
System.out.println("error: " + e.toString());
}
}
public void doLogging(){
logger.debug("Debug 1");
logger.debug("Debug 2");
logger.debug("Debug 3");
//logger.debug("Debug 4");
//logger.debug("Debug 5");
}
public static void main(String ... args){
AsyncLogging asyncLogging = new AsyncLogging();
asyncLogging.doLogging();
}
}
Neither the javadocs or the source code of AsyncAppender
say that no messages will be printed until the buffer is full. Indeed, according to my reading of the code:
The AsyncAppender.Dispatcher
thread that does the writing will be woken whenever an event is appended and the buffer is empty.
Once woken, it won't go to sleep until the buffer is empty.
That is pretty much the opposite of what the book you are reading says. (Assuming that you have read it correctly.)