view src/goodjava/logger/DailyRollingFileAppender.java @ 1640:570f3d483a31

host - move https.luan into src
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 21 Dec 2021 16:54:26 -0700
parents 8a717f0b7f45
children
line wrap: on
line source

package goodjava.logger;

import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;


public final class DailyRollingFileAppender extends WriterAppender {
	private final DateFormat format;
	private String fileName;
	public long deleteAfter = 0;

	public DailyRollingFileAppender(Layout layout,DateFormat format) {
		super(layout,null);
		this.format = format;
	}

	public synchronized void append(LoggingEvent event) {
		String newFileName = format.format(new Date());
		if( !newFileName.equals(fileName) ) {
			fileName = newFileName;
			if( writer != null )
				close();
			sweep();
			try {
				writer = new FileWriter(fileName,true);
			} catch(IOException e) {
				throw new RuntimeException(e);
			}
		}
		super.append(event);
	}

	private void sweep() {
		if( deleteAfter <= 0 )
			return;
		long expired = System.currentTimeMillis() - deleteAfter;
		File dir = new File(fileName).getParentFile();
		for( File file : dir.listFiles() ) {
			if( file.lastModified() < expired )
				file.delete();
		}
	}
}