Log4J configuration in web.xml

Posted by Anusha Reddy

Got Log4J warnings on application server startup, because of its initialization after StrutsTilesListener, Spring ContextLoaderListener, etc. Also, we won't get all the struts, spring, hibernate debug log messages from their initialization.

If we refer to the log4j.properties file, from WEB-INF/classes folder of the application, we can place the Log4JConfigListener as the first listener after the filter configurations, whatever used.

If we are referring to the log4j.properties file from a directory outside the application, then we need to get the file path to load the log4j configuration file.

One example is: http://www.coderanch.com/t/362833/Servlets/java/log-ServletContextListener, but this is tomcat application server specific.

We can pass the file path as an argument to the JVM, as environment variable (-Denv_var_name). Configure a ServletContextListener implementation class, and read the log4j.properties file, from its contextInitialized() method, by accessing the file path passed as JVM argument.

   
        package.hierarchy.listener.Log4JInitializationListener
   


        public class Log4JInitializationListener implements ServletContextListener {
                 private static Logger log = Logger.getLogger(Log4JInitListener.class);  
               
                 @Override
                  public void contextInitialized(ServletContextEvent sce) {
                           String filePath="";
                           RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
                           List argList=RuntimemxBean.getInputArguments();
                           for(int i=0;i                                  String[] vmArgs = argList.get(i).split("=");
                                  if(vmArgs[0] != null && vmArgs[0].equalsIgnoreCase("-Denv_var_name"))
                                           filePath=vmArgs[1];
                           }   

                           filePath=filePath+"/log4j.properties";
                           java.net.URL configURL=new URL(filePath);

                           org.apache.log4j.BasicConfigurator.resetConfiguration(); 
                           org.apache.log4j.PropertyConfigurator.configure(configURL);

                            if (configURL.getProtocol().equals("file")) {
                                      log.info("Watching file: " + configURL.getFile());
                                      org.apache.log4j.PropertyConfigurator.configureAndWatch(configURL.getFile()); 
                            }                   }

                  @Override
                   public void contextDestroyed(ServletContextEvent sce) {
                             log.info("context destroyed from Log4JInitializationListener");
                   }
         }
      


0 comments:

Post a Comment