Should log file streams be opened/closed on each write or kept open during a desktop application's lifetime?

前端 未结 13 1178
小蘑菇
小蘑菇 2020-12-04 19:52

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

相关标签:
13条回答
  • 2020-12-04 19:54

    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.

    0 讨论(0)
  • 2020-12-04 19:55

    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.

    0 讨论(0)
  • 2020-12-04 19:55

    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).

    0 讨论(0)
  • 2020-12-04 19:57

    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!

    0 讨论(0)
  • 2020-12-04 20:02

    I can think of a couple reasons you don't want to hold the file open:

    • If a log file is shared between several different apps, users, or app instances you could have locking issues.
    • If you're not clearing the stream buffer correctly you could lose the last few entries when that app crashes and you need them most.

    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.

    0 讨论(0)
  • 2020-12-04 20:03

    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.

    0 讨论(0)
提交回复
热议问题