I've written a custom logging Class that behaves very similarly to a PrintWriter like System.out or System.err. The main difference is that when myLogger.printf("Hello World!\n");
is called, the data isn't written directly to the log file, but instead to an internal queue, and this queue only gets flushed to the output file via the flush();
method. So use of the code looks like this:
myLogger.println("Line 1.");
myLogger.println("Line 3.");
myLogger.println("Actually that was Line 2. THIS is Line 3!");
myLogger.flush();
Which should give an output that (sort of) looks like this:
2016-03-30 15:44:45::389> Line 1.
2016-03-30 15:44:45::390> Line 3.
2016-03-30 15:44:45::395> Actually that was Line 2. THIS is Line 3!
However, the problem I have is when users make mistakes. Namely, they forget to call flush()
, and the data they've written to the logger never gets dumped to the file, and the program closes without ever flushing the data.
I can't flush after every single call, because it would defeat the purpose of writing this class in the first place. And having the system manage automatic flushing would be similarly self-defeating.
My idea was to put a call to flush()
inside the finalize()
method of the object, but as I've read from several other articles on this site, there's no guarantee that finalize()
will ever be called.
Just for clarity's sake, this is what the flush()
method looks like:
public void flush() {
open();
while(!unwrittenLogs.isEmpty()) {
String line = unwrittenLogs.poll();
log.print(line);
}
close();
}
private void open() {
if(log == null) {
try {
log = new PrintWriter(new FileOutputStream(logFile, true));
} catch (FileNotFoundException e) {
System.err.printf("Unable to open Log File.\n%s\n",e.getMessage());
e.printStackTrace(System.err);
}
}
}
private void close() {
if(log != null) {
log.close();
log = null;
}
}
So what is my best option to ensure that the logger is flushed before the program quits?