-
Notifications
You must be signed in to change notification settings - Fork 23
/
logger.cpp
400 lines (331 loc) · 9.21 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
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*
This file is part of FlashMQ (https://www.flashmq.org)
Copyright (C) 2021-2023 Wiebe Cazemier
FlashMQ is free software: you can redistribute it and/or modify
it under the terms of The Open Software License 3.0 (OSL-3.0).
See LICENSE for license details.
*/
#include "logger.h"
#include <sstream>
#include <iomanip>
#include <string.h>
#include <functional>
#include <mutex>
#include "threaddata.h"
#include "threadglobals.h"
#include "utils.h"
Logger* Logger::instance = nullptr;
std::mutex Logger::instanceMutex;
LogLine::LogLine(std::string &&line, bool alsoToStdOut) :
line(std::move(line)),
alsoToStdOut(alsoToStdOut)
{
}
LogLine::LogLine(const char *s, size_t len, bool alsoToStdOut) :
line(s, len),
alsoToStdOut(alsoToStdOut)
{
}
LogLine::LogLine() :
alsoToStdOut(true)
{
}
const char *LogLine::c_str() const
{
return line.c_str();
}
bool LogLine::alsoLogToStdOut() const
{
return alsoToStdOut;
}
Logger::Logger()
{
memset(&linesPending, 1, sizeof(sem_t));
sem_init(&linesPending, 0, 0);
auto f = std::bind(&Logger::writeLog, this);
this->writerThread = std::thread(f, this);
pthread_t native = this->writerThread.native_handle();
pthread_setname_np(native, "LogWriter");
}
Logger::~Logger()
{
if (running)
quit();
if (file)
{
fclose(file);
file = nullptr;
}
sem_close(&linesPending);
}
std::string_view Logger::getLogLevelString(int level)
{
switch (level)
{
case LOG_NONE:
return "NONE";
case LOG_INFO:
return "INFO";
case LOG_NOTICE:
return "NOTICE";
case LOG_WARNING:
return "WARNING";
case LOG_ERR:
return "ERROR";
case LOG_DEBUG:
return "DEBUG";
case LOG_SUBSCRIBE:
return "SUBSCRIBE";
case LOG_UNSUBSCRIBE:
return "UNSUBSCRIBE";
default:
return "UNKNOWN LOG LEVEL";
}
}
Logger *Logger::getInstance()
{
// Prevent duplicate creation without always needing the mutex.
if (instance == nullptr)
{
std::lock_guard<std::mutex> locker(instanceMutex);
if (instance == nullptr)
instance = new Logger();
}
return instance;
}
/**
* @brief Logger::stopAndReset was created for the test binary. Normally you shouldn't use this. It's also not thread-safe (it's raw pointer, not
* a smart pointer).
*/
void Logger::stopAndReset()
{
std::lock_guard<std::mutex> locker(instanceMutex);
instance->quit();
delete instance;
instance = nullptr;
}
void Logger::logf(int level, const char *str, ...)
{
va_list valist;
va_start(valist, str);
this->logf(level, str, valist);
va_end(valist);
}
/**
* @brief Logger::log
* @param level
* @return a StreamToLog, that you're not suppose to name. When you don't, its destructor will log the stream.
*
* Allows logging like: logger->log(LOG_NOTICE) << "blabla: " << 1 << ".". The advantage is safety (printf crashes), and not forgetting printf arguments.
*
* Beware though: C++ streams chars as characters. When you have an uint8_t or int8_t that's also a char, and those need to be cast to int first. A good
* solution needs to be devised.
*/
StreamToLog Logger::log(int level)
{
return StreamToLog(level);
}
void Logger::queueReOpen()
{
reload = true;
sem_post(&linesPending);
}
void Logger::reOpen()
{
reload = false;
if (file)
{
// Any further use of 'file' is undefined behavior, including closing again, so we just have to abandon it.
const int rc = fclose(file);
file = nullptr;
if (rc != 0)
{
const std::string err(strerror(errno));
log(LOG_ERR) << "Closing the log file failed with: " << err << ". Depending on whether it can be reopened again, logging may continue on stdout.";
}
}
if (logPath.empty())
return;
if ((file = fopen(logPath.c_str(), "a")) == nullptr)
{
logf(LOG_ERR, "(Re)opening log file '%s' error: %s. Logging to stdout.", logPath.c_str(), strerror(errno));
}
}
// I want all messages logged during app startup to also show on stdout/err, otherwise failure can look so silent. So, call this when the app started.
void Logger::noLongerLogToStd()
{
if (!logPath.empty())
logf(LOG_INFO, "Switching logging from stdout to logfile '%s'", logPath.c_str());
alsoLogToStd = false;
}
void Logger::setLogPath(const std::string &path)
{
this->logPath = path;
}
/**
* @brief Logger::setFlags sets the log level based on a maximum desired level.
* @param level Level based on the defines LOG_*.
* @param logSubscriptions
* @param quiet
*
* The log levels are mosquitto-compatible, and while the terminology is similar to the syslog standard, they are unfortunately
* not in order of verbosity/priority. So, we use our own enum for the config setting, so that DEBUG is indeed more verbose than INFO.
*
* The subscriptions flag is still set explicitly, because you may want that irrespective of the log level.
*/
void Logger::setFlags(LogLevel level, bool logSubscriptions)
{
curLogLevel = 0;
if (level <= LogLevel::Debug)
curLogLevel |= LOG_DEBUG;
if (level <= LogLevel::Info)
curLogLevel |= LOG_INFO;
if (level <= LogLevel::Notice)
curLogLevel |= LOG_NOTICE;
if (level <= LogLevel::Warning)
curLogLevel |= LOG_WARNING;
if (level <= LogLevel::Error)
curLogLevel |= LOG_ERR;
if (logSubscriptions)
curLogLevel |= (LOG_UNSUBSCRIBE | LOG_SUBSCRIBE);
else
curLogLevel &= ~(LOG_UNSUBSCRIBE | LOG_SUBSCRIBE);
}
/**
* @brief Logger::setFlags is provided for backwards compatability
* @param logDebug
* @param quiet
*/
void Logger::setFlags(std::optional<bool> logDebug, std::optional<bool> quiet)
{
if (logDebug)
{
if (logDebug.value())
curLogLevel |= LOG_DEBUG;
else
curLogLevel &= ~LOG_DEBUG;
}
// It only makes sense to allow quiet to mute things in backward compatability mode, not enable LOG_NOTICE and LOG_INFO again.
if (quiet)
{
if (quiet.value())
curLogLevel &= ~(LOG_NOTICE | LOG_INFO);
}
}
void Logger::quit()
{
running = false;
sem_post(&linesPending);
if (writerThread.joinable())
writerThread.join();
}
void Logger::writeLog()
{
maskAllSignalsCurrentThread();
int graceCounter = 0;
LogLine line;
while(running || (!lines.empty() && graceCounter++ < 1000 ))
{
sem_wait(&linesPending);
if (reload)
{
reOpen();
}
{
std::lock_guard<std::mutex> locker(logMutex);
if (lines.empty())
continue;
line = std::move(lines.front());
lines.pop();
}
if (this->file)
{
if (fputs(line.c_str(), this->file) < 0 ||
fputs("\n", this->file) < 0 ||
fflush(this->file) != 0)
{
alsoLogToStd = true;
fputs("Writing to log failed. Enabling stdout logger.", stderr);
}
}
if (!this->file || line.alsoLogToStdOut())
{
FILE *output = stdout;
#ifdef TESTING
output = stderr; // the stdout interfers with Qt test XML output, so using stderr.
#endif
fputs(line.c_str(), output);
fputs("\n", output);
fflush(output);
}
}
}
std::string Logger::getPrefix(int level)
{
int threadnr = -1;
const ThreadData *td = ThreadGlobals::getThreadData();
if (td)
threadnr = td->threadnr;
std::ostringstream oss;
const std::string stamp = timestampWithMillis();
oss << "[" << stamp << "] [" << getLogLevelString(level) << "] ";
if (threadnr == -1)
oss << "[main] ";
else
oss << "[T " << threadnr << "] ";
std::string result = oss.str();
return result;
}
void Logger::logstring(int level, const std::string &str)
{
if ((level & curLogLevel) == 0)
return;
std::string s = getPrefix(level);
s.append(str);
LogLine line(std::move(s), alsoLogToStd);
{
std::lock_guard<std::mutex> locker(logMutex);
lines.push(std::move(line));
}
sem_post(&linesPending);
}
void Logger::logf(int level, const char *str, va_list valist)
{
if ((level & curLogLevel) == 0)
return;
std::string s = getPrefix(level);
s.append(str);
const char *logfmtstring = s.c_str();
constexpr const int buf_size = 512;
char buf[buf_size + 1];
buf[buf_size] = 0;
va_list valist2;
va_copy(valist2, valist);
vsnprintf(buf, buf_size, logfmtstring, valist2);
size_t len = std::min<size_t>(buf_size, strlen(buf));
LogLine line(buf, len, alsoLogToStd);
va_end(valist2);
{
std::lock_guard<std::mutex> locker(logMutex);
lines.push(std::move(line));
}
sem_post(&linesPending);
}
int logSslError(const char *str, size_t len, void *u)
{
(void) u;
std::string msg(str, len);
Logger *logger = Logger::getInstance();
logger->logstring(LOG_ERR, msg);
return 0;
}
StreamToLog::StreamToLog(int level) :
level(level)
{
}
StreamToLog::~StreamToLog()
{
const std::string s = str();
Logger *logger = Logger::getInstance();
logger->logstring(this->level, s);
}