【问题标题】:easylogging++ : Clearing log file on application startupeasylogging++:在应用程序启动时清除日志文件
【发布时间】:2014-11-28 19:14:34
【问题描述】:

我最近在我的 C++ 应用程序中采用了Easylogging++,并且遇到了我希望他们文档中遗漏的内容。

我希望每次启动我的应用程序时都清除我的日志文件,而不是从以前的应用程序实例中附加日志事件。我意识到我可以在任何日志记录事件之前在启动时删除日志文件,但这似乎是一个 hack。

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: logging reset app-startup easylogging++


    【解决方案1】:

    从 v9.84 版开始,可以通过定义 configuration macro 来配置它。

    你需要在#include "easylogging++"之前添加#define ELPP_FRESH_LOG_FILE

    您很可能不想对每个包含都执行此操作。作者推荐使用编译器标志。或者,您可以创建一个包装头。

    【讨论】:

    • 刚刚下载了easylogging++_v9.84.zip。打开 easylogging++.h 并注意到文件顶部的这一行: // Easylogging++ v9.83
    • 我确认 easylogging++.h 中的代码实际上是在处理 ELPP_FRESH_LOG_FILE 编译器定义(并且可以正常工作)。好的!所以这似乎只是没有更新评论以反映正确的版本号的情况。
    【解决方案2】:

    如果不求助于编辑 easylogging++.h,我无法找到解决此问题的方法。显然,我希望这不是必需的,但我很确定从 v9.77 开始,不存在用于在应用程序启动时重置日志文件的内置工具。如有错误请大家指正。

    检查代码,我发现日志文件总是以附加模式创建的。似乎没有任何进一步的逻辑明确删除日志文件。

    对于任何对我的 hack 工作感兴趣的人,我将传递给 utils::File::newFileStream() 中 fstream 构造函数的打开模式参数更改为包含 fstream::trunc 而不是 fstream::app。更改发生在 easylogging++.h, v9.77 的第 1084 行附近。

    这是我所指的代码部分:

    namespace utils {
    class File : base::StaticClass {
    public:
    /// @brief Creates new out file stream for specified filename.
    /// @return Pointer to newly created fstream or nullptr
    static base::type::fstream_t* newFileStream(const std::string& filename) {
        // CLW: Dec 29, 2014:
        // I don't want a log file containing log events from past application instances,
        // but there seems to be no built-in way to reset the log file when the app is started
        // So, I'm changing the open mode in the following fstream constructor call to include 
        // fstream::trunc instead of fstream::app.
        base::type::fstream_t *fs = new base::type::fstream_t(filename.c_str(),
            base::type::fstream_t::out | base::type::fstream_t::trunc);
    //  base::type::fstream_t *fs = new base::type::fstream_t(filename.c_str(), 
    //      base::type::fstream_t::out | base::type::fstream_t::app);
    

    对不起,讨厌的代码格式。我只是按照easylogging++.h中当前格式的方式复制了代码,以便可以轻松识别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-21
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多