【发布时间】:2020-03-31 18:34:15
【问题描述】:
我正在 Boost.Log 之上实现一个包装器。在异步日志中,记录器不会立即写入日志消息,而是创建一个消息队列。当调用core.get()->flush() 方法时,消息将被写入文件。
但显然在每条消息之后调用 flush() 效率不高。这样异步日志记录没有任何好处。而且在程序结束时调用它一次也不是一个好主意。 (可能程序在服务器上运行了很长时间)
我想编写一个代码来定期调用 flush()(例如每 10 毫秒)。
有了这个example 和this 的问题,我使用Boost.asio 编写了一个异步计时器,但它没有将消息写入文件。实际上 logger 不会创建任何 .log 文件。可能是因为在没有发生日志记录时必须调用 flush() 方法。
typedef sinks::asynchronous_sink<
sinks::text_file_backend,
sinks::unbounded_ordering_queue<
logging::attribute_value_ordering< unsigned int, std::less< unsigned int > >
>
> Async_file_sink;
void do_flush(const boost::system::error_code& /*e*/,
boost::asio::deadline_timer* t)
{
logging::core::get()->flush();
t->expires_at(t->expires_at() + boost::posix_time::milliseconds(10));
t->async_wait(boost::bind(do_flush,
boost::asio::placeholders::error, t));
}
struct PerodicTimer{
PerodicTimer(boost::asio::deadline_timer &timer) : t(timer) {
t.async_wait(boost::bind(do_flush,
boost::asio::placeholders::error, &t));
}
boost::asio::deadline_timer& t;
};
void init_flushing()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::milliseconds(10));
PerodicTimer m(t);
std::thread th([&]{
// std::cout << "inside thread" << std::endl;
io.run();
});
th.detach();
}
static void init_logging()
{
logging::add_common_attributes();
boost::shared_ptr< Async_file_sink > sink(new Async_file_sink(
boost::make_shared< sinks::text_file_backend >(),
keywords::file_name = "sample_%N.log",
keywords::rotation_size = 1024 * 1024,
// We'll apply record ordering to ensure that records from different threads go sequentially in the file
keywords::order = logging::make_attr_ordering("LineID", std::less< unsigned int >())
));
// Set up where the rotated files will be stored
init_file_collecting(sink);
sink->set_formatter(&my_formatter);
sink->locked_backend()->scan_for_files();
logging::core::get()->add_sink(sink);
init_flushing(); // Starting Timer
}
int main()
{
init_logging();
ADD_LOG("SOME MESSAGE");
}
我认为问题出在调用()flush()时,同时异步记录器正在记录消息。我无法在同一个线程中运行异步计时器,因为 io.run() 正在阻塞。
什么是最小解决方案?
【问题讨论】:
标签: c++ asynchronous logging boost boost-asio