View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, 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 javax.servlet.ServletContextEvent;
21  import javax.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.classic.util.JNDIUtil;
29  
30  public class ContextDetachingSCL implements ServletContextListener {
31  
32    public void contextDestroyed(ServletContextEvent servletContextEvent) {
33      String loggerContextName = null;
34      
35      try {
36        Context ctx = JNDIUtil.getInitialContext();
37        loggerContextName = (String) JNDIUtil.lookup(ctx, JNDI_CONTEXT_NAME);
38      } catch (NamingException ne) {
39      }
40      
41      if (loggerContextName != null) {
42        System.out.println("About to detach context named " + loggerContextName);
43        
44        ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
45        LoggerContext context = selector.detachLoggerContext(loggerContextName);
46        if (context != null) {
47          Logger logger = context.getLogger(Logger.ROOT_LOGGER_NAME);
48          logger.warn("Stopping logger context " + loggerContextName);
49          // when the web-app is destroyed, its logger context should be stopped
50          context.stop();
51        } else {
52          System.out.println("No context named " + loggerContextName + " was found.");
53        }
54      }
55    }
56  
57    public void contextInitialized(ServletContextEvent arg0) {
58      // do nothing
59    }
60  
61  }