Should log classes open/close a log file stream on each write to the log file or should it keep the log file stream open throughout the application\'s lifetime until all log
The advantage to closing the file every time is that the OS will guarantee that the new message is written to disk. If your leave the file open and your program crashes, it is possible the entire thing wouldn't be written. You could also accomplish the same thing by doing an fflush() or whatever is the equivalent in the language you are using.
It's generally better to keep them open.
If you're concerned about being able to read them from another process, you need make sure that the share mode you use to open/create them allows others to read them (but not write to them, obviously).
If you're worried about losing data in the event of a crash, you should periodically flush/commit their buffers.
I would open and close on each write (or batch of writes). If doing this causes a performance problem in a desktop application, it's possible you're writing to the log file too often (although I'm sure there can be legitimate reasons for lots of writes).
For performance, keep open. For safety, flush often.
This will mean that the run-time library will not try to buffer writes until it has lots of data -- you may crash before that's written!
I can think of a couple reasons you don't want to hold the file open:
On the other hand, opening files can be slow, even in append mode. In the end, it comes to down to what your app is doing.
I would tend to leave them open -- but open them with the file share permissions set to allow other readers and make sure you flush log output with every message.
I hate programs which don't even let you look at the logfile while they are running, or where the log file isn't flushed and lags behind what is happening.