Reputation: 1720
I'm writing a singleton logger for my program right now, and I was wondering whether it would be better to open and close it everytime I log something, or to open the stream at creation of the singleton and close it at the termination of the program? And if I were to do that, how would I close it at termination?
Upvotes: 2
Views: 292
Reputation: 75896
The main advantage of opening the file once is performance. You save yourself the penalty of calling an open
each time, and seek to the end of the file for appending; this get worse if the file is big (and some logs tend to be).
The cons are:
You might not be able to read the last log line inmmediately, if there is some buffering in the writer (delayed writes). Howeever, this can be fixed by flushing after each write (you might lose some performance, but this is not usually relevant).
You cannot simultaneously write to the same log from different processes. But you probably don't need this - and if you need it, the open-and-close solution still needs to deal with concurrency.
Some external log processing (typically, log rotation with renaming) becomes problematic. To allow for this, you might need to implement some signalling that closes and reopens the file.
Typically, the advantage outweights the cons, so the general rule is to keep the log file open. But that depends on the scenario.
(As other answers point out, normally you'd prefer to use some standard logging library instead of implementing this on your own. But it's instructive to give it a try, or at least to think of all the issues involved).
Upvotes: 1
Reputation: 135992
Do not close it, just flush, this is what Log4j FileAppender does by default.
Upvotes: 1
Reputation: 201429
You should open once (and close once). If you do nothing, Java will close it for you. You may prefer to explicitly override Object.finalize().
Upvotes: 0