[an error occurred while processing this directive]

FileAppender in Log4j

                         

In previous section we have used ConsoleAppender to append log events. We can also append these log events to a file by using FileAppender.

 

 

 

 

FileAppender constructor can be created in the following way:

 FileAppender fileappender = new FileAppender();

It does not do any thing. So we have to use any one of the following:

FileAppender fileappender = 
new FileAppender(Layout layout, String filename);

It will instantiate an fileappender object with layout and filename as provided.

FileAppender fileappender = 
new FileAppender(Layout layout, String filename, boolean append);

It will instantiate an fileappender object with layout and will append log events to given filename and third parameter of boolean type denotes whether to append file or not. Since FileAppender throws exception so we need to handle exception.

Here is the example code for FileAppenderExample class :

FileAppenderExample.java

import org.apache.log4j.*;
public class FileAppenderExample {
  static Logger logger = Logger.getLogger("FileAppenderExample.class");
  public static void main(String[] args)throws Exception {
    FileAppender fileappender = 
   
new FileAppender(new PatternLayout(),"output.txt");
    logger.addAppender(fileappender);
    logger.info("Log has been appended to your output.txt");  
    logger.info("See your output.txt");    
  }
}

Compilation and execution of FileAppenderExample class will create "output.txt" file for the first time then will append log events to it.

Output:

Download Source Code

 

                         

[an error occurred while processing this directive]