How to protect log from application crash?

末鹿安然 提交于 2019-12-04 14:19:42

You should employ flush method, it is there to precisely solve problems like the one you're facing.

There is another approach which can be considered more safe, but requires substantially more effort to implement and test. The approach boils down to what is known as inter-process communication (IPC). In brief, you could implement your logger as a separate logger application which would communicate with your target application by means of specific protocol (interface). You can develop such protocol by yourself or employ one of the existing ones (which are usually very generic, i.e. general purpose). As a result, if your target application crashes, it doesn't drag logger application with it, and therefore logger can safely finish its job.

That approach is usually used by some huge, complex, and safety-critical systems. However, I guess that in your case this is definitely an overkill and bare flush() after each append is more than enough.

In our commercial application, we had a very robust solution for that. The price was non-portability.

We installed a Vectored Exception Handler. This handler is called in case of an unhandled OS exception, before the program exits (which is by far the most common crash). When it's called, you can not call C++ Standard Library function anymore (or even C functions). Even fflush is unreliable.

Yet it is OK to call basic OS functions. Be careful, though. Setting up the arguments for the OS call shouldn't use malloc either. Have the name of the crashfile already set up before the crash actually happens, etc. Do close the file immediately, again using OS functions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!