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     */
017    package org.apache.logging.log4j.web;
018    
019    import java.util.concurrent.locks.Lock;
020    import java.util.concurrent.locks.ReentrantLock;
021    import javax.servlet.ServletContext;
022    
023    import org.apache.logging.log4j.core.LoggerContext;
024    
025    /**
026     * Convenience methods for retrieving the {@link org.apache.logging.log4j.core.LoggerContext} associated with a
027     * particular ServletContext. These methods are most particularly useful for asynchronous servlets where the
028     * <abbr title="Thread Context ClassLoader">TCCL</abbr> is potentially different from the TCCL used by the
029     * Servlet container that bootstrapped Log4j.
030     *
031     * @since 2.0.1
032     */
033    public final class WebLoggerContextUtils {
034        private WebLoggerContextUtils() {
035        }
036    
037        private static final Lock WEB_SUPPORT_LOOKUP = new ReentrantLock();
038    
039        /**
040         * Finds the main {@link org.apache.logging.log4j.core.LoggerContext} configured for the given ServletContext.
041         *
042         * @param servletContext the ServletContext to locate a LoggerContext for
043         * @return the LoggerContext for the given ServletContext
044         * @throws java.lang.IllegalStateException if no LoggerContext could be found on the given ServletContext
045         * @since 2.0.1
046         */
047        public static LoggerContext getWebLoggerContext(final ServletContext servletContext) {
048            return (LoggerContext) servletContext.getAttribute(Log4jWebSupport.CONTEXT_ATTRIBUTE);
049        }
050    
051        /**
052         * Finds the main {@link org.apache.logging.log4j.core.LoggerContext} configured for the given ServletContext.
053         *
054         * @param servletContext the ServletContext to locate a LoggerContext for
055         * @return the LoggerContext for the given ServletContext or {@code null} if none was set
056         * @since 2.0.1
057         */
058        public static LoggerContext getRequiredWebLoggerContext(final ServletContext servletContext) {
059            final LoggerContext loggerContext = getWebLoggerContext(servletContext);
060            if (loggerContext == null) {
061                throw new IllegalStateException(
062                    "No LoggerContext found in ServletContext attribute " + Log4jWebSupport.CONTEXT_ATTRIBUTE);
063            }
064            return loggerContext;
065        }
066    
067        /**
068         * Finds or initializes the {@link org.apache.logging.log4j.web.Log4jWebLifeCycle} singleton for the given
069         * ServletContext.
070         *
071         * @param servletContext the ServletContext to get the Log4jWebLifeCycle for
072         * @return the Log4jWebLifeCycle for the given ServletContext
073         * @since 2.0.1
074         */
075        public static Log4jWebLifeCycle getWebLifeCycle(final ServletContext servletContext) {
076            WEB_SUPPORT_LOOKUP.lock();
077            try {
078                Log4jWebLifeCycle webLifeCycle = (Log4jWebLifeCycle) servletContext.getAttribute(
079                    Log4jWebSupport.SUPPORT_ATTRIBUTE);
080                if (webLifeCycle == null) {
081                    webLifeCycle = Log4jWebInitializerImpl.initialize(servletContext);
082                }
083                return webLifeCycle;
084            } finally {
085                WEB_SUPPORT_LOOKUP.unlock();
086            }
087        }
088    
089        /**
090         * Wraps a Runnable instance by setting its thread context {@link org.apache.logging.log4j.core.LoggerContext}
091         * before execution and clearing it after execution.
092         *
093         * @param servletContext the ServletContext to locate a LoggerContext for
094         * @param runnable       the Runnable to wrap execution for
095         * @return a wrapped Runnable
096         * @since 2.0.1
097         */
098        public static Runnable wrapExecutionContext(final ServletContext servletContext, final Runnable runnable) {
099            return new Runnable() {
100                @Override
101                public void run() {
102                    final Log4jWebSupport webSupport = getWebLifeCycle(servletContext);
103                    webSupport.setLoggerContext();
104                    try {
105                        runnable.run();
106                    } finally {
107                        webSupport.clearLoggerContext();
108                    }
109                }
110            };
111        }
112    }