WriterAppender in Log4j

In our previous section we have seen that we can append log events in simple file (plain/text) file and to the console also.

WriterAppender in Log4j

WriterAppender in Log4j

     

In our previous section we have seen that we can append log events in simple file (plain/text) file and to the console also. If we want to write files then we have to use WriterAppender. WriterAppender appends log events to a Writer or an OutputStream depending on the user's choice.

In our example we have created a class WriterAppenderExample . First we need to create logger object and then we have to add appender to it. So we have created an object of WriterAppender and since it requires Writer or OutputStream we are using a file "Writer.html". We have taken layout of HTML format that therefore we have to use HTMLLayout.

logger.addAppender(writeappender); will add writerappender to logger and all logging events will be added to this HTML file. 

Here is the example code for WriterAppenderExample class:

WriterAppenderExample.java

import java.io.*;
import org.apache.log4j.*;
public class WriterAppenderExample {

  static Logger logger = 
  Logger.getLogger
("WriterAppenderExample.class");
  public static void main(String[] args) {
  try{
  FileOutputStream filename=
  new 
FileOutputStream("Writer.html");
  WriterAppender writeappender = 
  new 
WriterAppender(new HTMLLayout(),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());  
  }  
  }
}

Output:

After compilation and execution of WriterAppenderExample.java will add the log events in  "Writer.html" file in the HTML format as since we have used HTMLLayout() . Output will look like this.

Download Source Code