/
Logger.cpp
88 lines (74 loc) · 1.94 KB
/
Logger.cpp
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
#include "Logger.h"
Logger::Logger(){
}
Logger::~Logger(){
}
std::string stringify(const LogSeverity severity){
std::map<LogSeverity, std::string>S_SEVERITY_MAP = {
{LogSeverity::error, "ERROR"},
{LogSeverity::warning, "WARNING"},
{LogSeverity::info, "INFO"},
{LogSeverity::debug, "DEBUG"},
};
std::string result = "NONE";
auto it = S_SEVERITY_MAP.find(severity);
if(it != S_SEVERITY_MAP.end()){
result = it->second;
}
return result;
}
void Logger::init(const std::string& filename, const LogOutput output){
m_filename = filename;
m_output = output;
}
void Logger::open(){
if(m_output == LogOutput::everywhere || m_output == LogOutput::file){
m_file.open(m_filename, std::ios::out);
m_isOpened = m_file.is_open();
if(!m_isOpened){
throw std::runtime_error("Couldnt open a log file");
}
}
m_isOpened = true;
}
void Logger::close(){
if(m_output == LogOutput::everywhere || m_output == LogOutput::file){
m_file.close();
}
}
void Logger::flush(){
if(m_output == LogOutput::everywhere || m_output == LogOutput::file){
m_file.flush();
}
}
void Logger::log(const std::string& msg, const LogSeverity severity){
std::string result = timestamp() +
" " + threadId() +
" " + stringify(severity) +
" " + msg;
if(m_output == LogOutput::console){
std::cout << result << std::endl;
}
if(m_output == LogOutput::file){
m_file << result << std::endl;
} else{
std::cout << result << std::endl;
m_file << result << std::endl;
}
}
/////////////////// PRIVATE
std::string Logger::timestamp(){
using namespace std::chrono;
auto now = system_clock::now();
time_t tt = system_clock::to_time_t(now);
auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
std::stringstream ss;
ss << std::put_time(std::localtime(&tt), "%F %T");
ss << "." << std::setfill('0') << std::setw(3) << ms.count();
return ss.str();
}
std::string Logger::threadId(){
std::stringstream ss;
ss << std::this_thread::get_id();
return ss.str();
}