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 java.io.IOException;
017
018import javax.servlet.Filter;
019import javax.servlet.FilterChain;
020import javax.servlet.FilterConfig;
021import javax.servlet.ServletException;
022import javax.servlet.ServletRequest;
023import javax.servlet.ServletResponse;
024
025import org.slf4j.LoggerFactory;
026
027import ch.qos.logback.classic.LoggerContext;
028import ch.qos.logback.classic.selector.ContextJNDISelector;
029import ch.qos.logback.classic.selector.ContextSelector;
030import ch.qos.logback.classic.util.ContextSelectorStaticBinder;
031
032/**
033 * A servlet filter that puts the environment dependent LoggerContext in a
034 * ThreadLocal variable, removing it after the request is processed.
035 * 
036 * <p>To use it, add the following lines to a web.xml file
037 *  
038 * <filter>
039 *   <filter-name>LoggerContextFilter</filter-name>
040 *   <filter-class>
041 *     ch.qos.logback.classic.selector.servlet.LoggerContextFilter
042 *   </filter-class>
043 * </filter>
044 * <filter-mapping>
045 *   <filter-name>LoggerContextFilter</filter-name>
046 *   <url-pattern>/*</url-pattern>
047 * </filter-mapping>
048 * 
049 * @author S&eacute;bastien Pennec
050 */
051public class LoggerContextFilter implements Filter {
052
053    public void destroy() {
054        // do nothing
055    }
056
057    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
058
059        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
060        ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
061        ContextJNDISelector sel = null;
062
063        if (selector instanceof ContextJNDISelector) {
064            sel = (ContextJNDISelector) selector;
065            sel.setLocalContext(lc);
066        }
067
068        try {
069            chain.doFilter(request, response);
070        } finally {
071            if (sel != null) {
072                sel.removeLocalContext();
073            }
074        }
075    }
076
077    public void init(FilterConfig arg0) throws ServletException {
078        // do nothing
079    }
080}