c++ - boost 记录器刷新到文件

标签 c++ logging boost

在执行每个日志记录代码行后,我需要 boost 日志记录。是否有可能以某种方式配置接收器以这种方式运行?目前日志是在程序结束后立即填充的。

#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <conio.h>;

namespace logging = boost::log;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;

void init()
{
    logging::add_file_log
    (
        keywords::file_name = "sample_%N.log",                                        /*< file name pattern >*/
        keywords::rotation_size = 10 * 1024 * 1024,                                   /*< rotate files every 10 MiB... >*/
        keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0), /*< ...or at midnight >*/
        keywords::format = "[%TimeStamp%]: %Message%"                                 /*< log record format >*/
    );

    logging::core::get()->set_filter
    (
        logging::trivial::severity >= logging::trivial::info
    );
    logging::core::get();
}
//]

#endif

int main(int, char*[])
{
    init();
    logging::add_common_attributes();

    using namespace logging::trivial;
    src::severity_logger< severity_level > lg;

    BOOST_LOG_SEV(lg, trace) << "A trace severity message";
    BOOST_LOG_SEV(lg, debug) << "A debug severity message";
    BOOST_LOG_SEV(lg, info) << "An informational severity message";
    BOOST_LOG_SEV(lg, warning) << "A warning severity message";
    BOOST_LOG_SEV(lg, error) << "An error severity message";
    BOOST_LOG_SEV(lg, fatal) << "A fatal severity message";
    std::cin.get();
    return 0;
}

最佳答案

正如评论者所说,只需添加 auto_flush 关键字:

logging::add_file_log
(
    keywords::file_name = "sample_%N.log",                                        /* file name pattern            */ 
    keywords::rotation_size = 10 * 1024 * 1024,                                   /* rotate files every 10 MiB... */ 
    keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0), /* ...or at midnight            */ 
    keywords::auto_flush = true,
    keywords::format = "[%TimeStamp%]: %Message%"                                 /* log record format            */ 
);

Live On Coliru

关于c++ - boost 记录器刷新到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27022719/

相关文章:

c++ - Thread 对象在创建后立即销毁自身?

c++ - 何时使用静态变量 C++

c++ - OpenGL 延迟渲染不工作

linux - Shell 脚本在可配置的小时或天数后压缩 "my_dir"目录中的所有日志文件

C++从图中删除顶点

c++ - 错误 : Assertation failed allegro5\addons\font\text. c line 77 expression font

testing - 如何在测试脚本中检查 Hubot 日志输出

C++/MySQL,在 1 次执行中插入 200 个数据点数组

c++ - 获取标签的子标签详细信息 [Boost Porperty_tree XML]

c++ - 解析 JSON 文件 (C++ Boost)