View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, 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 java.io.IOException;
17  
18  import javax.servlet.Filter;
19  import javax.servlet.FilterChain;
20  import javax.servlet.FilterConfig;
21  import javax.servlet.ServletException;
22  import javax.servlet.ServletRequest;
23  import javax.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>To use it, add the following lines to a web.xml file
37   *  
38   * <filter>
39   *   <filter-name>LoggerContextFilter</filter-name>
40   *   <filter-class>
41   *     ch.qos.logback.classic.selector.servlet.LoggerContextFilter
42   *   </filter-class>
43   * </filter>
44   * <filter-mapping>
45   *   <filter-name>LoggerContextFilter</filter-name>
46   *   <url-pattern>/*</url-pattern>
47   * </filter-mapping>
48   * 
49   * @author S&eacute;bastien Pennec
50   */
51  public class LoggerContextFilter implements Filter {
52  
53      public void destroy() {
54          // do nothing
55      }
56  
57      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
58  
59          LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
60          ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
61          ContextJNDISelector sel = null;
62  
63          if (selector instanceof ContextJNDISelector) {
64              sel = (ContextJNDISelector) selector;
65              sel.setLocalContext(lc);
66          }
67  
68          try {
69              chain.doFilter(request, response);
70          } finally {
71              if (sel != null) {
72                  sel.removeLocalContext();
73              }
74          }
75      }
76  
77      public void init(FilterConfig arg0) throws ServletException {
78          // do nothing
79      }
80  }