未调用Tomcat ServletContextListener.contextDestroyed

Mir*_*rko 7 tomcat servletcontextlistener

我们有多个MemoryLeaks(在catalina.out中找到),同时重新加载上下文.

为了清理这些线程,我创建了一个ServletContextListener的实现.

contextInitialized()创建上下文时成功调用该方法,因为我可以看到日志条目.

但是contextDestroyed()没有调用该方法,因此不会调用我的清理代码.任何想法为什么会这样?

我是否应该在需要重新加载上下文时实现另一个接口?

public class MyContextListener implements ServletContextListener {

    private static final Logger log = Logger.getLogger(MyContextListener.class);

    @Override
    public void contextDestroyed(final ServletContextEvent arg0) {
        MyContextListener.log.info("destroying Servlet Context");
        //Do stuff
        MyContextListener.log.info("Servlet Context destroyed");
    }

    @Override
    public void contextInitialized(final ServletContextEvent arg0) {
        try {
            MyContextListener.log.info("Creating Servlet Context");
            //Do stuff
        } finally {
            MyContextListener.log.info("Servlet Context created");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*kin 2

我遇到了一些问题,我通过 .“修复”了它System.out.println

  @WebListener
  public class App implements ServletContextListener {
      private static final Logger logger = LoggerFactory.getLogger(App.class);
   
      @Override
      public void contextInitialized(ServletContextEvent sce) {
          System.out.println("START");
          logger.info("START");
      }
   
      @Override
      public void contextDestroyed(ServletContextEvent sce) {
          System.out.println("STOP");
          logger.info("STOP");
      }
  }
Run Code Online (Sandbox Code Playgroud)

日志.txt:

[%thread] %-5level %logger{0}:%L - %msg%n
[localhost-startStop-1] INFO  App:16 - START
Run Code Online (Sandbox Code Playgroud)

标准输出:

Commons Daemon procrun stdout initialized
START
STOP
Run Code Online (Sandbox Code Playgroud)

这意味着contextDestroyed已被调用,但记录器之前已停止。我用了org.slf4j.Logger

要管理实时 cicle 日志记录(并解决问题),请参阅:从 servlet 上下文销毁事件记录日志