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

前端 未结 13 1177
小蘑菇
小蘑菇 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 20:07

    It's a tradeoff. Opening and closing the file each time makes it more likely that the file will be updated on disk in the program crashes. On the other hand, there's some overhead involved in opening the file, seeking to the end, and appending data to it.

    On Windows, you won't be able to move/rename/delete the file while it's open, so open/write/close might be helpful for a long-running process where you might occasionally want to archive the old log contents without interrupting the writer.

    In most of the cases where I've done this sort of logging, I've kept the file open, and used fflush() to make it more likely the file was up-to-date if the program crashed.

提交回复
热议问题