boost log的前端和后端

本文介绍了Boost Log模块的工作原理,详细解释了sink组件的结构,包括前端与后端的作用。并通过实例展示了如何配置同步sink,并说明了如何将日志记录输出到文件和控制台。此外还介绍了如何通过增加多个流来复制输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sink由两部分组成:前端(frontend)和后端(backend)。以boost::log的教程为例:


typedef boost::log::sinks::synchronous_sink<boost::log::sinks::text_ostream_backend> text_sink;

boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >();


前端(例如上例的boost::log::sinks::synchronous_sink模板类)负责sink的各种公共任务,例如线程同步模型,过滤及格式(对于文本格式的sink)。后端(例如上例的text_ostream_backend)实现特定sink的一切事情,例如在上例中就是写入文件。Log库提供许多可以彼此协作的前端和后端。


在上例中的展示的sychronous_sink模板类是同步的,这就意味着,它允许许多线程同时以阻塞方式进行日志工作。这也意味着后端(text_ostream_backend)完全不用担心多线程问题。


text_ostream_backend类向STL兼容的流写入格式化的日志记录(log record)。上例中我们使用了文件流,实际上我们可以写入任意类型的流。例如,添加输出日志到控制台如下所示:


#include <boost/log/utility/empty_deleter.hpp>

// We have to provide an empty deleter to avoid destroying the global stream object

boost::shared_ptr< std::ostream > stream(&std::clog, logging::empty_deleter());

sink->locked_backend()->add_stream(stream);


text_ostream_backend支持添加多个流,后端的输出将复制后发送至每一个添加的流中。这种复制输出结果到控制和文件中能非常有用,因为所有的过滤器、格式化及其它的库的开销只针对sink中的记录只处理一次。


请特别注意注册多个不同的sink和注册一个sink,该sink具有多个不同目的的stream之间的区别。虽然前者允许独立定制每个sink的输出,但是如果这样不需要定制,后者将工作的更快。


Log库提供了许多backend,这些backend提供不同的处理逻辑。例如通过指定syslog后端,可以将日志信息通过网络传输到syslog服务器,或者通过设置Windows NT event log后端,我们可以使用标准的windows工具来监视应用程序的运行时间。


The last thing worth notinghere is thelocked_backendmember function call to access the sink backend. It is used to get thread-safeaccess to the backend and is provided by all sink frontends. This functionreturns a smart-pointer to the backend and as long as it exists the backend islocked (which means even if another thread tries to log and the log record ispassed to the sink, it will not be logged until you release the backend). Theonly exception is theunlocked_sink frontend whichdoes not synchronize at all and simply returns an unlocked pointer to thebackend.


最后这里需要注意的是调用lockend()成员函数来访问sink的后端。这个函数可以线程安全的访问backend,所有的sink前端都提供了该函数。该函数返回一个后端的智能指针并且只要这个智能指针存在,后端就处于加锁状态(这就是说,甚至别的线程试图进行log并且logrecord已经传入sink,它也不会被记录,直到释放这个后端才可以进行这项工作)。唯一的例外是前端调用unlocked_sink操作,该操作不是同步操作,只是简单的返回一个未加锁的后端指针。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值