Skip to content

Instantly share code, notes, and snippets.

@p13i
Created August 11, 2019 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save p13i/6d4f7ef3fef777cdc8148df3309feb6c to your computer and use it in GitHub Desktop.
Save p13i/6d4f7ef3fef777cdc8148df3309feb6c to your computer and use it in GitHub Desktop.
import java.io.Closeable;
import java.io.Flushable;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Logger;
/**
* Writes log files to a after a specified number of items are writen to the buffer
*/
public class BufferingLogFileWriter implements Flushable, Closeable {
private static final Logger LOGGER = LoggerUtils.getLogger(BufferingLogFileWriter.class);
public static final int MAX_QUEUE_SIZE = 50;
public final Queue<String> mQueue = new LinkedList<>();
private String logFilePath;
private PrintWriter printWriter;
public BufferingLogFileWriter(String logFilePath) {
this.logFilePath = logFilePath;
}
public synchronized void open() {
this.printWriter = FileIO.openPrintWriter(this.logFilePath);
}
public synchronized void queue(String line) {
if (mQueue.size() > MAX_QUEUE_SIZE) {
this.flush();
}
mQueue.add(line);
}
public synchronized void flush() {
LOGGER.info("Flushing queue...");
while (!mQueue.isEmpty()) {
String line = mQueue.poll();
this.printWriter.print(line);
if (!line.endsWith("\n")) {
this.printWriter.println();
}
}
LOGGER.info("Flushed.");
}
public synchronized void close() {
this.printWriter.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment