在Spring Boot中定义logback shutdown hook

时间:2017-08-15 12:44:37

标签: spring-boot logback

我在spring-boot(1.5.3.RELEASE)应用程序中使用AsyncAppender。

logback.xml

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

根据logback文档,

  

在应用程序关闭或重新部署时,必须停止AsyncAppender   为了停止和回收工作线程并冲洗   记录队列中的事件。

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

进一步说:

  

为了避免在这些情况下中断工作线程   条件,可以将一个shutdown钩子插入到JVM运行时   在启动JVM关闭后正确停止LoggerContext

我想知道如何在Spring Boot应用程序中停止AsyncAppender。在Spring Boot中的哪个位置,我应该定义shutdown hook吗?

3 个答案:

答案 0 :(得分:8)

只需将<shutdownHook/>指令添加到logback.xml即可。例如:

<?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>

有了这个,您会注意到Logback自行配置时会发出以下日志消息:

  ch.qos.logback.core.joran.action.ShutdownHookAction中的 INFO - 即将实例化[ch.qos.logback.core.hook.DelayingShutdownHook]类型的关闭钩子

答案 1 :(得分:2)

我遇到了类似的问题但是版本1.1.6的logback和spring-boot 1.5.4。 我的解决方案是添加:

logging.register-shutdown-hook=true

到application.properties文件中进行邀请

org.springframework.boot.logging.logback.LogbackLoggingSystem在ApplicationContext.close调用上停止LoggerContext。

答案 2 :(得分:1)

从logback版本1.1.10开始,您无需显式定义关闭挂钩。从版本1.1.10开始,当web-app停止或重新加载时,logback负责停止当前的logback-classic上下文(以及所有appender)。尝试更新您的logback版本并检查一次。

以下是更新后的文档:https://logback.qos.ch/manual/configuration.html#webShutdownHook