HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

log4j.xml example – Log4j xml configuration example

By Lokesh Gupta | Filed Under: Log4j

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

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

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

21
Leave a Reply

This comment form is under antispam protection
13 Comment threads
8 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
13 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
Diksha

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.

Vote Up0Vote Down  Reply
13 days ago
Lokesh Gupta

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

Vote Up0Vote Down  Reply
13 days ago
Another WebSphere Programmer
&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 ?

Vote Up0Vote Down  Reply
1 month ago
sridhar

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

Vote Up0Vote Down  Reply
5 months ago
bajirao gharage

Hi Sir,

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

Vote Up0Vote Down  Reply
1 year ago
Wasim

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

Vote Up0Vote Down  Reply
2 years ago
Lokesh Gupta
String fileName = "c:/temp/info.log";

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.

Vote Up0Vote Down  Reply
2 years ago
Paulo Tavares

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

Vote Up0Vote Down  Reply
2 years ago
Lokesh Gupta

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

Vote Up0Vote Down  Reply
2 years ago
Ram

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 ?

Vote Up0Vote Down  Reply
3 years ago
Lokesh Gupta
<appender-ref ref="console"></appender-ref>
<appender-ref ref="console"></appender-ref>
Vote Up0Vote Down  Reply
3 years ago
Orlando

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

Vote Up0Vote Down  Reply
4 years ago
Lokesh Gupta

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

Vote Up0Vote Down  Reply
4 years ago
Vaibhav

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,

Vote Up0Vote Down  Reply
5 years ago
Praful
<?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>
Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

You can use <param name="Append" value="true" />

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

<log4j:configuration debug="true">
  <appender name="ROLL" class="org.apache.log4j.rolling.RollingFileAppender">
    <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
      <param name="FileNamePattern" value="/wombat/foo.%d{yyyy-MM}.gz"/>
    </rollingPolicy>
    <param name="Append" value="true" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%c{1} - %m%n"/>
    </layout>
  </appender>
  <root">
    <appender-ref ref="ROLL"/>
  </root>
</log4j:configuration>
Vote Up0Vote Down  Reply
5 years ago
Praful

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.

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

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

Vote Up0Vote Down  Reply
5 years ago
4XD7

Where save the files with this configuration?

Vote Up0Vote Down  Reply
5 years ago
mateen

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

Vote Up0Vote Down  Reply
6 years ago
Lokesh Gupta

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.”

Vote Up0Vote Down  Reply
6 years ago

Search Tutorials

Log4j2 Tutorial

  • Log4j2 – Introduction
  • Log4j2 – JSON Config
  • Log4j2 – Properties Config
  • Log4j2 – XML Config
  • 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

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

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 © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz