View Javadoc

1   /*
2    * Licensed to the University Corporation for Advanced Internet Development, 
3    * Inc. (UCAID) under one or more contributor license agreements.  See the 
4    * NOTICE file distributed with this work for additional information regarding
5    * copyright ownership. The UCAID licenses this file to You under the Apache 
6    * License, Version 2.0 (the "License"); you may not use this file except in 
7    * compliance with the License.  You may obtain a copy of the License at
8    *
9    *    http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package edu.internet2.middleware.shibboleth.common.log;
19  
20  import java.io.IOException;
21  
22  import javax.servlet.Filter;
23  import javax.servlet.FilterChain;
24  import javax.servlet.FilterConfig;
25  import javax.servlet.ServletException;
26  import javax.servlet.ServletRequest;
27  import javax.servlet.ServletResponse;
28  
29  import org.slf4j.MDC;
30  
31  /**
32   * A Servlet filter which clears all the MDC state that has been accumulated during the processing of a request. It
33   * should be installed as near as possible to the beginning of the effective filter chain - and in particular prior to
34   * any filters which make use of MDC in their own logging - so that this filter will be last when the request stack
35   * unwinds.
36   */
37  public class SLF4JMDCCleanupFilter implements Filter {
38  
39      /** {@inheritDoc} */
40      public void destroy() {
41      }
42  
43      /** {@inheritDoc} */
44      public void init(FilterConfig filterConfig) throws ServletException {
45      }
46  
47      /** {@inheritDoc} */
48      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
49              ServletException {
50  
51          try {
52              chain.doFilter(request, response);
53          } finally {
54              MDC.clear();
55          }
56  
57      }
58  
59  }