Use of XMLLayout in Log4j

In the previous sections we have used PatternLayout and SimpleLayout, now we are going to describe you how to use XMLLayout class to produce logging output in the XML format.

Use of XMLLayout in Log4j

Use of XMLLayout in Log4j

     

In the previous sections we have used PatternLayout and SimpleLayout, now we are going to describe you how to use XMLLayout class to produce logging output in the XML format. XMLLayout produces output in the series of <log4j:event> tags or elements as specified in the log4j.dtd.

In this example we have firstly called getLogger() method  which in turns returns an object of class Logger. For creating XML output file we have used WriterAppender and this appender is being added in to logger with the addAppender() method.

Here is the example code of XMLLayoutExample.java:

import java.io.*;
import org.apache.log4j.*;
import org.apache.log4j.xml.XMLLayout;

public class XMLLayoutExample {
  static Logger logger = 
  Logger.getLogger
("XMLLayoutExample.class");
  public static void main(String[] args) {
  try{
  FileOutputStream filename=
 
new FileOutputStream("XMLWriter.xml");
  WriterAppender writeappender = 
  new 
WriterAppender(new XMLLayout(),filename);
  logger.addAppender(writeappender);
  logger.info("Welcome");
  logger.info("to");
  logger.info("Rose India");
  logger.info("Writer Appender");
  logger.info("Example");
  logger.info("-----------");
  }catch(Exception e){
  System.out.println("Exception is ="+e.getMessage())
  }
  }
}

To run this example follow these steps as:

  • Create and save XMLLayoutExample.java
  • Compile and execute XMLLayoutExample
  • After this you will get XMLWriter.xml file as output like this:

Output:

<log4j:event logger="XMLLayoutExample.class" timestamp="1221114548406" level="INFO" thread="main">
<log4j:message><![CDATA[Welcome]]></log4j:message>
</log4j:event>

<log4j:event logger="XMLLayoutExample.class" timestamp="1221114548406" level="INFO" thread="main">
<log4j:message><![CDATA[to]]></log4j:message>
</log4j:event>

<log4j:event logger="XMLLayoutExample.class" timestamp="1221114548406" level="INFO" thread="main">
<log4j:message><![CDATA[Rose India]]></log4j:message>
</log4j:event>

<log4j:event logger="XMLLayoutExample.class" timestamp="1221114548406" level="INFO" thread="main">
<log4j:message><![CDATA[Writer Appender]]></log4j:message>
</log4j:event>

<log4j:event logger="XMLLayoutExample.class" timestamp="1221114548421" level="INFO" thread="main">
<log4j:message><![CDATA[Example]]></log4j:message>
</log4j:event>

<log4j:event logger="XMLLayoutExample.class" timestamp="1221114548421" level="INFO" thread="main">
<log4j:message><![CDATA[-----------]]></log4j:message>
</log4j:event>

Download Source Code