-
Notifications
You must be signed in to change notification settings - Fork 0
/
hola_logger.h
362 lines (308 loc) · 10.2 KB
/
hola_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
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
#ifndef _HOLA_LOGGER_H_
#define _HOLA_LOGGER_H_
#include <string>
#include <vector>
#include <mutex>
#include <iomanip>
#include <algorithm>
#include <thread>
#include <chrono>
#include <sstream>
#include <fstream>
#include <iostream>
#include <deque>
#include <condition_variable>
#if defined(WIN32) || defined(_WIN32)
#include <io.h>
#else
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#endif
#define DEFAULT_MAX_KB 1024 * 1024
#define MAX_LOG_BUFFER 100000
#if defined(WIN32) || defined(_WIN32)
#define PATH_SEP_CODE '\\'
#else
#define PATH_SEP_CODE '/'
#endif
namespace hola {
typedef enum
{
LOG_FATAL,
LOG_ERROR,
LOG_WARNING,
LOG_INFO,
LOG_DEBUG,
LOG_TRACE
} LogLevel;
static const std::vector<std::string> s_logAbbr = { "[F]", "[E]", "[W]", "[I]", "[D]", "[T]" };
static const std::vector<std::string> s_logName = { "Fatal", "Error", "Warning", "Info", "Debug", "Trace" };
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// LogOne ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename _OutputStream>
class LogOne
{
public:
LogOne(_OutputStream &os, LogLevel level = LOG_INFO) : _os(os), _level(level) {
auto pnow = std::chrono::system_clock::now();
auto tnow = std::chrono::system_clock::to_time_t(pnow);
_ss << std::put_time(std::localtime(&tnow), "%Y-%m-%d %H:%M:%S");
if (_enablems) {
_ss << "." << std::setfill('0') << std::setw(3) << tnow % 1000;
}
_ss << " " << s_logAbbr[level] << " ";
}
LogOne(const LogOne<_OutputStream> &one) : _os(one._os), _level(one._level), _ss(one._ss) {
}
~LogOne() {
if (_level <= _ulevel) {
std::lock_guard<std::mutex> lock(_mutex);
_os << _ss.str() + "\n";
}
}
template <typename _Value>
LogOne & operator<< (const _Value &val) {
_ss << val;
return *this;
}
static void setLogLevel(LogLevel level) {
_ulevel = level;
}
static void enableMilliSecond(bool enable) {
_enablems = enable;
}
private:
_OutputStream &_os;
LogLevel _level;
std::stringstream _ss;
static LogLevel _ulevel;
static bool _enablems;
static std::mutex _mutex;
};
template <typename _OutputStream> LogLevel LogOne<_OutputStream>::_ulevel = LOG_INFO;
template <typename _OutputStream> bool LogOne<_OutputStream>::_enablems = false;
template <typename _OutputStream> std::mutex LogOne<_OutputStream>::_mutex;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// SimpleLogger ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class SimpleLogger
{
template <typename _OutputStream> friend class LogOne;
public:
SimpleLogger(const std::string logFile) : _logFile(logFile) {
openLog();
}
virtual ~SimpleLogger() {
close();
}
bool isOpen() {
return _ofs.is_open();
}
void close() {
closeLog();
}
void setLogLevel(LogLevel level) {
LogOne<SimpleLogger>::setLogLevel(level);
}
void enableMilliSecond(bool enable) {
LogOne<SimpleLogger>::enableMilliSecond(enable);
}
protected:
virtual SimpleLogger & operator<<(const std::string &log) {
_ofs << log;
return *this;
}
virtual void openLog() {
if (!_logFile.empty()) {
_ofs.open(_logFile, std::ios::ate | std::ios::app);
}
}
virtual void closeLog() {
if (_ofs.is_open()) {
_ofs.close();
}
}
protected:
std::string _logFile;
std::ofstream _ofs;
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// HolaLogger ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class HolaLogger
{
template <typename _OutputStream> friend class LogOne;
public:
HolaLogger(const std::string &logFile) :
_logFile(logFile), _maxSize(DEFAULT_MAX_KB << 10), _curSize(0), _maxNum(10), _exitFlag(false) {
auto pos = logFile.rfind(PATH_SEP_CODE);
_logPath = pos == std::string::npos ? "" : logFile.substr(0, pos + 1);
_logName = pos == std::string::npos ? logFile : logFile.substr(pos + 1);
openLog();
listLog();
_logPtrCur = &_logBufA;
_logPtrBackup = &_logBufB;
_logThread = std::thread([this]() { logThread(); });
}
virtual ~HolaLogger() {
close();
}
bool isOpen() {
return _ofs.is_open();
}
void close() {
_exitFlag = true;
_cond.notify_one();
if (_logThread.joinable()) {
_logThread.join();
}
closeLog();
}
void setLogMaxKb(uint32_t maxKb) {
_maxSize = maxKb << 10;
}
void setMaxFileNum(uint32_t maxNum) {
_maxNum = maxNum < 1 ? 1 : maxNum;
resizeLog();
}
void setLogLevel(LogLevel level) {
LogOne<HolaLogger>::setLogLevel(level);
}
void enableMilliSecond(bool enable) {
LogOne<HolaLogger>::enableMilliSecond(enable);
}
private:
virtual HolaLogger & operator<<(const std::string &log) {
if (!_exitFlag) {
std::lock_guard<std::mutex> lock(_mutex);
if (_logPtrCur->size() >= MAX_LOG_BUFFER) {
_cond.notify_one();
} else {
_logPtrCur->push_back(log);
}
}
return *this;
}
void listLog() {
#if defined(WIN32) || defined(_WIN32)
long hFile = 0;
struct _finddata_t fileInfo;
if ((hFile = _findfirst((_logPath + _logName + "*").c_str(), &fileInfo)) != -1) {
do {
if (!(fileInfo.attrib & _A_SUBDIR) && _logName != fileInfo.name) {
_logList.emplace_back(_logPath + fileInfo.name);
}
} while (_findnext(hFile, &fileInfo) == 0);
_findclose(hFile);
}
#else
if (_logPath.empty()) {
_logPath = "./";
}
DIR *dir;
if ((dir = opendir(_logPath.c_str()))) {
struct dirent *info = nullptr;
while ((info = readdir(dir))) {
struct stat fstat;
if (std::string(info->d_name).find(_logName) == 0 &&
stat(info->d_name, &fstat) == 0 &&
S_ISREG(fstat.st_mode)) {
_logList.emplace_back(_logPath + info->d_name);
}
}
closedir(dir);
}
#endif
resizeLog();
}
void resizeLog() {
while (_maxNum <= _logList.size()) {
remove(_logList.front().c_str());
_logList.pop_front();
}
}
virtual void openLog() {
if (!_logFile.empty()) {
_ofs.open(_logFile, std::ios::ate | std::ios::app);
}
if (_ofs.is_open()) {
if (_ofs.tellp() == std::streampos(0)) {
_ofs << std::setfill('#') << std::setw(55) << "" << std::endl;
_ofs << "# Abbreviations used in this document" << std::setfill(' ') << std::setw(17) << "#" << std::endl;
for (size_t i = 0; i < s_logAbbr.size(); i++) {
_ofs << "# " << s_logAbbr[i] << " " << s_logName[i] << std::setfill(' ')
<< std::setw(44 - s_logName[i].length()) << "#" << std::endl;
}
_ofs << std::setfill('#') << std::setw(55) << "" << std::endl;
}
_curSize = _ofs.tellp();
}
}
virtual void closeLog() {
if (_ofs.is_open()) {
_ofs.close();
}
}
void switchLog() {
closeLog();
auto pnow = std::chrono::system_clock::now();
auto tnow = std::chrono::system_clock::to_time_t(pnow);
std::stringstream sstime;
sstime << std::put_time(std::localtime(&tnow), "%Y-%m-%d-%H-%M-%S");
std::string nameTo = _logFile + "_" + sstime.str();
rename(_logFile.c_str(), nameTo.c_str());
_logList.emplace_back(nameTo);
resizeLog();
return openLog();
}
void logThread()
{
while (!_exitFlag) {
{
std::unique_lock<std::mutex> lock(_mutex);
_cond.wait_for(lock, std::chrono::seconds(2));
if (_logPtrCur->empty()) {
continue;
} else {
std::swap(_logPtrCur, _logPtrBackup);
}
}
auto batchLog = [this](std::vector<std::string> *logPtr) {
for (auto &log : *logPtr) {
if (_curSize + log.length() > _maxSize) {
switchLog();
}
_ofs << log;
_curSize += log.length();
}
_ofs.flush();
logPtr->clear();
};
batchLog(_logPtrBackup);
if (_exitFlag) {
batchLog(_logPtrCur);
}
}
}
private:
std::string _logFile;
std::deque<std::string> _logList;
std::string _logPath;
std::string _logName;
std::ofstream _ofs;
std::mutex _mutex;
std::condition_variable _cond;
uint32_t _maxSize;
uint32_t _curSize;
uint32_t _maxNum;
bool _exitFlag;
std::thread _logThread;
std::vector<std::string> _logBufA;
std::vector<std::string> _logBufB;
std::vector<std::string> *_logPtrCur;
std::vector<std::string> *_logPtrBackup;
};
}
#endif // !_HOLA_LOGGER_H_