【Java】ServletContextListener没有打印contextDestroyed方法内的日志问题

场景

@Slf4j
public class ScanJob implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        log.info("Listener initialized");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.info("Listener destroyed");
    }

    // business logic

}        

这时候如果Job服务被停止之后,不会打印Listener destroyed

排查顺序

  1. 检查web.xml配置顺序,确认是不是有别的Listener
    1. 没有
  2. 检查是不是缺少了@WebListener
    1. 这个和web.xml效果一样,如果有web.xml配置则不需要@WebListener
  3. 检查类加载器是不是加载错误了,在初始化方法里加
    this.getClass().getClassLoader()
    sce.getServletContext().getClassLoader()

    检查这两个是否是同一个路径下的java程序(jar包或者war包)

 排查完发现都不是,后来发现是因为Slf4j框架在销毁过程之前已经被销毁了,所以log框架打的日志在contextDestroyed没有打印

或者用StackOverflow推荐的这个禁用auto-shutdown

https://stackoverflow.com/questions/33844659/no-log-output-on-contextdestroyed-using-servletcontextlistener-slf4j

解决办法

选择用System.out.println();

 

posted @ 2025-04-29 14:03  onejay  阅读(20)  评论(0)    收藏  举报