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
|
#include "cru/common/Logger.h"
#include <array>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <memory>
#include <mutex>
#include <string_view>
namespace cru::log {
namespace {
Logger *CreateLogger() {
const auto logger = new Logger();
return logger;
}
} // namespace
Logger *Logger::GetInstance() {
static std::unique_ptr<Logger> logger{CreateLogger()};
return logger.get();
}
void Logger::AddSource(std::unique_ptr<ILogSource> source) {
sources_.push_back(std::move(source));
}
void Logger::RemoveSource(ILogSource *source) {
sources_.remove_if([source](const std::unique_ptr<ILogSource> &s) {
return s.get() == source;
});
}
namespace {
String LogLevelToString(LogLevel level) {
switch (level) {
case LogLevel::Debug:
return u"DEBUG";
case LogLevel::Info:
return u"INFO";
case LogLevel::Warn:
return u"WARN";
case LogLevel::Error:
return u"ERROR";
default:
std::terminate();
}
}
String GetLogTime() {
auto time = std::time(nullptr);
auto calendar = std::localtime(&time);
return Format(u"{}:{}:{}", calendar->tm_hour, calendar->tm_min,
calendar->tm_sec);
}
} // namespace
void Logger::Log(LogLevel level, StringView message) {
#ifndef CRU_DEBUG
if (level == LogLevel::Debug) {
return;
}
#endif
for (const auto &source : sources_) {
source->Write(level, Format(u"[{}] {}: {}\n", GetLogTime(),
LogLevelToString(level), message));
}
}
void Logger::Log(LogLevel level, StringView tag, StringView message) {
#ifndef CRU_DEBUG
if (level == LogLevel::Debug) {
return;
}
#endif
for (const auto &source : sources_) {
source->Write(level, Format(u"[{}] {} {}: {}\n", GetLogTime(),
LogLevelToString(level), tag, message));
}
}
namespace {
std::mutex stdio_lock;
void WriteStdio(LogLevel level, StringView s) {
std::string m = s.ToString().ToUtf8();
if (level == LogLevel::Error) {
std::cerr << m;
} else {
std::cout << m;
}
}
} // namespace
StdioLogSource::StdioLogSource(bool use_lock) : use_lock_(use_lock) {}
StdioLogSource::~StdioLogSource() {}
void StdioLogSource::Write(LogLevel level, StringView s) {
if (use_lock_) {
std::lock_guard<std::mutex> guard(stdio_lock);
WriteStdio(level, s);
} else {
WriteStdio(level, s);
}
}
} // namespace cru::log
|