comparison src/goodjava/logger/RollingFileAppender.java @ 1449:dd14d2dce7ee

add appenders
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 28 Feb 2020 21:14:23 -0700
parents
children 6c6ce14db6a8
comparison
equal deleted inserted replaced
1448:6fc083e1d08c 1449:dd14d2dce7ee
1 package goodjava.logger;
2
3 import java.io.File;
4 import java.io.FileWriter;
5 import java.io.IOException;
6
7
8 public class RollingFileAppender extends WriterAppender {
9 protected final String fileName;
10 protected final File file;
11 public long maxFileSize = 10*1024*1024;
12 public int backups = 1;
13
14 public RollingFileAppender(Layout layout,String fileName) throws IOException {
15 super(layout,null);
16 this.fileName = fileName;
17 this.file = new File(fileName);
18 open();
19 }
20
21 protected void open() throws IOException {
22 this.writer = new FileWriter(file,true);
23 }
24
25 public synchronized void append(LoggingEvent event) {
26 super.append(event);
27 if( file.length() > maxFileSize ) {
28 rollOver();
29 }
30 }
31
32 protected void rollOver() {
33 close();
34 File backup = new File(fileName+'.'+backups);
35 if( backup.exists() ) {
36 if( !backup.delete() )
37 debug("couldn't delete "+backup);
38 }
39 for( int i=backups-1; i>=1; i-- ) {
40 File f = backup;
41 backup = new File(fileName+'.'+i);
42 backup.renameTo(f);
43 }
44 if( !file.renameTo(backup) )
45 debug("couldn't rename "+file+" to "+backup);
46 try {
47 open();
48 } catch(IOException e) {
49 throw new RuntimeException(e);
50 }
51 }
52
53 protected void debug(String msg) {
54 System.err.println("RollingFileAppender: "+msg);
55 }
56 }