1 Reply Latest reply on Jun 17, 2005 9:36 AM by Stephane LAISNE

    Configuration of log4j

    Stephane LAISNE Newbie

      Hi at all,

      I've a problem to configure log4j in my J2EE application.

      I have a log4j.xml in my classpath, as follow:

      ?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

      <log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>








      <level="DEBUG"/>
      <appender-ref ref="PDM_STDOUT"/>


      </log4j:configuration>

      And I'm using the following class to set my logging context.

      public class PDMRepositorySelector implements RepositorySelector {
      private static boolean initialized = false;
      private static Object guard = LogManager.getRootLogger();

      private static Map repositories = new HashMap();
      private static LoggerRepository defaultRepository;

      /**
      * Register your web-app with this repository selector.
      */
      public static synchronized void init() throws ServletException {
      if( !initialized ) // set the global RepositorySelector
      {
      defaultRepository = LogManager.getLoggerRepository();
      RepositorySelector theSelector = new PDMRepositorySelector();
      LogManager.setRepositorySelector(theSelector, guard);
      initialized = true;
      }

      Hierarchy hierarchy = new Hierarchy(new RootCategory(Level.DEBUG));
      loadLog4JConfig(hierarchy);
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      repositories.put(loader, hierarchy);


      }

      public static synchronized void removeFromRepository() {
      repositories.remove(Thread.currentThread().getContextClassLoader());
      }

      private static void loadLog4JConfig(Hierarchy hierarchy) throws ServletException {
      try {
      String log4jFile = "log4j.xml";
      InputStream log4JConfig = Thread.currentThread().getContextClassLoader().getResourceAsStream(log4jFile);
      Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(log4JConfig);
      DOMConfigurator conf = new DOMConfigurator();
      conf.doConfigure(doc.getDocumentElement(), hierarchy);
      } catch (Exception e) {
      throw new ServletException(e);
      }
      }

      private PDMRepositorySelector() {
      }

      public LoggerRepository getLoggerRepository() {
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      LoggerRepository repository = (LoggerRepository)repositories.get(loader);

      if (repository == null) {
      return defaultRepository;
      } else {
      return repository;
      }
      }
      }


      After, I call it by:

      PDMRepositorySelector.init();

      The configure runs only once, why?