Link to home
Start Free TrialLog in
Avatar of rnayeneni
rnayeneni

asked on

How to use DOMconfigurator - Log4J

Hi Experts,

Can anybody help me how to do Log4j configuration using DOMConfigurator.

Step by Step approach.

Thanks.
Avatar of Mayank S
Mayank S
Flag of India image

DOMConfigurator.configure ( "path of XML configuration file" ) ;
Make sure you have the XML configuration file as per the correct schema. An example is posted here:

http://www.javaworld.com/javaforums/showflat.php?Cat=2&Board=TheoryPractice&Number=2396&page=0&view=collapsed&sb=11&o=&fpart=1
ASKER CERTIFIED SOLUTION
Avatar of Mayank S
Mayank S
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rnayeneni
rnayeneni

ASKER

in my case

i have created a URL provider to locate the path of config file.

and using single ton class which will initialize log4j
like the below
Context context = getInitialContext();
URL url = (URL) context.lookup("java:comp/env/UMGStartupRef");
if (url == null) {
      System.out.println("URL:ERROR - servlet was unable to load a startup configuration file (continuing).");
      return;
}
DOMConfigurator.configure(url);
System.out.println("Log4j config file being initialized ");

and in my code i am initalizing the single ton class

UMGHubConfig config = UMGHubConfig.getInstance();

and accessing logger
 Logger log = config.getLogger();
 log.debug("testing logging");
 log.info("testing info object");

and my config file is like



//-----------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
      <!-- 1  filter class added -->
      <!-- stdout is stdout -->
      <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
            <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
            </layout>
      </appender>
      <!-- ddl is <DEVLDBG> -->
      <appender name="ddl" class="org.apache.log4j.RollingFileAppender">
            <param name="File" value="/weblogs/umg/UMG_errorlog.log"/>
            <param name="Append" value="true"/>
            <param name="MaxBackupIndex" value="5"/>
            <param name="MaxFileSize" value="20MB"/>
            <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%d{MM-dd HH:mm:ss,SSS}[%5.5p]:%6.6t:%m%n"/>
            </layout>
      </appender>
      <!-- dl is <DBG> -->
      <appender name="dl" class="org.apache.log4j.RollingFileAppender">
            <param name="File" value="/weblogs/umg/UMG_errorlog.log"/>
            <param name="Append" value="true"/>
            <param name="MaxBackupIndex" value="5"/>
            <param name="MaxFileSize" value="20MB"/>
            <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%d{MM-dd HH:mm:ss,SSS}[%5.5p]%6.6t:%m%n"/>
            </layout>
      </appender>
      <!-- il is <INF> -->
      <appender name="il" class="org.apache.log4j.RollingFileAppender">
            <param name="File" value="/weblogs/umg/UMG_errorlog.log"/>
            <param name="Append" value="true"/>
            <param name="MaxBackupIndex" value="5"/>
            <param name="MaxFileSize" value="20MB"/>
            <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%d{MM-dd HH:mm:ss,SSS}[%5.5p]:%6.6t:%m%n"/>
            </layout>
      </appender>
      <!-- wl is <WAR> -->
      <appender name="wl" class="org.apache.log4j.RollingFileAppender">
            <param name="File" value="/weblogs/umg/UMG_errorlog.log"/>
            <param name="Append" value="true"/>
            <param name="MaxBackupIndex" value="5"/>
            <param name="MaxFileSize" value="10MB"/>
            <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%d{MM-dd HH:mm:ss,SSS}[%5.5p]:%t:%m%n"/>
            </layout>
      </appender>
      <!-- el is <ERR> -->
      <appender name="el" class="org.apache.log4j.RollingFileAppender">
            <param name="File" value="/weblogs/umg/UMG_errorlog.log"/>
            <param name="Append" value="true"/>
            <param name="MaxBackupIndex" value="5"/>
            <param name="MaxFileSize" value="10MB"/>
            <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%d{MM-dd HH:mm:ss,SSS}[%5.5p]:%t:%m%n"/>
            </layout>
      </appender>
      <!-- fl is <CRI> =Fatal -->
      <appender name="fl" class="org.apache.log4j.RollingFileAppender">
            <param name="File" value="/weblogs/umg/UMG_errorlog.log"/>
            <param name="Append" value="true"/>
            <param name="MaxBackupIndex" value="5"/>
            <param name="MaxFileSize" value="10MB"/>
            <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%d{MM-dd HH:mm:ss,SSS}[%5.5p]:%t:%m%n"/>
            </layout>
      </appender>
      <!-- errtelnet is telnet to ?.?.?.?:5678 -->
      <appender name="errtelnet" class="org.apache.log4j.net.TelnetAppender">
            <param name="Port" value="5678"/>
            <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%d{MM-dd HH:mm:ss,SSS}[%5.5p]:%t:%m%n"/>
            </layout>
      </appender>
      <!-- recslog is raw records log -->
      <appender name="recsl" class="org.apache.log4j.RollingFileAppender">
            <param name="File" value="/weblogs/umg/UMG_errorlog.log"/>
            <param name="Append" value="true"/>
            <param name="MaxBackupIndex" value="10"/>
            <param name="MaxFileSize" value="20MB"/>
            <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%d{MM-dd HH:mm:ss,SSS}[%5.5p]:%t:%m%n"/>
            </layout>
      </appender>
      <!-- healthlog is ndmhealthcheck.log -->
      <appender name="healthlog" class="org.apache.log4j.RollingFileAppender">
            <param name="File" value="/weblogs/umg/UMG_errorlog.log"/>
            <param name="Append" value="true"/>
            <param name="MaxBackupIndex" value="5"/>
            <param name="MaxFileSize" value="10MB"/>
            <layout class="org.apache.log4j.TTCCLayout">
                  <param name="DateFormat" value="ISO8601"/>
            </layout>
      </appender>
      <!-- xmllog is xml stmts log -->
      <appender name="xmll" class="org.apache.log4j.RollingFileAppender">
            <param name="File" value="/weblogs/umg/UMG_errorlog.log"/>
            <param name="Append" value="true"/>
            <param name="MaxBackupIndex" value="10"/>
            <param name="MaxFileSize" value="20MB"/>
            <layout class="org.apache.log4j.PatternLayout">
                  <param name="ConversionPattern" value="%d{MM-dd HH:mm:ss,SSS}[%5.5p]:%t:%m%n"/>
            </layout>
      </appender>
      <logger name="devldbg" additivity = "true">
            <appender-ref ref="ddl"/>
      </logger>
      <logger name="recordslog" additivity = "true" >
            <appender-ref ref="recsl"/>
      </logger>
      <logger name="xmllog" additivity = "true">
            <appender-ref ref="xmll"/>
      </logger>
      <logger name="com.adp.bsg.umg.hub" additivity = "true">
            <appender-ref ref="il"/>
      </logger>
      <logger name="debug" additivity = "true">
        <level value="debug"/>
        <appender-ref ref="dl"/>
      </logger>
      <logger name="info" additivity = "true">
            <appender-ref ref="il"/>
            <appender-ref ref="dl"/>
      </logger>
            <logger name="warn" additivity = "true">
            <appender-ref ref="wl"/>
            <appender-ref ref="dl"/>
         <appender-ref ref="il"/>
      </logger>
      <logger name="error" additivity = "true">
           <appender-ref ref="el"/>
         <appender-ref ref="dl"/>
         <appender-ref ref="il"/>
         <appender-ref ref="wl"/>
      </logger>
      <logger name="fatal" additivity = "true">
        <appender-ref ref="fl"/>
        <appender-ref ref="dl"/>
        <appender-ref ref="il"/>
        <appender-ref ref="wl"/>
        <appender-ref ref="el"/>
  </logger>
      <root>
            <!--appender-ref ref="stdout" /> -->
      </root>
</log4j:configuration>
----------------------------------------------//

it says
Log4j config file being initialized

and

But still no log files are getting created at location I have specified.
nothing is happening. Any ideas.
>> But still no log files are getting created at location I have specified.

Make sure you have permissions to write on those locations.
Oh ok. I will find out. Thanks a lot.
I found that I have all permissions.

I am pasting my singleton class code. Please have a look if you find any problems


/**
 *
 */

package com.adp.bsg.umg.hub;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

/**
 *
 * This is Singleton Class. It provide logger object and connection object.
 */
public class UMGHubConfig {

      /**
       *  singleton class instance variable
       */
      private static UMGHubConfig config = null;

      /**
       *  logger instance object
       */
      private static Logger logger = null;

      /**
       *  logger instace object
       */
      private DataSource dataSource = null;

      private static String loggerName = "com.adp.bsg.umg.hub";

      /**
       * constructor instatiate variables and values
       */
      private UMGHubConfig() {
            setupLog4jConfig();
            logger = Logger.getLogger(loggerName);
            intializeDataSource();
      }

      /**
       *
       * @return Instance of Singleton Class
       */
      public static synchronized UMGHubConfig getInstance() {
            if (config == null)
                  config = new UMGHubConfig();
            return config;
      }

      /**
       * Opens a JDBC connection.
       * @throws SQLException
       */
      protected Connection getConnection() throws SQLException {
            
            if(config==null)
                  throw new NullPointerException();
            
            Connection con = null;
            if(dataSource != null) {
                  con = dataSource.getConnection();
            }
            return con;
      }

      /**
       *
       * @return instance of Logger object.
       */
      public Logger getLogger() {
            logger = Logger.getLogger(loggerName);
            return logger;
      }

      /**
       * retrieves datasource from either a local source or JNDI lookup
       * @throws DaoException - if the DataSource could not be retrieved
       */
      private void intializeDataSource() {
            try {
                  InitialContext context = (InitialContext) getInitialContext();
                  dataSource = (DataSource) context.lookup("java:comp/env/jdbc/umg");
            } catch (Exception e) {
                  System.out.println("Unable lookup Datasource from JNDI Context");
            }
      }

      private static InitialContext getInitialContext()
                  throws NamingException {
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY,
                                    "com.ibm.websphere.naming.WsnInitialContextFactory");
                  //env.put(Context.PROVIDER_URL, ""); // Include Server Name and port.
            return new InitialContext(env);
      }

      private static void setupLog4jConfig() {

            try {
                  Context context = getInitialContext();
                  URL url = (URL) context
                              .lookup("java:comp/env/UMGStartupRef");
                  if (url == null) {
                        System.out.println("URL:ERROR - servlet was unable to load a startup configuration file (continuing).");
                        return;
                  }
                  DOMConfigurator.configure(url);
                  System.out.println("Log4j config file being initialized ");
            } catch (NamingException ne) {
                  System.out.println("Exception finding jndi object"+ ne.toString());
                  return;
            } catch (Exception e) {
                  System.out.println("******The Log4J watchdog configured in the UMGLoggerImpl could not be started!");
            }
      }
}
Did you try getting the root logger?
log4j.properties

#Default log level to ERROR. Other levels are INFO and DEBUG.
log4j.rootLogger=ERROR, ROOT
log4j.appender.ROOT=org.apache.log4j.RollingFileAppender
log4j.appender.ROOT.File=c:/temp/myapplication.log
log4j.appender.ROOT.MaxFileSize=1000KB
#Keep 5 old files around.
log4j.appender.ROOT.MaxBackupIndex=5
log4j.appender.ROOT.layout=org.apache.log4j.PatternLayout
#Format almost same as WebSphere's common log format.
log4j.appender.ROOT.layout.ConversionPattern=[%d] %t %c %-5p - %m%n

#Optionally override log level of individual packages or classes
log4j.logger.de.laliluna.logexample=INFO
log4j.logger.de.laliluna.logexample=DEBUG

--------------------------------------------------------------------------------------------------
package de.laliluna.logexample;
import org.apache.log4j.Logger;
import org.apache.log4j.*;


public class LogClass {

       private static org.apache.log4j.Logger log = Logger
          .getLogger(LogClass.class);

 public static void main(String[] args) {

       System.out.println("Logger class");
                  log.trace("Trace");
                  log.debug("Debug");
                  log.info("Info");
                  log.warn("Warn");
                  log.error("Error");
                  log.fatal("Fatal");

 }

}