001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.web;
018
019import java.io.IOException;
020import javax.servlet.Filter;
021import javax.servlet.FilterChain;
022import javax.servlet.FilterConfig;
023import javax.servlet.ServletContext;
024import javax.servlet.ServletException;
025import javax.servlet.ServletRequest;
026import javax.servlet.ServletResponse;
027
028/**
029 * This is responsible for the following:
030 * <ul>
031 *     <li>Clearing the logger context when the application has finished starting up.</li>
032 *     <li>Setting the logger context before processing a request and clearing it after processing a request.</li>
033 *     <li>Setting the logger context when the application is starting to shut down.</li>
034 * </ul>
035 * This filter is a once-per-request filter. It is capable of filtering all the different types of requests
036 * (standard, asynchronous, error, etc.) but will not apply processing if the filter matches multiple times on the same
037 * logical request.
038 */
039public class Log4jServletFilter implements Filter {
040
041    static final String ALREADY_FILTERED_ATTRIBUTE = Log4jServletFilter.class.getName() + ".FILTERED";
042
043    private ServletContext servletContext;
044    private Log4jWebInitializer initializer;
045
046    @Override
047    public void init(final FilterConfig filterConfig) throws ServletException {
048        this.servletContext = filterConfig.getServletContext();
049        this.servletContext.log("Log4jServletFilter initialized.");
050
051        this.initializer = Log4jWebInitializerImpl.getLog4jWebInitializer(this.servletContext);
052        this.initializer.clearLoggerContext(); // the application is mostly finished starting up now
053    }
054
055    @Override
056    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
057            throws IOException, ServletException {
058        if (request.getAttribute(ALREADY_FILTERED_ATTRIBUTE) != null) {
059            chain.doFilter(request, response);
060        } else {
061            request.setAttribute(ALREADY_FILTERED_ATTRIBUTE, true);
062
063            try {
064                this.initializer.setLoggerContext();
065
066                chain.doFilter(request, response);
067            } finally {
068                this.initializer.clearLoggerContext();
069            }
070        }
071    }
072
073    @Override
074    public void destroy() {
075        if (this.servletContext == null || this.initializer == null) {
076            throw new IllegalStateException("Filter destroyed before it was initialized.");
077        }
078        this.servletContext.log("Log4jServletFilter destroyed.");
079
080        this.initializer.setLoggerContext(); // the application is just now starting to shut down
081    }
082}