001package com.nimbusds.common.servlet;
002
003
004import java.io.InputStream;
005
006import javax.servlet.ServletContext;
007import javax.servlet.ServletContextEvent;
008import javax.servlet.ServletContextListener;
009
010import org.apache.log4j.Logger;
011import org.apache.log4j.LogManager;
012import org.apache.log4j.PropertyConfigurator;
013
014
015/**
016 * Configures Log4j logging at servlet context startup. 
017 *
018 * <p>The name / path of the Log4j properties file is specified in a servlet 
019 * context init parameter {@code log4j.configurationFile}.
020 */
021public class Log4jConfigurator implements ServletContextListener {
022        
023        
024        /**
025         * Handler for servlet context startup events; configures Log4j using
026         * the properties file specified in the servlet context parameter
027         * {@code log4j.configurationFile}. 
028         *
029         * <p>The properties file location must be relative to the web 
030         * application directory, e.g. {@code /WEB-INF/log4j.properties}.
031         *
032         * <p>Upon successful Log4j initialisation logs the event at INFO 
033         * level.
034         *
035         * @param sce A servlet context event.
036         */
037        @Override
038        public void contextInitialized(ServletContextEvent sce) {
039
040                ServletContext servletContext = sce.getServletContext();
041
042                String configFile = servletContext.getInitParameter("log4j.configurationFile");
043                
044                if (configFile == null || configFile.trim().isEmpty())
045                        return; // Logging disabled
046                
047                InputStream is = servletContext.getResourceAsStream(configFile);
048                
049                if (is == null)
050                        return;
051                
052                PropertyConfigurator.configure(is);
053                        
054                Logger logger = LogManager.getLogger(Log4jConfigurator.class);
055                logger.info("Configured Log4j from properties file " + configFile);
056        }
057
058
059        /**
060         * Handler for servlet context shutdown events.
061         *
062         * @param sce A servlet context event.
063         */
064        @Override
065        public void contextDestroyed(ServletContextEvent sce) {
066
067                // Do nothing
068        }
069}