HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Log4j / log4j.xml example – Log4j xml configuration example

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 !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. MANIKANTA NUKALA

    April 1, 2020

    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**
    
    • Lokesh Gupta

      April 2, 2020

      Tried this LevelRangeFilter example.

  2. Diksha

    November 25, 2019

    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.

    • Lokesh Gupta

      November 25, 2019

      Log4j does not add or filter any statement. You need to handle it in application code.

    • MANIKANTA NUKALA

      April 1, 2020

      Use the following param tag inside your appender tag
      false will make the log to override the file. true will make the log to append to the file

  3. Another WebSphere Programmer

    October 12, 2019

    &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 ?

  4. sridhar

    June 25, 2019

    I have given only %m%n in my conversionPattern, but im getting a lot of data. why is that?

  5. bajirao gharage

    June 28, 2018

    Hi Sir,

    Actually we want to dynamic value from java code to print on every line of log file.

  6. Wasim

    March 16, 2017

    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

    • Lokesh Gupta

      March 16, 2017

      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.

  7. Paulo Tavares

    January 6, 2017

    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

    • Lokesh Gupta

      January 6, 2017

      You will need to pass hostnames at server startup parameters (usually using -D<paramaName>=<paramValue> format.)

  8. Ram

    October 7, 2016

    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 ?

    • Lokesh Gupta

      October 7, 2016

      &lt;appender-ref ref=&quot;console&quot;&gt;&lt;/appender-ref&gt;
      &lt;appender-ref ref=&quot;console&quot;&gt;&lt;/appender-ref&gt;
  9. Orlando

    December 3, 2015

    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

    • Lokesh Gupta

      December 4, 2015

      Looks like code you posted is lost.. Please paste the code inside [xml] … [/xml] tags.

  10. Vaibhav

    December 1, 2014

    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,

  11. Praful

    May 13, 2014

    <?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>
    
    • Lokesh Gupta

      May 13, 2014

      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;
      
  12. Praful

    May 13, 2014

    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.

    • Lokesh Gupta

      May 13, 2014

      Can’t see anything…:-( Please paste the code inside [ xml ]…[ /xml ] tag (without spaces in opening and closing tag ).

  13. 4XD7

    May 12, 2014

    Where save the files with this configuration?

  14. mateen

    October 8, 2013

    is it possible to code the entire log4j java file without xml and without properties if yes then please upload and update me

    • Lokesh Gupta

      October 8, 2013

      Read “Automatic Configuration” section in : http://logging.apache.org/log4j/2.x/manual/configuration.html

      “If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.”

Comments are closed on this article!

Search Tutorials

Log4j2 Tutorial

  • Log4j2 – Introduction
  • Log4j2 – JSON Config
  • Log4j2 – Properties Config
  • Log4j2 – XML Config
  • Log4j2 – ConsoleAppender
  • Log4j2 – RollingFileAppender
  • Log4j2 – Multiple appenders
  • Log4j2 – LevelRangeFilter
  • Log4j2 – HTMLLayout
  • Log4j2 – Fish Tagging
  • Log4j2 – Conversion Patterns
  • Log4j2 – JUnit

Log4j Tutorial

  • Log4j – Introduction
  • Log4j – Properties Config
  • Log4j – XML Config
  • Log4j – Maven Config
  • Log4j – Logging Levels
  • Log4j – ConsoleAppender
  • Log4j – RollingFileAppender
  • Log4j – SocketAppender
  • Log4j – JDBCAppender
  • Log4j – XMLLayout
  • Log4j – HTMLLayout
  • Log4j – Runtime Reload
  • Log4j vs. SLF4j
  • Log4j – RESTEasy + Tomcat 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)