Boost.Log - how to configure a text sink backend to append to rotated files

半世苍凉 提交于 2019-11-28 09:41:36

That functionality is built in to the text sink, and the documentation includes an example to set the file-name pattern and rules for rotating at certain sizes and times:

// The function registers file sink in the logging library
void init_logging()
{
    boost::shared_ptr< logging::core > core = logging::core::get();

    boost::shared_ptr< sinks::text_file_backend > backend =
        boost::make_shared< sinks::text_file_backend >(
            // file name pattern
            keywords::file_name = "file_%5N.log",
            // rotate the file upon reaching 5 MiB size...
            keywords::rotation_size = 5 * 1024 * 1024,
            // ...or at noon, whichever comes first
            keywords::time_based_rotation = sinks::file::rotation_at_time_point(12, 0, 0)
        );

    // Wrap it into the frontend and register in the core.
    // The backend requires synchronization in the frontend.
    typedef sinks::synchronous_sink< sinks::text_file_backend > sink_t;
    boost::shared_ptr< sink_t > sink(new sink_t(backend));

    core->add_sink(sink);
}

There is apparently no way to make the library append to existing files with this setup. You should call backend->scan_for_files(); prior to constructing sink, as shown under the "Managing rotated files" heading in the documentation, but that only prevents the library from overwriting previous logs before they're due for cleanup.

When this topic arose on a development mailing list in February 2013, the library's author explained that adding support for appending would be a nontrivial change that couldn't be made under the current design.

You have to specify the open_mode before use the text file. By default Boost.Log will use std::ios_base::trunc|std::ios_base::out as the open mode which obviously will truncate the old log file.

You can create text_file_backend instance with the following parameters:

    {
        boost::shared_ptr<sinks::text_file_backend> backend =
            boost::make_shared<sinks::text_file_backend>(
                keywords::file_name = logger_file_path,
                keywords::open_mode = std::ios_base::app|std::ios_base::out,
                keywords::rotation_size = 5 * 1024 * 1024,
                keywords::time_based_rotation = sinks::file::rotation_at_time_point(12, 0, 0));
        // Wrap it into the frontend and register in the core.
        // The backend requires synchronization in the frontend.
        typedef sinks::synchronous_sink<sinks::text_file_backend> sink_t;
        boost::shared_ptr<sink_t> sink(new sink_t(backend));
        sink->set_formatter(logFmt);
        core->add_sink(sink);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!