view src/goodjava/logger/RollingFileAppender.java @ 1804:b4328322d2be

minor
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 07 May 2024 22:08:37 -0600
parents 97cc73664ca8
children
line wrap: on
line source

package goodjava.logger;

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


public class RollingFileAppender extends WriterAppender {
	protected final String[] fileNames;
	protected final File file;
	public long maxFileSize = 10*1024*1024;

	public RollingFileAppender(Layout layout,String[] fileNames) throws IOException {
		super(layout,null);
		this.fileNames = fileNames;
		this.file = new File(fileNames[0]);
		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(fileNames[fileNames.length-1]);
		try {
			IoUtils.delete(backup);
			for( int i=fileNames.length-2; i>=1; i-- ) {
				File f = backup;
				backup = new File(fileNames[i]);
				IoUtils.move(backup,f);
			}
			IoUtils.move(file,backup);
			open();
		} catch(IOException e) {
			throw new RuntimeException(e);
		}
	}
}