Spring @PreDestroy: No logging because Logback stops too soon

后端 未结 2 663
悲&欢浪女
悲&欢浪女 2021-02-07 14:29

In my project, I am using Logback as logging facility. I have the following class

@Component
class Test {
    @PreDestroy
    public void destroy() {
        try         


        
相关标签:
2条回答
  • 2021-02-07 14:45

    To pick up Dovmo's answer. It's all about ordering. I have the same issue on Tomcat 8.5.x. Bacially, the initializer does an addListener, you don't have any control over the listener. At shutdown, Tomcat reverse-iterates that list, picking the Logback listener first: Spring won't log anything.

    A custom listener won't help because you cannot prepend it. What works for me on Tomcat is:

    <listener>
        <listener-class>ch.qos.logback.classic.servlet.LogbackServletContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <context-param>
        <param-name>logbackDisableServletContainerInitializer</param-name>
        <param-value>true</param-value>
    </context-param>
    
    0 讨论(0)
  • 2021-02-07 14:52

    There is a documented way to disable to disable the registering of the LogbackServletContextListener:

    You may disable the automatic the installation of LogbackServletContextListener by setting a named logbackDisableServletContainerInitializer in your web-application's web.xml file. Here is the relevant snippet.

    <web-app>
        <context-param>
            <param-name>logbackDisableServletContainerInitializer</param-name>
            <param-value>true</param-value>
        </context-param>
        .... 
    </web-app>
    

    Note that logbackDisableServletContainerInitializer variable can also be set as a Java system property an OS environment variable. The most local setting has priority, i.e. web-app first, system property second and OS environment last.

    I would imagine you'll probably want to write your own shutdown hook if this is the case and stop the LoggerContext

    0 讨论(0)
提交回复
热议问题