Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

logging

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 logging is complete?

I'm asking in context of a desktop application. I have seen people do it both ways and was wondering which approach yields the best all-around results for a logger.

like image 961
Jordan Parmer Avatar asked Oct 02 '08 19:10

Jordan Parmer


People also ask

Where should log files be stored?

The "standard" place for the log would be the AppData directory. However, really its up to you where you want to store them. As they are administrator (power users) then there should be no problems storing the logs in the same directory as the application being run.

What opens log files?

You can read a LOG file with any text editor, like Windows Notepad. You might be able to open one in your web browser, too. Just drag it directly into the browser window, or use the Ctrl+O keyboard shortcut to open a dialog box to browse for the file.


1 Answers

If you have frequent read/writes it is more efficient to keep the file open for the lifetime with a single open/close.

You might want to flush periodically or after each write though in case your application crashes you might not have all the data written to your file. Use fflush on Unix based systems and FlushFileBuffers on Windows.

If you are running on Windows as well you can use the CreateFile API with FILE_FLAG_NO_BUFFERING to go direct to file on each write.

It is also better to keep the file open for the lifetime, because each time you open/close you might have a failure if the file is in use. For example you might have a backup application that runs and open/closes your file as it's backing it up. And this might cause your program to not be able to access your own file. Ideally you would want to keep your file open always and specify sharing flags on Windows (FILE_SHARE_READ). On Unix based systems, sharing will be default.

like image 73
Brian R. Bondy Avatar answered Sep 19 '22 14:09

Brian R. Bondy