【问题标题】:How to use Boost::log not to rewrite the log file?如何使用 Boost::log 不重写日志文件?
【发布时间】:2022-01-03 18:39:29
【问题描述】:

下面是使用boost::log写日志的简单例子,

#include <boost/log/trivial.hpp>

namespace logging = boost::log;

logging::add_file_log("sample.log")->set_filter(
    logging::trivial::severity >= logging::trivial::info
);

BOOST_LOG_TRIVIAL(info) << "log content";

每次运行logging::add_file_log("sample.log") 都会重写日志文件——擦除原始内容并写入新日志。所以它不能用于多进程一个日志文件系统。 如何设置不重写文件?

编辑:

我将此 boost::log 包装在一个 dll 中并尝试让其他 exe 文件调用它。

【问题讨论】:

    标签: c++ logging boost c++17


    【解决方案1】:

    您可以将 openmode 传递给 setup 函数:

    Live On Coliru

    #include <boost/log/trivial.hpp>
    #include <boost/log/utility/setup.hpp>
    #include <random>
    
    namespace logging = boost::log;
    namespace logkw = logging::keywords;
    
    int main()
    {
        logging::add_file_log("sample.log", logkw::open_mode = std::ios::app)
            ->set_filter(                                            //
                logging::trivial::severity >= logging::trivial::info //
            );
    
        std::mt19937 mt(std::random_device{}());
    
        BOOST_LOG_TRIVIAL(info) << "log content " << std::uniform_int_distribution(5,50)(mt);
    }
    

    打印例如

    log content 33
    log content 14
    log content 39
    log content 39
    log content 46
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多