Video in progress
When do you need an AsyncAppender in Logback, and what are its risks?
An AsyncAppender moves log writing to a separate thread so business threads don't wait on disk or network. But if the queue fills up, by default logs below INFO are dropped, and if the application is killed abruptly, logs still in the queue can be lost.
📖 Answer
With a synchronous appender, log.info doesn't return until it is written to the file. If the disk is slow (NFS, a full volume) or the log goes straight over the network, request threads end up waiting on the log. In one incident, under load, hundreds of threads were sitting BLOCKED around the appender's lock.
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>8192</queueSize>
<discardingThreshold>0</discardingThreshold>
<neverBlock>true</neverBlock>
<appender-ref ref="FILE"/>
</appender>
What the settings mean:
queueSize: the default is 256, which is too small under load;discardingThreshold: by default, when the queue is 80% full, TRACE/DEBUG/INFO are dropped; if it is 0, nothing is dropped;neverBlock=true: if the queue is full, the thread doesn't wait and the log is lost. If it'sfalse, the thread blocks on a full queue.
So the choice is clear: either lose logs or slow the application down. Losing is not acceptable for payment audit logs, so write those to a separate, synchronous or reliable channel.
Two more things:
- caller data (
%line,%method) is expensive; in async it isn't collected by default (includeCallerData=false); - Logback must be shut down properly so the queue is drained when the application stops. Spring Boot does this with a shutdown hook, but with
kill -9it's lost anyway.
Sign up to mark studied questions and save your progress.