View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, 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 v1.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  package ch.qos.logback.classic.selector.servlet;
15  
16  import static ch.qos.logback.classic.ClassicConstants.JNDI_CONTEXT_NAME;
17  
18  import javax.naming.Context;
19  import javax.naming.NamingException;
20  import jakarta.servlet.ServletContextEvent;
21  import jakarta.servlet.ServletContextListener;
22  
23  import org.slf4j.Logger;
24  
25  import ch.qos.logback.classic.LoggerContext;
26  import ch.qos.logback.classic.selector.ContextSelector;
27  import ch.qos.logback.classic.util.ContextSelectorStaticBinder;
28  import ch.qos.logback.core.util.JNDIUtil;
29  
30  public class ContextDetachingSCL implements ServletContextListener {
31  
32      public void contextInitialized(ServletContextEvent arg0) {
33          // do nothing
34      }
35  
36      public void contextDestroyed(ServletContextEvent servletContextEvent) {
37          String loggerContextName = null;
38  
39          try {
40              Context ctx = JNDIUtil.getInitialContext();
41              loggerContextName = (String) JNDIUtil.lookupString(ctx, JNDI_CONTEXT_NAME);
42          } catch (NamingException ne) {
43          }
44  
45          if (loggerContextName != null) {
46              System.out.println("About to detach context named " + loggerContextName);
47  
48              ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
49              if (selector == null) {
50                  System.out.println("Selector is null, cannot detach context. Skipping.");
51                  return;
52              }
53              LoggerContext context = selector.getLoggerContext(loggerContextName);
54              if (context != null) {
55                  Logger logger = context.getLogger(Logger.ROOT_LOGGER_NAME);
56                  logger.warn("Stopping logger context " + loggerContextName);
57                  selector.detachLoggerContext(loggerContextName);
58                  // when the web-app is destroyed, its logger context should be stopped
59                  context.stop();
60              } else {
61                  System.out.println("No context named " + loggerContextName + " was found.");
62              }
63          }
64      }
65  
66  }