boost log库使用三

现在,我要将日志写到本地文件中。我的例子代码比官方文档简单点。

#include <iostream>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/file.hpp>
namespace logging = boost::log;
using namespace std;
void SetFilter1() {
  logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info);
}
void SetFilter2() {
  logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::debug);
}
int main () {
  cout << "hello, world" << endl;
  logging::add_file_log("sample.log");
  SetFilter1();
  BOOST_LOG_TRIVIAL(trace) << "A trace severity message";
  BOOST_LOG_TRIVIAL(debug) << "A debug severity message";
  BOOST_LOG_TRIVIAL(info) << "An informational severity message";
  BOOST_LOG_TRIVIAL(warning) << "A warning severity message";
  BOOST_LOG_TRIVIAL(error) << "An error severity message";
  BOOST_LOG_TRIVIAL(fatal) << "A fatal severity message";
 
  BOOST_LOG_TRIVIAL(info) << "--------------------" << endl;
  SetFilter2();
  BOOST_LOG_TRIVIAL(trace) << "A trace severity message";
  BOOST_LOG_TRIVIAL(debug) << "A debug severity message";
  BOOST_LOG_TRIVIAL(info) << "An informational severity message";
  BOOST_LOG_TRIVIAL(warning) << "A warning severity message";
  BOOST_LOG_TRIVIAL(error) << "An error severity message";
  BOOST_LOG_TRIVIAL(fatal) << "A fatal severity message";
}

不要忘记包含头文件

<boost/log/utility/setup/file.hpp>

,否则你会遇到编译错误:

no member named 'add_file_log' in namespace 'boost::log'

现在运行程序,可以看到当前目录下有了sample.log文件。内容如下:

$ cat sample.log
An informational severity message
A warning severity message
An error severity message
A fatal severity message
--------------------
A debug severity message
An informational severity message
A warning severity message
An error severity message
A fatal severity messag

现在我们遇到了sink的概念。sink决定日志信息输出到什么地方。在前面两篇文章中,我没有添加sink。boost log使用console作为默认的sink. 现在,因为我调用了add_file_log函数,因此默认的sink被file sink取代。要设置sink, 需要将其添加到core中,上面的例子只用了一行代码:

logging::add_file_log("sample.log");

boost log还有一个概念叫做source。这个文档描述了boost log设计的架构。

boost log库使用三_第1张图片



左边是 log source, 负责从程序中收集日志信息,就像这样的语句:

BOOST_LOG_TRIVIAL(trace) << "A trace severity message";
右边是sink, 负责处理日志信息,决定日志输出到哪里,怎么使用。

中间的logging core将它们连接在一起。




你可能感兴趣的:(log,boost)