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 javax.servlet.ServletContext;
020    import javax.servlet.ServletContextEvent;
021    import javax.servlet.ServletContextListener;
022    
023    /**
024     * In environments older than Servlet 3.0, this initializer is responsible for starting up Log4j logging before anything
025     * else happens in application initialization. In all environments, this shuts down Log4j after the application shuts
026     * down.
027     */
028    public class Log4jServletContextListener implements ServletContextListener {
029    
030        private ServletContext servletContext;
031        private Log4jWebLifeCycle initializer;
032    
033        @Override
034        public void contextInitialized(final ServletContextEvent event) {
035            this.servletContext = event.getServletContext();
036            this.servletContext.log("Log4jServletContextListener ensuring that Log4j starts up properly.");
037    
038            this.initializer = Log4jWebInitializerImpl.getLog4jWebInitializer(this.servletContext);
039            try {
040                this.initializer.start();
041                this.initializer.setLoggerContext(); // the application is just now starting to start up
042            } catch (final IllegalStateException e) {
043                throw new IllegalStateException("Failed to initialize Log4j properly.", e);
044            }
045        }
046    
047        @Override
048        public void contextDestroyed(final ServletContextEvent event) {
049            if (this.servletContext == null || this.initializer == null) {
050                throw new IllegalStateException("Context destroyed before it was initialized.");
051            }
052            this.servletContext.log("Log4jServletContextListener ensuring that Log4j shuts down properly.");
053    
054            this.initializer.clearLoggerContext(); // the application is finished shutting down now
055            this.initializer.stop();
056        }
057    }