boost::log 关闭日志文件并打开一个新文件

boost::log close log file and open a new one

我正在使用 boost::log 同时登录到文件和控制台。它是这样初始化的:

void Init() {
logging::core::get()->set_filter
    (
        // set logging level to one of trace, debug, info, warning, error, fatal
        logging::trivial::severity >= logging::trivial::trace
    );
logging::add_common_attributes(); // enables timestamps and such
logging::add_file_log
    (
        keywords::file_name     = logfile + "_%N.log",
        keywords::rotation_size = 1024 * 1024 * 50, // 50MB log file max
        //       keywords::format = "[%TimeStamp%]: %Message%"
        keywords::format        = "%Message% #[%TimeStamp%]"
    );

logging::add_console_log(std::cout,
                         keywords::format = "%Message%"
);
}

在我的程序中的某些点,我想手动更改日志文件。我可以更改上面代码中的 "logfile" 字符串并再次调用 Init(),但随后它会继续写入旧日志文件并启动新日志文件,并开始将控制台日志上的输出加倍。

是否有某种对应的 "remove_file_log" 我丢失了,或者手动告诉它停止记录到原始日志并移动到下一个?

每次调用 add_file_log 都会在日志记录核心中注册一个新的文件接收器,这会导致同时写入多个文件。不会更换现有的水槽。根据您实际想做的事情,您可以做很多事情。

首先,如果您查看 add_file_log reference, you will notice that it returns the pointer to the created sink. You can pass that pointer to core::remove_sink 希望该水槽停止使用的时间。被销毁后,接收器将关闭它正在使用的日志文件。

typedef sinks::synchronous_sink< sinks::text_file_backend > sink_t;
boost::shared_ptr< sink_t > g_file_sink;

void Init() {
    // ...
    g_file_sink = logging::add_file_log
    (
        keywords::file_name     = logfile + "_%N.log",
        keywords::rotation_size = 1024 * 1024 * 50, // 50MB log file max
        keywords::format        = "%Message% #[%TimeStamp%]"
    );

    // ...
}

void StopFileLogging() {
    logging::core::get()->remove_sink(g_file_sink);
    g_file_sink.reset();
}

其次,接收器后端的text_file_backend which is created and returned by add_file_log has the ability to rotate log files. If you just want to switch the log file at certain points of the program, this is what you're probably looking for. You can add the named parameters such as keywords::rotation_size to the add_file_log call and they will be used to set up automatic file rotation in the backend. You can also rotate the file manually by calling text_file_backend::rotate_file

void RotateLogFile() {
    g_file_sink->locked_backend()->rotate_file();
}

请注意,在这种情况下,您不必从核心中移除水槽;它在文件旋转后保持活动状态。