1449
+ − 1 package goodjava.logger;
+ − 2
+ − 3 import java.io.File;
+ − 4 import java.io.FileWriter;
+ − 5 import java.io.IOException;
1473
+ − 6 import goodjava.io.IoUtils;
1449
+ − 7
+ − 8
+ − 9 public class RollingFileAppender extends WriterAppender {
+ − 10 protected final String fileName;
+ − 11 protected final File file;
+ − 12 public long maxFileSize = 10*1024*1024;
+ − 13 public int backups = 1;
+ − 14
+ − 15 public RollingFileAppender(Layout layout,String fileName) throws IOException {
+ − 16 super(layout,null);
+ − 17 this.fileName = fileName;
+ − 18 this.file = new File(fileName);
+ − 19 open();
+ − 20 }
+ − 21
+ − 22 protected void open() throws IOException {
+ − 23 this.writer = new FileWriter(file,true);
+ − 24 }
+ − 25
+ − 26 public synchronized void append(LoggingEvent event) {
+ − 27 super.append(event);
+ − 28 if( file.length() > maxFileSize ) {
+ − 29 rollOver();
+ − 30 }
+ − 31 }
+ − 32
+ − 33 protected void rollOver() {
+ − 34 close();
+ − 35 File backup = new File(fileName+'.'+backups);
+ − 36 try {
1473
+ − 37 IoUtils.delete(backup);
+ − 38 for( int i=backups-1; i>=1; i-- ) {
+ − 39 File f = backup;
+ − 40 backup = new File(fileName+'.'+i);
+ − 41 IoUtils.move(backup,f);
+ − 42 }
+ − 43 IoUtils.move(file,backup);
1449
+ − 44 open();
+ − 45 } catch(IOException e) {
+ − 46 throw new RuntimeException(e);
+ − 47 }
+ − 48 }
+ − 49 }