Configure Log4j.xml file in java

Earlier we have seen configuring log4j with properties file. Now we will

see how to do the same with xml file. Below are steps to configure log4j with xml file.

Step 1: Download Log4j jar file. You can download from Apache Log4j

Step 2: Create a simple class named 'LoggerExample.java'

Step 3: Create log4j.xml file

Step 4: Attach log4j dependency to class path.

We will create few methods in the class to see different logging levels printing on the console. The below is the updated class 'LoggerExample.java'

package com.log;

import org.apache.log4j.Logger;

public class LoggerExample {

	 // get a logger instance
	public static Logger logger = Logger.getLogger(LoggerExample.class);

	public void testLoggerDebug() {
		logger.debug("Hello.. im in Debug method");
	}

	public void testLoggerInfo() {
		logger.info("Hello.. im in Info method");
	}

	public void testLoggerWarn() {
		logger.warn("Hello.. im in Warn method");
	}

	public void testLoggerError() {
		logger.error("Hello.. im in Error method");
	}

	public void testLoggerFatal() {
		logger.fatal("Hello.. im in Fatal method");
	}

	public static void main(String[] args) {
		LoggerExample example = new LoggerExample();
		example.testLoggerDebug();
		example.testLoggerInfo();
		example.testLoggerWarn();
		example.testLoggerError();
		example.testLoggerFatal();
	}
}

Log4j allows logging requests to print statements to multiple destinations which is called an appender. Currently, appenders exist for the ConsoleAppender appends log events to System.out or System.err using a layout specified by the user. The default target is System.out.

Now let us create sample Log4j.xml file as below:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
	<appender name="roller" class="org.apache.log4j.RollingFileAppender">
	<param name="maxFileSize" value="1MB" />
	 <param name="MaxBackupIndex" value="2"/>
		<param name="File" value="Applicationlog.log" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern"
				value="%d{yyyy-MMM-dd HH:mm:ss,SSS} [%t] %c %x%n  %-5p %m%n" />
		</layout>
	</appender>

	<root>
		<level value="DEBUG" />
		<appender-ref ref="roller" />
	</root>
</log4j:configuration>

After performing all the above steps, project structure should look like below:
Log4j xml structure

In the above log4j.xml we have used RollingFileAppender which extends FileAppender to backup the log files when they reach defined size. The default maximum size of a file is 10MB.

If you want to provide the max size, we can add below statement as param to RollingFileAppender.

<param name="maxFileSize" value="1MB" />

We can define 'MaxBackupIndex' option which determines the number of previously rolled files to preserve. MaxBackUp takes only a positive integer value. MaxBackUp value will be set to 1 by default. If we set it to zero, then no roll over occurs and the log file will be simply truncated when it reaches the MaxFileSize.

<param name="MaxBackupIndex" value="2"/>

For example, when the maxFileSize is reached to the specified size limit (here in our example 1MB), then the contents are archived in a file named Applicationlog.log.1 . When the max size limit is reached for the second time, Applicationlog.log.1 is renamed to Applicationlog.log.2 and contents from Applicationlog.log are archived to Applicationlog.log.1. This will continue until the defined maximum backup index (here in example MaxBackupIndex=2) is reached, after which the oldest log file is deleted on each rollover.

It is up to your requirement to have MaxBackupIndex and maxFileSize and totally depends on how much space you can accommodate. MaxBackupIndex times MaxFileSize will give you the maximum size of this particular log4j log file. For example, if MaxBackupIndex is 100 and MaxFileSize is 10MB, then the maximum space considered is 1GB.

In the above log4j.xml file, PatternLayout lets the user to specify the output format according to conversion patterns. We have discussed most of the patterns in previous article.

After executing the above program, we should get the below output :

2014-Sep-20 18:42:50,705 [main] com.log.LoggerExample 
  INFO  Hello.. im in Info method
2014-Sep-20 18:42:50,705 [main] com.log.LoggerExample 
  WARN  Hello.. im in Warn method
2014-Sep-20 18:42:50,705 [main] com.log.LoggerExample 
  ERROR Hello.. im in Error method
2014-Sep-20 18:42:50,705 [main] com.log.LoggerExample 
  FATAL Hello.. im in Fatal method
2014-Sep-20 18:42:54,675 [main] com.log.LoggerExample 
  DEBUG Hello.. im in Debug method
2014-Sep-20 18:42:54,679 [main] com.log.LoggerExample 
  INFO  Hello.. im in Info method
2014-Sep-20 18:42:54,679 [main] com.log.LoggerExample 
  WARN  Hello.. im in Warn method
2014-Sep-20 18:42:54,680 [main] com.log.LoggerExample 
  ERROR Hello.. im in Error method
2014-Sep-20 18:42:54,680 [main] com.log.LoggerExample 
  FATAL Hello.. im in Fatal method

And the project structure will look like below when the maxFileSize exceeds and then the MaxBackUpIndex param will come into picture.
Log4j xml with maxBackupIndex

Please feel free to comment for any questions / suggestions / observations.

Log4j Tutorials: 

Comments

Hi..i didnt find any material on PageFactory.please upload it.

can we put this "log4j.xml" file at project level??

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.