-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.cpp
152 lines (136 loc) · 2.42 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include <ctime>
#include <cstring>
#include <clocale>
#include "logger.hpp"
#include "main.hpp"
uint8_t Logger::pLogLevel=LOG_DEBUG;
bool Logger::pLogFileEnabled=true;
mutex *Logger::pLogMutex=nullptr;
Logger *gLogger=nullptr;
const char mgstypestring[8][10]=
{
"EMERGENCY",
"ALERT",
"CRITICAL",
"ERROR",
"WARNING",
"NOTICE",
"INFO",
"DEBUG"
};
Logger::Logger()
{
if(gLogger)
{
return;
}
gLogger=this;
if(!pLogMutex)
{
pLogMutex=new mutex;
}
pSysLogEnabled=false;
pLogFilePath.clear();
pLogFile=nullptr;
}
Logger::~Logger()
{
if(pLogFile)
{
fclose(pLogFile);
pLogFile=nullptr;
}
}
uint8_t Logger::LogLevel() const
{
return(pLogLevel);
}
void Logger::SetLogLevel(uint8_t log_level)
{
if(log_level>LOG_DEBUG)
{
log_level=LOG_DEBUG;
}
pLogMutex->lock();
pLogLevel=log_level;
pLogMutex->unlock();
}
bool Logger::LogFileEnabled() const
{
return(pLogFileEnabled);
}
void Logger::SetLogFileEnabled(bool enabled)
{
pLogMutex->lock();
pLogFileEnabled=enabled;
pLogMutex->unlock();
}
string Logger::LogFilePath() const
{
return(pLogFilePath);
}
void Logger::SetLogFilePath(const string newPath)
{
if(newPath.length()==0)
{
return;
}
pLogMutex->lock();
pLogFilePath=newPath;
pLogMutex->unlock();
}
bool Logger::SysLogEnabled() const
{
return(pSysLogEnabled);
}
void Logger::SetSysLogEnabled(bool enabled)
{
pLogMutex->lock();
pSysLogEnabled=enabled;
pLogMutex->unlock();
}
void Logger::Log(const char *message, uint8_t msg_level)
{
if(!message)
{
return;
}
string msg(message);
Log(msg, msg_level);
}
void Logger::Log(const string message, uint8_t msg_level)
{
if(msg_level>pLogLevel)
{
return;
}
if(0==message.length())
{
return;
}
setlocale(LC_NUMERIC, "C");
pLogMutex->lock();
time(&pRawTime);
pTimeInfo=localtime(&pRawTime);
sprintf(pLogDTstr, "%.2i/%.2i/%i %.2i:%.2i:%.2i", pTimeInfo->tm_mday, 1+pTimeInfo->tm_mon, 1900+pTimeInfo->tm_year, pTimeInfo->tm_hour, pTimeInfo->tm_min, pTimeInfo->tm_sec);
fprintf(stdout, "%s [%s] %s\n", pLogDTstr, mgstypestring[msg_level], message.data());
fflush(stdout);
if(pLogFileEnabled)
{
pLogFile=fopen(pLogFilePath.data(), "a");
if(pLogFile)
{
fprintf(pLogFile, "%s [%s] %s\n", pLogDTstr, mgstypestring[msg_level], message.data());
fflush(pLogFile);
fclose(pLogFile);
pLogFile=nullptr;
}
}
#if defined(__linux__)
if(pSysLogEnabled)
{
syslog(msg_level, "%s %s", pLogDTstr, message.data());
}
#endif
pLogMutex->unlock();
}