-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLogger.h
63 lines (52 loc) · 1.22 KB
/
Logger.h
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
#include <ostream>
#include <ctime>
#include <sstream>
#include <iomanip>
class Logger {
public:
Logger(std::ostream & backend, int level, bool showTimestamp = false)
: m_level(level), m_showTimestamp(showTimestamp),
m_realStream(backend, true), m_devNull(backend, false)
{}
enum {TRACE, DEBUG, INFO, WARNING, ERROR, FATAL};
class LogStream {
friend class Logger;
LogStream(std::ostream & backend, bool enabled)
: m_backend(backend), m_enabled(enabled)
{}
std::ostream & m_backend;
bool m_enabled;
public:
template <class T>
LogStream & operator<<(const T & x) {
if (m_enabled) {
m_backend << x;
}
return *this;
}
};
LogStream & log(int level) {
if (level >= m_level) {
if (m_showTimestamp) {
m_realStream << timestamp();
}
return m_realStream;
} else {
return m_devNull;
}
}
std::string timestamp() {
std::clock_t now = clock();
std::clock_t totalMillis = now / (CLOCKS_PER_SEC / 1000);
std::ostringstream buf;
buf << std::setw(3) << (totalMillis / 1000) << "."
<< std::setfill('0') << std::setw(3) << (totalMillis % 1000)
<< " ";
return buf.str();
}
private:
int m_level;
bool m_showTimestamp;
LogStream m_realStream;
LogStream m_devNull;
};