Spring-boot – Define logback shutdown hook in Spring Boot

logbackspring-boot

I am using AsyncAppender in spring-boot (1.5.3.RELEASE) application.

logback.xml

<appender name="FILE_ASYNC" class="ch.qos.logback.classic.AsyncAppender">
    <queueSize>5000</queueSize>
    <discardingThreshold>0</discardingThreshold>
    <appender-ref ref="FILE" />
</appender>

As per logback documentation,

Upon application shutdown or redeploy, AsyncAppender must be stopped
in order to stop and reclaim the worker thread and to flush the
logging events from the queue.

https://logback.qos.ch/manual/appenders.html

Further it says:

In order to avoid interrupting the worker thread under these
conditions, a shutdown hook can be inserted to the JVM runtime that
stops the LoggerContext properly after JVM shutdown has been initiated

I want to know how to stop AsyncAppender in Spring Boot application. At which place in Spring Boot, should I define shutdown hook?

Best Answer

Just add the <shutdownHook/> instruction to your logback.xml. For example:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook"/>

    <appender name="FILE_ASYNC" class="ch.qos.logback.classic.AsyncAppender">
        <queueSize>5000</queueSize>
        <discardingThreshold>0</discardingThreshold>
        <appender-ref ref="FILE" />
    </appender>

    <!-- the rest of your logback config -->

</configuration>

With this in place you'll notice the following log message is emitted when Logback is configuring itself:

INFO in ch.qos.logback.core.joran.action.ShutdownHookAction - About to instantiate shutdown hook of type [ch.qos.logback.core.hook.DelayingShutdownHook]

Related Topic