comparison src/goodjava/logger/DailyRollingFileAppender.java @ 1600:8a717f0b7f45

add DailyRollingFileAppender.deleteAfter
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 09 Apr 2021 19:44:14 -0600
parents 329197048ff0
children
comparison
equal deleted inserted replaced
1599:f2a663a4ba9e 1600:8a717f0b7f45
1 package goodjava.logger; 1 package goodjava.logger;
2 2
3 import java.io.FileWriter; 3 import java.io.FileWriter;
4 import java.io.File;
4 import java.io.IOException; 5 import java.io.IOException;
5 import java.text.DateFormat; 6 import java.text.DateFormat;
6 import java.util.Date; 7 import java.util.Date;
7 8
8 9
9 public final class DailyRollingFileAppender extends WriterAppender { 10 public final class DailyRollingFileAppender extends WriterAppender {
10 private final DateFormat format; 11 private final DateFormat format;
11 private String fileName; 12 private String fileName;
13 public long deleteAfter = 0;
12 14
13 public DailyRollingFileAppender(Layout layout,DateFormat format) { 15 public DailyRollingFileAppender(Layout layout,DateFormat format) {
14 super(layout,null); 16 super(layout,null);
15 this.format = format; 17 this.format = format;
16 } 18 }
19 String newFileName = format.format(new Date()); 21 String newFileName = format.format(new Date());
20 if( !newFileName.equals(fileName) ) { 22 if( !newFileName.equals(fileName) ) {
21 fileName = newFileName; 23 fileName = newFileName;
22 if( writer != null ) 24 if( writer != null )
23 close(); 25 close();
26 sweep();
24 try { 27 try {
25 writer = new FileWriter(fileName,true); 28 writer = new FileWriter(fileName,true);
26 } catch(IOException e) { 29 } catch(IOException e) {
27 throw new RuntimeException(e); 30 throw new RuntimeException(e);
28 } 31 }
29 } 32 }
30 super.append(event); 33 super.append(event);
31 } 34 }
35
36 private void sweep() {
37 if( deleteAfter <= 0 )
38 return;
39 long expired = System.currentTimeMillis() - deleteAfter;
40 File dir = new File(fileName).getParentFile();
41 for( File file : dir.listFiles() ) {
42 if( file.lastModified() < expired )
43 file.delete();
44 }
45 }
32 } 46 }