view src/goodjava/logger/RollingFileAppender.java @ 1455:1437fb1f0956

add slf4j-goodjava
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 08 Mar 2020 16:50:14 -0600
parents dd14d2dce7ee
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);
	}
}