1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, 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 v2.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 java.io.IOException;
17  
18  import jakarta.servlet.Filter;
19  import jakarta.servlet.FilterChain;
20  import jakarta.servlet.FilterConfig;
21  import jakarta.servlet.ServletException;
22  import jakarta.servlet.ServletRequest;
23  import jakarta.servlet.ServletResponse;
24  
25  import org.slf4j.LoggerFactory;
26  
27  import ch.qos.logback.classic.LoggerContext;
28  import ch.qos.logback.classic.selector.ContextJNDISelector;
29  import ch.qos.logback.classic.selector.ContextSelector;
30  import ch.qos.logback.classic.util.ContextSelectorStaticBinder;
31  
32  /**
33   * A servlet filter that puts the environment-dependent LoggerContext in a
34   * ThreadLocal variable, removing it after the request is processed.
35   * 
36   * <p>
37   * To use it, add the following lines to a web.xml file
38   * </p>
39   * <pre>
40    &lt;filter>
41      &lt;filter-name>LoggerContextFilter&lt;/filter-name>
42      &lt;filter-class>ch.qos.logback.classic.selector.servlet.LoggerContextFilter&lt;/filter-class>
43   &lt;/filter>
44  
45   &lt;filter-mapping>
46     &lt;filter-name>LoggerContextFilter&lt;/filter-name>
47     &lt;url-pattern>/*&lt;/url-pattern>
48   &lt;/filter-mapping>
49   </pre>
50   *
51   * @author S&eacute;bastien Pennec
52   */
53  public class LoggerContextFilter implements Filter {
54  
55      public void destroy() {
56          // do nothing
57      }
58  
59      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
60              throws IOException, ServletException {
61  
62          LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
63          ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
64          ContextJNDISelector sel = null;
65  
66          if (selector instanceof ContextJNDISelector) {
67              sel = (ContextJNDISelector) selector;
68              sel.setLocalContext(lc);
69          }
70  
71          try {
72              chain.doFilter(request, response);
73          } finally {
74              if (sel != null) {
75                  sel.removeLocalContext();
76              }
77          }
78      }
79  
80      public void init(FilterConfig arg0) throws ServletException {
81          // do nothing
82      }
83  }