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.*;
|
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> |