Basic steps to configure Log4j using xml and properties file

This example demonstrated how to configure Log4j setup using the Properties file and XML file. These are the two most widely used techniques for configuring the Log4j for your application. But, in the recent days configuring with properties files are considered to be old technique and recommended using XML.

This example program uses simple standalone java program for running the example. But, in most of the project scenarios it will be used in the web application. However the configuration file will be the same.

You would consider reading the list of Java books recommended.

If you are Java developer and would like to receive the daily updates on Java tips or techniques, please subscribe here.

Configure Log4j

log4j.properties

It is the traditional properties file for configuring the log4j mechanism. It is not used by most of the projects because of the XML configuration’s flexibility.

# Set root logger level to DEBUG and its only appender
              to Appender1.
log4j.rootLogger=INFO, Appender1,Appender2

# Appender1 is set to be a ConsoleAppender.
log4j.appender.Appender1=org.apache.log4j.
                                ConsoleAppender
log4j.appender.Appender2=org.apache.log4j.
                              RollingFileAppender
log4j.appender.Appender2.File=sample.log

# Appender2 uses PatternLayout.
log4j.appender.Appender1.layout=org.apache.log4j.
                                       PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=
                               %-4r [%t] %-5p %c %x - %m%n

log4j.appender.Appender2.layout=org.apache.log4j.
                                        PatternLayout
log4j.appender.Appender2.layout.ConversionPattern=
                                 %-4r [%t] %-5p %c %x - %m%n

log4j.xml

It is mostly used and recommended configuration for setting up the log4j mechanism.

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

xmlns:log4j=
              "http://jakarta.apache.org/log4j/"
               debug="false">

   <appender name="consoleAppender"
      class="org.apache.log4j.ConsoleAppender">
      <param name="Threshold" value="INFO" />
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d
             %-5p  [%c{1}] %m %n" />
      </layout>
   </appender>

   <appender name="fileAppender"
           class="org.apache.log4j.RollingFileAppender">
      <param name="Threshold" value="INFO" />
      <param name="File" value="sample.log"/>
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d
                %-5p  [%c{1}] %m %n" />
      </layout>
   </appender>

   <logger name="javabeat.net.log4j" additivity="false" >
      <level value="INFO" />
      <appender-ref ref="consoleAppender"/>
      <appender-ref ref="fileAppender"/>
   </logger>

</log4j:configuration>

Log4jPropertyTest.java

package javabeat.net.log4j;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 * source : www.javabeat.net
 */
public class Log4jPropertyTest {
    private static Logger logger = Logger.getLogger
               (Log4jPropertyTest.class);
    public static void main (String args[]){
        PropertyConfigurator.configure("log4j.properties");
        logger.info("Test Log");
    }
}

Log4jXmlTest.java

package javabeat.net.log4j;

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

/**
 * source : www.javabeat.net
 */
public class Log4jXmlTest {
    private static Logger logger = Logger.getLogger
                (Log4jXmlTest.class);
    public static void main (String args[]){
        DOMConfigurator.configure("log4j.xml");
        logger.info("Test Log");
    }

}

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Best article on Log4j! Saved my time! Thank you.

    • suthukrish says:

      Thanks you for the comments!! If you have any issues on configuring the log4j, please post it here.

      Thanks,
      Krishna

    • Thank you for reading the articles. Please post it here If you have any suggestions.

  2. Shweta says:

    I want my log file to get generated in a generalised unix server location, how can i specify the location in log4j.xml? Can the file name be specified as under??
    <param name="File" value="${root}Application/logs/Myservice.log"/>

  3. Thanks for the article, but i think there is a little mistake in the title ;)

  4. when i tried to implement logger using xml file got this
    “java.io.filenot found exception : E:iRapidiRapideclipselog4j.xml (The system cannot find the file specified)”
    Cant we give path of log4j.xml file of our project instead of storing it to eclipse folder

  5. Provide some explanation instead of just pasting some code. difficult to understand for a beginner in Log4j

  6. Nice article.
    one question if my log4j.properties available on classpath can I remove following line
    PropertyConfigurator.configure(“log4j.properties”);

  7. gurpreet bajwa says:

    Hi,
    I wanted to know how the log4j jar reads the data in the log4j.xml? Where can I find that particular piece of code?

  8. I followed instructions as mentioned but getting the following exception:

    Exception in thread “main” java.lang.ExceptionInInitializerError
    Caused by: java.lang.ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext

    Plz help

    • Eduardo says:

      Me too

      • Hey Eduardo
        I got this exception because I didnt downloaded the xact jar file
        it should be “log4j-1.2.17.jar”
        try importing this file
        and include “import org.apache.log4j.Logger;”.
        worked in my case you should also try :)

  9. Hi Srinivasan,

    I have below in my log4j.properties file:

    log4j.logger.com.google.code=WARN
    log4j.logger.com.carrotsearch=WARN
    log4j.logger.com.sun=WARN
    log4j.logger.httpclient=WARN
    log4j.logger.net.spymemcached=WARN
    log4j.logger.org.apache.commons.httpclient=ERROR
    log4j.logger.org.apache=WARN
    log4j.logger.org.carrot2=WARN
    log4j.logger.org.json=WARN
    log4j.logger.sf.net=WARN
    log4j.logger.sun.net=WARN

    log4j.threshold=ALL
    log4j.rootLogger=ALL, InfoAppender, WarnAppender, ErrorAppender

    log4j.appender.InfoAppender=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.InfoAppender.File=/logfiles/info.log


    log4j.logger.REF_API_HIT_LOGGER=INFO, RefApiHitAppender
    log4j.additivity.REF_API_HIT_LOGGER=false
    log4j.appender.RefApiHitAppender=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.RefApiHitAppender.File=/logfiles/ref_api_hits.log
    log4j.appender.RefApiHitAppender.layout=org.apache.log4j.PatternLayout
    log4j.appender.RefApiHitAppender.layout.ConversionPattern=%m%n
    log4j.appender.RefApiHitAppender.Threshold=INFO
    log4j.appender.RefApiHitAppender.DatePattern=’.’yyyy-MM-dd

    What would be log4j2 xml configuration for this? What do i write in my xml file for this configuration??

  10. I used above code for log4j.xml and log4test.java. Code compiles fine but did not show output in console as well as in Log file. What could be the reason.

Trackbacks

  1. JavaPins says:

    Basic steps to configure Log4j using xml and properties file…

    Thank you for submitting this cool story – Trackback from JavaPins…

Speak Your Mind

*