Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Tutorials Log4j FileAppender in Log4j

Related Tutorials


 
 

Share on Google+Share on Google+

FileAppender in Log4j

Advertisement
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 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

 

     

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 11, 2008

Related Tutorials

Discuss: FileAppender in Log4j   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
Rodislav
September 23, 2011
Big Thanks!!!!

VERY BIG THANKS!
DMCA.com