-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog.cpp
More file actions
114 lines (92 loc) · 2.33 KB
/
log.cpp
File metadata and controls
114 lines (92 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/log/support/date_time.hpp>
#include "log.hpp"
#include "throw-with-trace.hpp"
namespace logging = boost::log;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;
namespace expr = boost::log::expressions;
BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", general_log::SeverityLevel);
namespace general_log
{
const std::vector<std::string> strings =
{
"dbg",
"inf",
"war",
"err",
"fat",
};
SeverityLevel severity_level(size_t level)
{
if (level >= strings.size())
{
std::string allowed;
for (auto const &s : strings)
allowed += s + " ";
throw_with_trace(std::runtime_error("The allowed log levels are: " + allowed));
}
return static_cast<SeverityLevel>(level);
}
SeverityLevel severity_level(const std::string &level)
{
size_t i;
for(i = 0; i < strings.size(); i++)
{
if (level == strings[i])
break;
}
return severity_level(i);
}
void init(const std::string &logfile, SeverityLevel clog_min, SeverityLevel flog_min)
{
auto format = expr::stream
<< "[" << expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%Y-%m-%d %H:%M:%S.%f")
<< " " << severity << "] "
<< expr::smessage;
auto fsink = logging::add_file_log
(
keywords::file_name = logfile,
keywords::format = format
);
auto csink = logging::add_console_log
(
std::clog,
keywords::format = format
);
fsink->locked_backend()->auto_flush(true);
fsink->set_filter
(
severity >= flog_min
);
csink->locked_backend()->auto_flush(true);
csink->set_filter
(
severity >= clog_min
);
logging::add_common_attributes();
}
std::ostream& operator<< (std::ostream& strm, SeverityLevel level)
{
auto l = static_cast< std::size_t >(level);
if (l < strings.size())
strm << strings[l];
else
strm << l;
return strm;
}
std::istream& operator>> (std::istream& in, SeverityLevel& unit)
{
std::string token;
in >> token;
unit = severity_level(token);
return in;
}
}