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.*;
|
Compilation and execution of FileAppenderExample class will create "output.txt" file for the first time then will append log events to it.
Output: