前一篇文章boost log – 使用心得和碰到的那些坑(一) 写了如何使用boost;;log, 这篇文章主要写写怎样用boost;;log构建一个工程,目的就是让用户使用时忘掉log细节。
项目依赖
boost c++11 cmake
设计
为了以后扩展方便,将log设计成接口。 接口提供基本的log功能:
class logger_iface
{
public:
public:
logger_iface(void)= default;
virtual ~logger_iface(void) = default;
logger_iface(const logger_iface &) = default;
logger_iface &operator=(const logger_iface &) = default;
public:
virtual void init() = 0;
virtual void set_log_level(log_level level) = 0;
virtual void debug_log(const std::string &msg, const std::string &file, std::size_t line) = 0;
virtual void info_log(const std::string &msg, const std::string &file, std::size_t line) = 0;
virtual void warn_log(const std::string &msg, const std::string &file, std::size_t line) = 0;
virtual void error_log(const std::string &msg, const std::string &file, std::size_t line) = 0;
virtual void critical_log(const std::string &msg, const std::string &file, std::size_t line) = 0;
};
boost logger 继承这个类。
前文已经提到了,boost logger 需要一个log core 一个sink,同时使用async backend。所以boost logger实现接口的同时加入这两个成员变量。
boost::shared_ptr<sink_t> _sink;
boost::log::sources::severity_logger_mt<log_level> lg;
利用前文所写的实现这几个函数,需要注意的是 log level其实就是设置boost;;log的 filter
void boost_logger::set_log_level(log_level level)
{
m_level = level;
if (_sink)
{
_sink->set_filter(expr::attr<log_level>("Severity") >= m_level);
}
}
现在class功能都已经实现,如何使用呢?我们需要的就是__LOG(level, msg)
这样简单的API。这需要有个全局的实例。
还有一个要考虑的是, boost;;logger没有提供文件及文件行号信息。
解决这个问题, 我们有个宏定义:
#define __LOG(level, msg) \
\
{ \
tostringstream var; \
var << "[fuction:" << __func__ << "] " << msg; \
level(var.str(), __FILE__, __LINE__); \
}
#else
#define __LOG(level, msg)
#endif /* __LOGGING_ENABLED */
其实level是一个函数,msg提供了像std;;cout一样的用法。
下面我们看看level是怎么实现的:
void debug(const std::string &msg, const std::string &file, std::size_t line)
{
if (active_logger)
active_logger->debug_log(msg, file, line);
}
active_logger是一个全局的instance。
std::unique_ptr<logger_iface> active_logger(new boost_logger(log_level::error_level)); //nullptr;
至此,基本功能都已经实现了。
需要源代码,移步:https://github.com/maxcong001/boostlogger