log4j.xml example – Log4j xml configuration example

Log4j is a simple and flexible logging framework. Application logging equips the developer with detailed context for application failures. With log4j, it is possible to enable logging at runtime without modifying the application binary. The log4j package is designed so that these statements can remain in shipped code without incurring a heavy performance cost.

The two most common configuration options are in practice i.e. using log4j.xml configuration or using log4j.properties configuration.

In this log4j xml configuration tutorial, I am showing the example code for log4j.xml configuration.

Read more: Log4j properties file example

1. Log4j maven dependencies

Create a maven java project and update log4j dependencies.

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

2. log4j.xml file

This is the main configuration file having all runtime configuration used by log4j. This file will have log4j appenders information, log level information and output file names for file appenders.

Create this file and put in application classpath.

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'>

  <appender name="console" class="org.apache.log4j.ConsoleAppender">
    <param name="Target" value="System.out"/>
    <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
    </layout>
  </appender>

  <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="demoApplication.log"/>
    <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
    </layout>
  </appender>

  <root>
    <priority value ="debug"></priority>
    <appender-ref ref="console"></appender>
    <appender-ref ref="fileAppender"></appender>
  </root>

</log4j:configuration>

3. log4j.xml example

package com.howtodoinjava;

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

public class Log4jXmlConfigurationExample
{
	static Logger logger = Logger.getLogger(Log4jXmlConfigurationExample.class);

	public static void main(String[] args)
	{
		//DOMConfigurator is used to configure logger from xml configuration file
		DOMConfigurator.configure("log4j.xml");

		//Log in console in and log file
		logger.debug("Log4j appender configuration is successful !!");
	}
}

Output in console and demoApplication.log in project root folder:

[main] DEBUG com.howtodoinjava.Log4jXmlConfigurationExample - Log4j xml configuration is successful !!

Now let’s see some log4j.xml examples to output log messages to specific location.

4. Log4j console appender – Logging to console

Java program to output logs to console using ConsoleAppender.

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'>

  <appender name="console" class="org.apache.log4j.ConsoleAppender">
    <param name="Target" value="System.out"/>
    <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
    </layout>
  </appender>

  <root>
    <priority value ="debug"></priority>
    <appender-ref ref="console"></appender>
  </root>

</log4j:configuration>

4. Log4j rolling file appender – Logging to file

Java program to output logs to file using RollingFileAppender.

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'>

  <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="demoApplication.log"/>
    <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
    </layout>
  </appender>

  <root>
    <priority value ="debug"></priority>
    <appender-ref ref="fileAppender"></appender>
  </root>

</log4j:configuration>

Let me know if any question on log4j.xml configuration and usage.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

24 thoughts on “log4j.xml example – Log4j xml configuration example”

  1. I am using log4j configuration for my project. I want to exclude the warn messages from the log. I find that I need to add LevelRangeFilter in the xml configuration file for this. But, I am getting the following error:

    log4j: Trying to find [log4j.xml] using context classloader sun.misc.Launcher$AppClassLoader@73d16e93.
    log4j: Using URL [file:/D:/Mani/Sync/bin/log4j.xml] for automatic log4j configuration.
    log4j: Preferred configurator class: org.apache.log4j.xml.DOMConfigurator
    log4j: System property is :null
    log4j: Standard DocumentBuilderFactory search succeded.
    log4j: DocumentBuilderFactory is: org.apache.xerces.jaxp.DocumentBuilderFactoryImpl
    log4j:WARN Continuable parsing error 15 and column 90
    log4j:WARN Element type "LevelRangeFilter" must be declared.
    log4j:WARN Continuable parsing error 16 and column 13
    log4j:WARN The content of element type "appender" must match 
    "(errorHandler?,param*,rollingPolicy?,triggeringPolicy?,connectionSource?,layout?,filter*,appender-ref*)".
    log4j: debug attribute= "null".
    log4j: Ignoring debug attribute.
    log4j: reset attribute= "false".
    log4j: Threshold ="null".
    log4j: Level value for root is  [info].
    log4j: root level set to INFO
    log4j: Class name: [org.apache.log4j.ConsoleAppender]
    log4j: Setting property [target] to [System.out].
    log4j: Parsing layout of class: "org.apache.log4j.PatternLayout"
    log4j: Setting property [conversionPattern] to [%d{dd/MM/yyyy HH:mm:ss} %-5p %c{1} - %m%n].
    log4j:WARN **Unrecognized element LevelRangeFilter**
    
    Reply
  2. I want only fresh logs to be generated in my Log file each time when I run any scripts.
    Can you help on this what changes needs to be done in .xml file.

    Reply
  3. &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
    &lt;!DOCTYPE log4j:configuration PUBLIC &quot;-//LOG4J//DTD CONFIGURATION//EN&quot; &quot;http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/log4j.dtd&quot;&gt;
    
    
    &lt;log4j:configuration xmlns:log4j=&quot;http://jakarta.apache.org/log4j/&quot; debug=&quot;false&quot;&gt;
    
        &lt;appender name=&quot;defaultLog&quot; class=&quot;org.apache.log4j.DailyRollingFileAppender&quot;&gt;
            &lt;param name=&quot;File&quot; value=&quot;${log.path}\fcm.log&quot; /&gt;
            &lt;param name=&quot;append&quot; value=&quot;true&quot; /&gt;                  
            &lt;param name=&quot;encoding&quot; value=&quot;UTF-8&quot; /&gt;  
            &lt;param name=&quot;DatePattern&quot; value=&quot;'.'MM-dd-yyyy&quot; /&gt;   
            &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt;
    			&lt;param name=&quot;ConversionPattern&quot; value=&quot;[%-5p:%t][%X{USERID}][%X{SESSIONID}][%d{MM-dd-yyyy HH:mm:ss,SSS a Z}]%-c{1}: %n%m%n&quot;/&gt;
            &lt;/layout&gt;
        &lt;/appender&gt;
    
        &lt;root&gt;
    		&lt;level value=&quot;info&quot; /&gt;
    		&lt;appender-ref ref=&quot;defaultLog&quot; /&gt;
    	&lt;/root&gt;
    &lt;/log4j:configuration&gt;
    

    This looks correct to me. Also by using:
    private static Logger log = Logger.getLogger(ClassName.class);

    log.info does work and does write to the log file.

    But every time I start WebSphere Server I see in red:
    log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

    Also, Log4j.xml is under WEB-INF and log4j-1.2.16.jar is in the Java Build Path/Libraries.

    Can you tell me what is wrong with this setup ?

    Reply
  4. Hi,

    Thanks for sharing this.

    How can I log all console output to a file ?
    Console output like all the system output i.e system.out.print,system.err.print and all jvm related error/exceptions.

    Could you please help me here.

    Thanks,
    Wasim

    Reply
    • String fileName = &quot;c:/temp/info.log&quot;;
      
      System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(fileName))));
      System.setErr(new PrintStream(new BufferedOutputStream(new FileOutputStream(fileName))));
      

      After you run above code, all output will go to file.

      Reply
  5. Hi Lokesh!

    I’m new to log4j config. What I’m trying to do is add server name/hostname to the file name of the appender.
    Indeed I have the same EAR deployed into 2 different servers (a cluster) using Weblogic and I need server name/hostname to be replaced by the name of each server during start up of the app.
    I hope I’ve made myself clear.
    Can you help here?
    Here is the code:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true" threshold="debug">
    
        <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="%-4r %-5p [%t] %37c %3x - %m%n"/>
            </layout>
        </appender>
    
        <appender name="DFe" class="org.apache.log4j.RollingFileAppender">
            <param name="File" value="servers/${weblogic.Name}/logs/dfe_${HERE I WANT TO ADD SERVER NAME/HOSTNAME}.log"/>
            <param name="Append" value="true"/>
            <param name="MaxFileSize" value="10000KB"/>
            <param name="MaxBackupIndex" value="10"/>
    
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="%X{version} - %d %-5p [%c] %m%n"/>
            </layout>
        </appender>
    
        <logger name="br.com.synchro.dfe" additivity="false">
            <level value="debug"/>
            <appender-ref ref="DFe"/>
        </logger>
    
        <root>
            <priority value="error"/>
            <appender-ref ref="DFe"/>
        </root>
    </log4j:configuration>
    

    Thanks in advance.
    Paulo

    Reply
  6. I am seeing org.xml.sax.SAXParseException; systemId: file:/E:/Fresh%20Start/Practise%20Concepts%20Advanced/log4j-config.xml; lineNumber: 20; columnNumber: 35; The element type “appender-ref” must be terminated by the matching end-tag “”.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:205)
    at org.apache.log4j.xml.DOMConfigurator$1.parse(DOMConfigurator.java:749)
    at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:871)
    at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:755)
    at org.apache.log4j.xml.DOMConfigurator.configure(DOMConfigurator.java:896)
    at log4jdemo.Log4jFromXML.main(Log4jFromXML.java:13)

    And my xml file looks like

    
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    <log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'>
     
      <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
        </layout>
      </appender>
     
      <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
        <param name="File" value="demoApplication.log"/>
        <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
        </layout>
      </appender>
     
      <root>
        <priority value ="debug"></priority>
        <appender-ref ref="console"></appender>
        <appender-ref ref="fileAppender"></appender>
      </root>
     
    </log4j:configuration>
    
    
    

    As same as given above. Please tell me what shall i do ?

    Reply
  7. Hi,

    there is a possibility of a load a parameter file within properties the log4j.xml . I am using WebLogic Server within the server and have the search.properties file within the file and have routAux = / my / dir / out / so that in the log4j.xml can do something like this

    within the log4j.xml x. I am using WebLogic Server within the server and have the search.properties arhivo within the file and have routAux = / my / dir / out / so that in the log4j.xml can do something like this

    Reply
  8. HI,
    Thanks for posting this.
    I am new to the log4j configuration. The problem I am facing is, while printing the loggers on the server log I am getting %3D, %2C type of character instead of = & , characters & so on.
    I tried to put , but still problem is remaining as it is.
    Can you please guide me how to resolve this issue.
    When I searched on google, I came to know It’s encoding issue.

    Please suggest.
    Thanks,

    Reply
  9. <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
    <log4j:configuration>
    
    <appender name="file" class="org.apache.log4j.RollingFileAppender">
    		<param name="maxFileSize" value="10MB" />
    		<param name="maxBackupIndex" value="500000" />
    
    		<param name="File" value="C:/LOGS/test.log" />
    		<param name="threshold" value="info" />
    		<layout class="org.apache.log4j.PatternLayout">
    			<param name="ConversionPattern" value="%d %5p %c{1}:%L - %m%n" />
    		</layout>
    	</appender>
    
    <root>
    		<priority value="debug"></priority>
    		<appender-ref ref="errorfile" />
    		<appender-ref ref="debugfile" />
    		<appender-ref ref="file" />
    	</root>
    
    
    </log4j:configuration>
    
    Reply
    • You can use <param name="Append" value="true" />

      If want to backup file as well then you can use RollingFileAppender with TimeBasedRollingPolicy.

      &lt;log4j:configuration debug=&quot;true&quot;&gt;
        &lt;appender name=&quot;ROLL&quot; class=&quot;org.apache.log4j.rolling.RollingFileAppender&quot;&gt;
          &lt;rollingPolicy class=&quot;org.apache.log4j.rolling.TimeBasedRollingPolicy&quot;&gt;
            &lt;param name=&quot;FileNamePattern&quot; value=&quot;/wombat/foo.%d{yyyy-MM}.gz&quot;/&gt;
          &lt;/rollingPolicy&gt;
          &lt;param name=&quot;Append&quot; value=&quot;true&quot; /&gt;
          &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt;
            &lt;param name=&quot;ConversionPattern&quot; value=&quot;%c{1} - %m%n&quot;/&gt;
          &lt;/layout&gt;
        &lt;/appender&gt;
        &lt;root&quot;&gt;
          &lt;appender-ref ref=&quot;ROLL&quot;/&gt;
        &lt;/root&gt;
      &lt;/log4j:configuration&gt;
      
      Reply
  10. Hi below is my log4j.xml snippet, when my web application is deployed in websphere, log files are getting overwritten instead of backup files. Kindly guide me.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.