如何保护日志从应用程序崩溃? [英] How to protect log from application crash?

查看:471
本文介绍了如何保护日志从应用程序崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的记录器,将所有重要的日志记录到文本文件中。我使用 std :: ofstream 但有一个问题 - 当程序不关闭文件(调用 std :: ofstream :: close ())无论什么原因(如崩溃),创建的日志实际上是空的(0大小)。由于日志在异常情况下最为有用(当出现错误时) - 您会看到问题。



有什么办法保护我的日志?我可以尝试关闭文件后写几行和使用append - 但是仍然不能保护我的情况,当程序崩溃在日志/中间关闭文件之前。

解决方案

您应该使用 flush 方法,它是为了精确地解决像你面对的问题。 p>

有另一种方法可以被认为更安全,但需要更多的努力来实现和测试。该方法归结为所谓的 进程间通信(IPC) 。简而言之,您可以将记录器作为单独的记录器应用程序实现,该应用程序将通过特定的协议(接口)与目标应用程序进行通信。你可以自己开发这样的协议或使用现有的协议(通常非常通用,即通用)。因此,如果您的目标应用程序崩溃,它不会拖动记录器应用程序与它,因此记录器可以安全地完成其工作。



这种方法通常使用一些庞大,复杂和安全关键的系统。但是,我想在你的情况下,这绝对是一个overkill和裸露 flush()在每个append是足够的。


I've created a simple logger which, well, logs everything of importance into a text file. I'm using std::ofstream but there's a problem - when the program doesn't close the file (call std::ofstream::close()) for whatever reason (like crash), the created log is actually empty (0 size). And since the log is most useful in exceptional situations (when something goes wrong) - you see the problem.

Is there any way to protect my log from that? I could try closing the file after writing every couple of lines and using append - but that still doesn't protect me from the situation when the program crashes in the middle of logging/before closing the file. Is there any solution or am I just doomed?

解决方案

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.

这篇关于如何保护日志从应用程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆