1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v2.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  
15  package ch.qos.logback.classic.servlet;
16  
17  import jakarta.servlet.ServletContextEvent;
18  import jakarta.servlet.ServletContextListener;
19  
20  import org.slf4j.ILoggerFactory;
21  import org.slf4j.LoggerFactory;
22  
23  import ch.qos.logback.classic.LoggerContext;
24  import ch.qos.logback.classic.util.StatusViaSLF4JLoggerFactory;
25  import ch.qos.logback.core.spi.ContextAwareBase;
26  
27  /**
28   * Allows for graceful shutdown of the {@link LoggerContext} associated with
29   * this web-app.
30   * 
31   * @author Ceki Gulcu
32   * @since 1.1.10
33   */
34  public class LogbackServletContextListener implements ServletContextListener {
35  
36      ContextAwareBase contextAwareBase = new ContextAwareBase();
37  
38      @Override
39      public void contextInitialized(ServletContextEvent sce) {
40  
41      }
42  
43      @Override
44      public void contextDestroyed(ServletContextEvent sce) {
45  
46          ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
47          if (iLoggerFactory instanceof LoggerContext) {
48              LoggerContext loggerContext = (LoggerContext) iLoggerFactory;
49              contextAwareBase.setContext(loggerContext);
50              StatusViaSLF4JLoggerFactory.addInfo("About to stop " + loggerContext.getClass().getCanonicalName() + " ["
51                      + loggerContext.getName() + "]", this);
52              loggerContext.stop();
53          }
54      }
55  
56  }