Log4j Configuration Using XML File

In this article, you will see how to generate logs using a XML file configured externally.

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml


log4j.xml provides some advanced configuration options such as Filter, ErrorHandlers and few advanced Appenders.

1. XML file

The following configuration creates the same result as in previous article.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
 <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
   <layout class="org.apache.log4j.PatternLayout">
     <param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n"/>
	  <priority value="info"></priority>
	  <appender-ref ref="stdout"/>

2. Log4j in Java Program

The following Java class is a very simple example that initializes, and then uses, the Log4J logging library for Java applications.

package com.kruders;

import org.apache.log4j.Logger;

public class HelloWorld {
	static final Logger logger = Logger.getLogger(HelloWorld.class);
	public static void main(String[] args) {
		logger.info("Hello World!!!");

When you run the above example you’ll get an output like:

0 [main] INFO com.kruders.HelloWorld – Hello World!!!

You can download the source code of this example here.


No comments yet.

Leave a Reply