Created
August 11, 2019 20:58
-
-
Save p13i/6d4f7ef3fef777cdc8148df3309feb6c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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