Aktualizr
C++ SOTA Client
All Classes Namespaces Files Functions Variables Enumerations Enumerator Pages
default_log_sink.cc
1 #include <iomanip>
2 #include <iostream>
3 
4 #include <boost/log/trivial.hpp>
5 #include <boost/log/utility/setup/console.hpp>
6 
7 static void color_fmt(boost::log::record_view const& rec, boost::log::formatting_ostream& strm) {
8  auto severity = rec[boost::log::trivial::severity];
9  bool color = false;
10  if (severity) {
11  switch (severity.get()) {
12  case boost::log::trivial::warning:
13  strm << "\033[33m";
14  color = true;
15  break;
16  case boost::log::trivial::error:
17  case boost::log::trivial::fatal:
18  strm << "\033[31m";
19  color = true;
20  break;
21  default:
22  break;
23  }
24  }
25  // setw(7) = the longest log level. eg "warning"
26  strm << std::setw(7) << std::setfill(' ') << severity << ": " << rec[boost::log::expressions::smessage];
27  if (color) {
28  strm << "\033[0m";
29  }
30 }
31 
32 void logger_init_sink(bool use_colors = false) {
33  auto* stream = &std::cerr;
34  if (getenv("LOG_STDERR") == nullptr) {
35  stream = &std::cout;
36  }
37  auto sink = boost::log::add_console_log(*stream, boost::log::keywords::format = "%Message%",
38  boost::log::keywords::auto_flush = true);
39  if (use_colors) {
40  sink->set_formatter(&color_fmt);
41  }
42 }