001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2026, 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 v2.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 jakarta.servlet.Filter;
019import jakarta.servlet.FilterChain;
020import jakarta.servlet.FilterConfig;
021import jakarta.servlet.ServletException;
022import jakarta.servlet.ServletRequest;
023import jakarta.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>
037 * To use it, add the following lines to a web.xml file
038 * </p>
039 * <pre>
040  &lt;filter>
041    &lt;filter-name>LoggerContextFilter&lt;/filter-name>
042    &lt;filter-class>ch.qos.logback.classic.selector.servlet.LoggerContextFilter&lt;/filter-class>
043 &lt;/filter>
044
045 &lt;filter-mapping>
046   &lt;filter-name>LoggerContextFilter&lt;/filter-name>
047   &lt;url-pattern>/*&lt;/url-pattern>
048 &lt;/filter-mapping>
049 </pre>
050 *
051 * @author S&eacute;bastien Pennec
052 */
053public class LoggerContextFilter implements Filter {
054
055    public void destroy() {
056        // do nothing
057    }
058
059    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
060            throws IOException, ServletException {
061
062        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
063        ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
064        ContextJNDISelector sel = null;
065
066        if (selector instanceof ContextJNDISelector) {
067            sel = (ContextJNDISelector) selector;
068            sel.setLocalContext(lc);
069        }
070
071        try {
072            chain.doFilter(request, response);
073        } finally {
074            if (sel != null) {
075                sel.removeLocalContext();
076            }
077        }
078    }
079
080    public void init(FilterConfig arg0) throws ServletException {
081        // do nothing
082    }
083}