001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.selector.servlet;
015
016import static ch.qos.logback.classic.ClassicConstants.JNDI_CONTEXT_NAME;
017
018import javax.naming.Context;
019import javax.naming.NamingException;
020import javax.servlet.ServletContextEvent;
021import javax.servlet.ServletContextListener;
022
023import org.slf4j.Logger;
024
025import ch.qos.logback.classic.LoggerContext;
026import ch.qos.logback.classic.selector.ContextSelector;
027import ch.qos.logback.classic.util.ContextSelectorStaticBinder;
028import ch.qos.logback.classic.util.JNDIUtil;
029
030public class ContextDetachingSCL implements ServletContextListener {
031
032    public void contextInitialized(ServletContextEvent arg0) {
033        // do nothing
034    }
035    
036    public void contextDestroyed(ServletContextEvent servletContextEvent) {
037        String loggerContextName = null;
038
039        try {
040            Context ctx = JNDIUtil.getInitialContext();
041            loggerContextName = (String) JNDIUtil.lookup(ctx, JNDI_CONTEXT_NAME);
042        } catch (NamingException ne) {
043        }
044
045        if (loggerContextName != null) {
046            System.out.println("About to detach context named " + loggerContextName);
047
048            ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
049            if (selector == null) {
050                System.out.println("Selector is null, cannot detach context. Skipping.");
051                return;
052            }
053            LoggerContext context = selector.getLoggerContext(loggerContextName);
054            if (context != null) {
055                Logger logger = context.getLogger(Logger.ROOT_LOGGER_NAME);
056                logger.warn("Stopping logger context " + loggerContextName);
057                selector.detachLoggerContext(loggerContextName);
058                // when the web-app is destroyed, its logger context should be stopped
059                context.stop();
060            } else {
061                System.out.println("No context named " + loggerContextName + " was found.");
062            }
063        }
064    }
065
066 
067
068}