-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.hpp
93 lines (79 loc) · 1.71 KB
/
logger.hpp
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
//
// Created by anson on 19-2-25.
//
#ifndef FS_NDN_LOGGER_HPP
#define FS_NDN_LOGGER_HPP
#include <iostream>
#include <ctime>
enum LogLevel
{
LOG_NONE = 0, // Log nothing
LOG_ERROR = 1, // Log errors only
LOG_DEBUG = 2, // Log all (debug + error)
LOG_DEBUG2 = 3
};
inline const char* toString(LogLevel l)
{
switch (l)
{
case LOG_ERROR: return "ERROR";
default: return "DEBUG";
}
}
class Output2FILE // implementation of OutputPolicy
{
public:
static FILE*& stream();
static void output(const std::string& msg);
};
inline FILE*& Output2FILE::stream()
{
static FILE* pStream = stderr;
return pStream;
}
inline void Output2FILE::output(const std::string& msg)
{
FILE* pStream = stream();
if (!pStream)
return;
fprintf(pStream, "%s", msg.c_str());
fflush(pStream);
}
template <typename OutputPolicy>
class Log
{
public:
Log()
{
}
virtual ~Log()
{
OutputPolicy::output(os.str());
}
std::ostringstream& get(LogLevel level = LOG_DEBUG)
{
std::time_t time = std::time(nullptr);
os << "- " << time;
os << " " << toString(level) << ": ";
os << std::string(level > LOG_DEBUG ? level - LOG_DEBUG : 0, '\t');
logLevel_ = level;
return os;
}
public:
static LogLevel& reportingLevel()
{
static LogLevel level = LOG_DEBUG;
return level;
}
protected:
std::ostringstream os;
private:
Log(const Log&);
Log& operator =(const Log&);
private:
LogLevel logLevel_;
};
#define FILE_LOG(level) \
if (level > Log<Output2FILE>::reportingLevel() || !Output2FILE::stream()) ; \
else Log<Output2FILE>().get(level)
#endif //FS_NDN_LOGGER_HPP