-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathlogger.cpp
More file actions
87 lines (76 loc) · 1.93 KB
/
Copy pathlogger.cpp
File metadata and controls
87 lines (76 loc) · 1.93 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
#include "../core/logger.h"
#include <iomanip>
#include <chrono>
Logger::Logger()
:logToStdout(false),logToStderr(false),logTime(true),files()
{}
Logger::~Logger()
{
for(size_t i = 0; i<logBufs.size(); i++)
delete logBufs[i];
for(size_t i = 0; i<files.size(); i++) {
files[i]->close();
delete files[i];
}
}
void Logger::setLogToStdout(bool b) {
logToStdout = b;
}
void Logger::setLogToStderr(bool b) {
logToStderr = b;
}
void Logger::setLogTime(bool b) {
logTime = b;
}
void Logger::addFile(const string& file) {
files.push_back(new ofstream(file, ofstream::app));
}
void Logger::write(const string& str, bool endLine) {
lock_guard<std::mutex> lock(mutex);
time_t time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
if(logToStdout) {
if(logTime)
cout << std::put_time(std::localtime(&time), "%F %T%z: ") << str;
else
cout << ": " << str;
if(endLine) cout << std::endl; else cout << std::flush;
}
if(logToStderr) {
if(logTime)
cerr << std::put_time(std::localtime(&time), "%F %T%z: ") << str;
else
cerr << ": " << str;
if(endLine) cerr << std::endl; else cerr << std::flush;
}
for(size_t i = 0; i<files.size(); i++) {
if(logTime)
(*files[i]) << std::put_time(std::localtime(&time), "%F %T%z: ") << str;
else
(*files[i]) << ": " << str;
if(endLine) (*files[i]) << std::endl; else (*files[i]) << std::flush;
}
}
void Logger::write(const string& str) {
write(str,true);
}
void Logger::writeNoEndline(const string& str) {
write(str,false);
}
ostream* Logger::createOStream() {
unique_lock<std::mutex> lock(mutex);
LogBuf* logBuf = new LogBuf(this);
logBufs.push_back(logBuf);
lock.unlock();
return new ostream(logBuf);
}
LogBuf::LogBuf(Logger* l)
:stringbuf(),logger(l)
{}
LogBuf::~LogBuf()
{}
int LogBuf::sync() {
const string& str = this->str();
logger->writeNoEndline(str);
this->str("");
return 0;
}