view 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
line wrap: on
line source

package goodjava.logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


public class RollingFileAppender extends WriterAppender {
	protected final String fileName;
	protected final File file;
	public long maxFileSize = 10*1024*1024;
	public int backups = 1;

	public RollingFileAppender(Layout layout,String fileName) throws IOException {
		super(layout,null);
		this.fileName = fileName;
		this.file = new File(fileName);
		open();
	}

	protected void open() throws IOException {
		this.writer = new FileWriter(file,true);
	}

	public synchronized void append(LoggingEvent event) {
		super.append(event);
		if( file.length() > maxFileSize ) {
			rollOver();
		}
	}

	protected void rollOver() {
		close();
		File backup = new File(fileName+'.'+backups);
		if( backup.exists() ) {
			if( !backup.delete() )
				debug("couldn't delete "+backup);
		}
		for( int i=backups-1; i>=1; i-- ) {
			File f = backup;
			backup = new File(fileName+'.'+i);
			backup.renameTo(f);
		}
		if( !file.renameTo(backup) )
			debug("couldn't rename "+file+" to "+backup);
		try {
			open();
		} catch(IOException e) {
			throw new RuntimeException(e);
		}
	}

	protected void debug(String msg) {
		System.err.println("RollingFileAppender: "+msg);
	}
}