Tuesday, 14 June 2011

Load a properties files and use one of its properties to initialize log4j DOMConfigurator

In sample code below, we assume the main application configuration (properties) file is /opt/system.properties and it contains property LOG4J_XML_PATH which holds the full path to log4j xml configuration file. Of course, the configuration file can all other parameters required by the application.

public class ConfigFileReader{ 

    private static Properties systemProperties; 
    static {
        try {
            systemProperties = new Properties();
            systemProperties.load(new FileInputStream("/opt/system.properties"));
            String log4jpath=systemProperties.getProperty("LOG4J_XML_PATH");
            DOMConfigurator.configure(log4jpath);
       } catch (Exception e) {
              e.printStackTrace();
              System.exit(1);
       }
    }
}

log4j configuration quick start

The sample below will put you on track quickly to start using log4j. Before you begin, make sure to add log4j jar file in your CLASSPATH

public class Sample{
     static {
          DOMConfigurator.configure("C:/log4j.xml");
     }
     private static Logger logger = Logger.getLogger(Sample.class);

  public Sample() {
      logger.debug("Sample version 1.0");
  }
}

log4j.xml sample content(located under C:\log4j.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
<appender name="QuickStart" class="org.apache.log4j.RollingFileAppender">
<param name="Encoding" value="UTF-8" />
<param name="File" value="C:/logs/application.log" />
<param name="MaxFileSize" value="10MB" />
<param name="MaxBackupIndex" value="10" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{DATE} [%t] %-5p %c{1} - %m%n" />
</layout>
</appender>
<root>
<priority value="debug" />
<appender-ref ref="QuickStart" />
</root>
</log4j:configuration>