View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * 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  package org.apache.logging.log4j.web;
18  
19  import java.io.IOException;
20  import javax.servlet.Filter;
21  import javax.servlet.FilterChain;
22  import javax.servlet.FilterConfig;
23  import javax.servlet.ServletContext;
24  import javax.servlet.ServletException;
25  import javax.servlet.ServletRequest;
26  import javax.servlet.ServletResponse;
27  
28  import org.apache.logging.log4j.Logger;
29  import org.apache.logging.log4j.status.StatusLogger;
30  
31  /**
32   * This is responsible for the following:
33   * <ul>
34   *     <li>Clearing the logger context when the application has finished starting up.</li>
35   *     <li>Setting the logger context before processing a request and clearing it after processing a request.</li>
36   *     <li>Setting the logger context when the application is starting to shut down.</li>
37   * </ul>
38   * This filter is a once-per-request filter. It is capable of filtering all the different types of requests
39   * (standard, asynchronous, error, etc.) but will not apply processing if the filter matches multiple times on the same
40   * logical request.
41   */
42  public class Log4jServletFilter implements Filter {
43  
44      private static final Logger LOGGER = StatusLogger.getLogger();
45  
46      static final String ALREADY_FILTERED_ATTRIBUTE = Log4jServletFilter.class.getName() + ".FILTERED";
47  
48      private ServletContext servletContext;
49      private Log4jWebLifeCycle initializer;
50  
51      @Override
52      public void init(final FilterConfig filterConfig) throws ServletException {
53          this.servletContext = filterConfig.getServletContext();
54          LOGGER.debug("Log4jServletFilter initialized.");
55  
56          this.initializer = WebLoggerContextUtils.getWebLifeCycle(this.servletContext);
57          this.initializer.clearLoggerContext(); // the application is mostly finished starting up now
58      }
59  
60      @Override
61      public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
62              throws IOException, ServletException {
63          if (request.getAttribute(ALREADY_FILTERED_ATTRIBUTE) != null) {
64              chain.doFilter(request, response);
65          } else {
66              request.setAttribute(ALREADY_FILTERED_ATTRIBUTE, Boolean.TRUE);
67  
68              try {
69                  this.initializer.setLoggerContext();
70  
71                  chain.doFilter(request, response);
72              } finally {
73                  this.initializer.clearLoggerContext();
74              }
75          }
76      }
77  
78      @Override
79      public void destroy() {
80          if (this.servletContext == null || this.initializer == null) {
81              throw new IllegalStateException("Filter destroyed before it was initialized.");
82          }
83          LOGGER.debug("Log4jServletFilter destroyed.");
84  
85          this.initializer.setLoggerContext(); // the application is just now starting to shut down
86      }
87  }