26 #include "timezone/ztime.hpp"
32 using namespace std::string_literals;
47 inline const char* to_string(Severity sv) {
48 static const char* svstr[] = {
56 return static_cast<std::size_t
>(sv) <
sizeof(svstr)/
sizeof(svstr[0]) ?
57 svstr[
static_cast<int>(sv)] :
"unknown";
60 inline Severity from_string(
const std::string& s) {
61 if (s ==
"TRACE"s)
return SV_TRACE;
62 if (s ==
"DEBUG"s)
return SV_DEBUG;
63 if (s ==
"INFO"s)
return SV_INFO;
64 if (s ==
"WARN"s)
return SV_WARN;
65 if (s ==
"ERROR"s)
return SV_ERROR;
66 if (s ==
"FATAL"s)
return SV_FATAL;
67 throw std::range_error(
"unknown severity string");
78 Logger() : f(
nullptr), level(SV_TRACE),
tz(
"GMT") { }
79 Logger(
const std::string& s,
const std::string& tz_p) : level(SV_TRACE) {
83 inline void init(
const std::string& s,
const std::string& tz_p) {
84 f = fopen(s.c_str(),
"a");
86 throw std::system_error(std::error_code(errno, std::system_category()),
87 "cannot open log file");
92 inline void uninit() {
109 f = fopen(s.c_str(),
"a");
117 inline int log(Severity sv,
const char* fmt, ...) {
121 std::string tm = tz::to_string(std::chrono::system_clock::now(),
122 "", tzones.find(
tz),
tz,
true);
123 static char str[BUFLEN];
125 vsnprintf(str, BUFLEN, fmt, ap);
127 fprintf(f,
"%s [%s]: %s\n", tm.c_str(), to_string(sv), str) :
128 printf(
"%s [%s]: %s\n", tm.c_str(), to_string(sv), str);
141 inline void setLevel(Severity sv) { level = sv; }
147 inline Severity from_string(
const std::string& s) {
148 if (s ==
"TRACE"s)
return SV_TRACE;
149 if (s ==
"DEBUG"s)
return SV_DEBUG;
150 if (s ==
"INFO"s)
return SV_INFO;
151 if (s ==
"WARN"s)
return SV_WARN;
152 if (s ==
"ERROR"s)
return SV_ERROR;
153 if (s ==
"FATAL"s)
return SV_FATAL;
154 throw std::range_error(
"unknown severity string");
162 static const int BUFLEN = 512;