Tuesday, 3 December 2013

use boost log step 3

Now, I need to write log to local file. My example code is simpler than official doc.

#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";
}
Do not forget to include <boost/log/utility/setup/file.hpp>, otherwise you will get compilation error like so:
no member named 'add_file_log' in namespace 'boost::log'

 Now, run the app, you will see sample file is created in current folder.
$ 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 message
Here we encounter a concept "sink", sink decides where the log info will be written. In the previous two articles, I didn't add sink. The boost log uses console as default sink. Now, because I call add_file_log function, so the default sink is replaced by the file sink now. To setup sink, you need to add it into core. Just one statement in above example:
logging::add_file_log("sample.log");
boost log has another concept-- source. This doc describes the architecture of boost log design.


The left side is log source, it collects the log info in our app. just like this statement
  BOOST_LOG_TRIVIAL(trace) << "A trace severity message";
The right side is sink, it processes log info, decides where the log should be put, how to use it.
And the logging core interconnects them. 

No comments:

Followers

Contributors