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