forked from dyninc/OpenBFDD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Logger.cpp
executable file
·643 lines (513 loc) · 13.5 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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/**************************************************************
* Copyright (c) 2010-2014, Dynamic Network Services, Inc.
* Author - Jake Montgomery ([email protected])
* Distributed under the FreeBSD License - see LICENSE
***************************************************************/
#include "standard.h"
#include "Logger.h"
#include "LogException.h"
#include "compat.h"
#include <syslog.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
const size_t Logger::MaxMessageLen;
// We use our own simple auto lock, since the real one uses logging ... which
// would be a problem. Be careful, as this class does not include the same
// checks as the full featured one.
class LogAutoLock
{
public:
enum LockType
{
None, // not locked
Read, // Read locked
Write // write locked.
};
LogAutoLock(pthread_rwlock_t *lock, LogAutoLock::LockType lockInitial)
{
m_rwLock = lock;
m_lockedByMeType = LogAutoLock::None;
if (lockInitial == LogAutoLock::Read)
ReadLock();
else if (lockInitial == LogAutoLock::Write)
WriteLock();
}
~LogAutoLock()
{
if (m_lockedByMeType != LogAutoLock::None)
UnLock();
}
bool ReadLock()
{
if (pthread_rwlock_rdlock(m_rwLock))
{
fprintf(stderr, "pthread_rwlock_rdlock failed\n");
return false;
}
m_lockedByMeType = LogAutoLock::Read;
return true;
}
bool WriteLock()
{
if (pthread_rwlock_wrlock(m_rwLock))
{
fprintf(stderr, "pthread_rwlock_wrlock failed\n");
return false;
}
m_lockedByMeType = LogAutoLock::Write;
return true;
}
bool UnLock()
{
if (pthread_rwlock_unlock(m_rwLock))
{
fprintf(stderr, "pthread_rwlock_unlock failed\n");
return false;
}
m_lockedByMeType = LogAutoLock::None;
return true;
}
private:
pthread_rwlock_t *m_rwLock;
LogAutoLock::LockType m_lockedByMeType;
};
Logger:: Logger() :
m_types(NULL)
, m_typeCount(Log::TypeCount)
, m_levelsMap(NULL)
, m_levelCount(Log::LevelCount)
, m_logFile(NULL)
, m_useSyslog(false)
, m_extendedTimeInfo(TimeInfo::None)
{
if (pthread_rwlock_init(&m_settingsLock, NULL))
{
fprintf(stderr, "pthread_rwlock_init failed\n");
exit(1);
}
// Create the levels and types. Yes, this may leak a little if a memory
// exception is thrown.
m_levelsMap = new LevelInfo[m_levelCount];
m_types = new TypeInfo[m_typeCount];
for (size_t i = 0; i < m_levelCount; ++i)
{
m_levelsMap[i].types = new bool[m_typeCount];
m_levelsMap[i].name = "unknown";
}
// Setup all types to defaults
for (size_t index = 0; index < m_typeCount; index++)
{
m_types[index].enabled = false;
m_types[index].throws = false;
m_types[index].syslogPriority = LOG_INFO;
m_types[index].logName = "info";
m_types[index].name = "xxdummyxxx";
m_types[index].description = NULL;
m_types[index].toStdErr = false;
m_types[index].toStdOut = false;
}
}
Logger::~Logger()
{
closeLogFile();
closeSyslog();
for (size_t i = 0; i < m_levelCount; ++i)
delete[] m_levelsMap[i].types;
delete[] m_levelsMap;
delete[] m_types;
if (pthread_rwlock_destroy(&m_settingsLock))
fprintf(stderr, "pthread_rwlock_destroy failed\n");
}
inline bool Logger::isLogTypeValid(Log::Type type)
{
return type >= 0 && static_cast<size_t>(type) < m_typeCount;
}
inline bool Logger::isLogLevelValid(Log::Level level)
{
return level >= 0 && static_cast<size_t>(level) < m_levelCount;
}
void Logger::copyLevelTypes(Log::Level source, Log::Level dest)
{
if (!isLogLevelValid(source) || !isLogLevelValid(dest))
return;
memcpy(m_levelsMap[dest].types, m_levelsMap[source].types, sizeof(bool) * m_typeCount);
}
void Logger::setLevelTypes(Log::Level level, bool value)
{
if (!isLogLevelValid(level))
return;
memset(m_levelsMap[level].types, value ? 1 : 0, sizeof(bool) * m_typeCount);
}
void Logger::LogToSyslog(const char *ident, bool teeLogToStderr)
{
LogAutoLock lock(&m_settingsLock, LogAutoLock::Write);
int opt = LOG_NDELAY;
if (teeLogToStderr)
opt |= LOG_PERROR;
closeLogFile();
closeSyslog();
openlog(ident, opt, LOG_DAEMON);
m_useSyslog = true;
m_ident = ident;
}
/**
* Closes syslog logging.
* Must hold write lock to call.
*/
void Logger::closeSyslog()
{
if (m_useSyslog)
closelog();
m_useSyslog = false;
}
/**
* All logging goes to the file. Stops syslog logging.
*
* @param logFilePath [in] - The path of the file to log to.
*
* @return bool - false if failed to open file.
*/
bool Logger::LogToFile(const char *logFilePath)
{
FILE *newFile;
LogAutoLock lock(&m_settingsLock, LogAutoLock::Write);
if (!logFilePath || !logFilePath[0])
{
closeLogFile();
m_logFile = NULL;
return true;
}
if (0 == m_logFilePath.compare(logFilePath))
return true;
newFile = ::fopen(logFilePath, "a");
if (!newFile)
{
char buf[1024];
compat_strerror_r(errno, buf, sizeof(buf));
fprintf(stderr, "Failed to open logfile %s: %s\n", logFilePath, buf);
return false;
}
closeLogFile();
m_logFile = newFile;
m_logFilePath = logFilePath;
return true;
}
/**
* Closes File logging.
* Must hold write lock to call.
*/
void Logger::closeLogFile()
{
if (m_logFile)
fclose(m_logFile);
m_logFile = NULL;
m_logFilePath.clear();
}
void Logger::SetLogLevel(Log::Level level)
{
if (!isLogLevelValid(level))
return;
LogAutoLock lock(&m_settingsLock, LogAutoLock::Write);
// Set all log types.
for (size_t index = 0; index < m_typeCount; index++)
m_types[index].enabled = isTypeInLevel((Log::Type)index, level);
}
void Logger::SetStdOut(Log::Type type, bool shouldOut)
{
if (!isLogTypeValid(type))
return;
LogAutoLock lock(&m_settingsLock, LogAutoLock::Write);
m_types[type].toStdOut = shouldOut;
}
void Logger::SetStdOut(Log::Level level, bool shouldOut)
{
if (!isLogLevelValid(level))
return;
LogAutoLock lock(&m_settingsLock, LogAutoLock::Write);
for (size_t index = 0; index < m_typeCount; index++)
{
if (isTypeInLevel((Log::Type)index, level))
m_types[index].toStdOut = shouldOut;
}
}
void Logger::SetStdErr(Log::Type type, bool shouldOut)
{
if (!isLogTypeValid(type))
return;
LogAutoLock lock(&m_settingsLock, LogAutoLock::Write);
m_types[type].toStdErr = shouldOut;
}
void Logger::SetStdErr(Log::Level level, bool shouldOut)
{
if (!isLogLevelValid(level))
return;
LogAutoLock lock(&m_settingsLock, LogAutoLock::Write);
for (size_t index = 0; index < m_typeCount; index++)
{
if (isTypeInLevel((Log::Type)index, level))
m_types[index].toStdErr = shouldOut;
}
}
void Logger::SetExtendedTimeInfo(TimeInfo::Type type)
{
LogAutoLock lock(&m_settingsLock, LogAutoLock::Write);
m_extendedTimeInfo = type;
}
void Logger::SetPrintTypeNames(bool printTypeNames)
{
LogAutoLock lock(&m_settingsLock, LogAutoLock::Write);
m_printTypeNames = printTypeNames;
}
const char* Logger::LogTypeToString(Log::Type type)
{
// Since names never change, there is no need for lock
if (!isLogTypeValid(type))
return "unknown";
return m_types[type].name;
}
const char* Logger::LogTypeDescription(Log::Type type)
{
// Since names never change, there is no need for lock
if (!isLogTypeValid(type))
return "";
if (m_types[type].description == NULL)
return "";
return m_types[type].description;
}
Log::Type Logger::StringToLogType(const char *str)
{
if (!str)
return Log::TypeCount;
// Since names never change, there is no need for lock
for (size_t index = 0; index < m_typeCount; index++)
{
if (0 == strcmp(m_types[index].name, str))
return(Log::Type)index;
}
return Log::TypeCount;
}
const char* Logger::LogLevelToString(Log::Level level)
{
if (!isLogLevelValid(level))
return "unknown";
return m_levelsMap[level].name.c_str();
}
Log::Level Logger::StringToLogLevel(const char *str)
{
if (!str)
return Log::LevelCount;
for (size_t index = 0; index < m_levelCount; index++)
{
if (0 == strcmp(m_levelsMap[index].name.c_str(), str))
return(Log::Level)index;
}
return Log::LevelCount;
}
void Logger::EnableLogType(Log::Type type, bool enable)
{
LogAutoLock lock(&m_settingsLock, LogAutoLock::Write);
if (!isLogTypeValid(type))
return;
m_types[type].enabled = enable;
}
bool Logger::LogTypeEnabled(Log::Type type)
{
LogAutoLock lock(&m_settingsLock, LogAutoLock::Read);
if (!isLogTypeValid(type))
return false;
return m_types[type].enabled;
}
void Logger::Optional(Log::Type type, const char *format, ...)
{
LogAutoLock lock(&m_settingsLock, LogAutoLock::Read);
if (!isLogTypeValid(type))
return;
if (!m_types[type].enabled)
return;
va_list args;
va_start(args, format);
logMsg(&m_types[type], format, args);
va_end(args);
}
void Logger::OptionalVa(Log::Type type, const char *format, va_list args)
{
LogAutoLock lock(&m_settingsLock, LogAutoLock::Read);
if (!isLogTypeValid(type))
return;
if (!m_types[type].enabled)
return;
logMsg(&m_types[type], format, args);
}
void Logger::Message(Log::Type type, const char *format, ...)
{
LogAutoLock lock(&m_settingsLock, LogAutoLock::Read);
if (!isLogTypeValid(type))
return;
va_list args;
va_start(args, format);
logMsg(&m_types[type], format, args);
va_end(args);
}
void Logger::MessageVa(Log::Type type, const char *format, va_list args)
{
LogAutoLock lock(&m_settingsLock, LogAutoLock::Read);
if (!isLogTypeValid(type))
return;
logMsg(&m_types[type], format, args);
}
/**
*
* Do the actual message format and output.
* Must hold at least a read lock.
*
*/
void Logger::logMsg(const TypeInfo *typeInfo, const char *format, va_list args)
{
char message[MaxMessageLen];
char timeStr[64];
vsnprintf(message, sizeof(message), format, args);
if (typeInfo->throws)
throw (LogException(message));
if (m_extendedTimeInfo == TimeInfo::Real)
{
struct timespec extendedNow;
if (0 > clock_gettime(CLOCK_REALTIME, &extendedNow))
extendedNow.tv_sec = extendedNow.tv_nsec = 0;
snprintf(timeStr, sizeof(timeStr), "[%jd:%09ld]", (intmax_t)extendedNow.tv_sec, extendedNow.tv_nsec);
}
else if (m_extendedTimeInfo == TimeInfo::Mono)
{
struct timespec extendedNow;
if (0 > clock_gettime(CLOCK_MONOTONIC, &extendedNow))
extendedNow.tv_sec = extendedNow.tv_nsec = 0;
snprintf(timeStr, sizeof(timeStr), "[%jd:%09ld]", (intmax_t)extendedNow.tv_sec, extendedNow.tv_nsec);
}
else
timeStr[0] = '\0';
const char *logName = "";
const char *logNamePrefix = "";
if (m_printTypeNames)
{
logName = typeInfo->logName;
logNamePrefix = " ";
}
if (m_useSyslog)
{
syslog(typeInfo->syslogPriority, "[%d]%s%s%s: %s",
(int)getpid(),
timeStr,
logNamePrefix, logName, message);
}
if (!m_logFile && !typeInfo->toStdErr && !typeInfo->toStdOut)
return;
if (m_logFile)
{
time_t now = (time_t)time(NULL);
fprintf(m_logFile, "[%u] %s[%d]%s%s%s: %s\n", (unsigned int)now,
m_ident.c_str(), (int)getpid(),
timeStr,
logNamePrefix, logName, message);
fflush(m_logFile);
}
if (typeInfo->toStdErr || typeInfo->toStdOut)
{
for (int i = 0; i < 2; ++i)
{
FILE *dst;
if (i == 0 && typeInfo->toStdErr)
dst = stderr;
else if (i == 0 && typeInfo->toStdOut)
dst = stdout;
else
continue;
// no pid for stderr and stdout
if (!m_ident.empty() || timeStr[0] != '\0')
{
fprintf(dst, "%s%s%s%s: %s\n",
m_ident.c_str(),
timeStr,
logNamePrefix, logName, message);
}
else if (m_printTypeNames)
fprintf(dst, "%s: %s\n", logName, message);
else
fprintf(dst, "%s\n", message);
}
}
}
/**
* Always logs message.
* If using syslog then this uses the LOG_WARNING level.
* No newline is needed.
*/
void Logger::LogWarn(const char *format, ...)
{
Log::Type type = Log::Warn;
LogAutoLock lock(&m_settingsLock, LogAutoLock::Read);
va_list args;
va_start(args, format);
logMsg(&m_types[type], format, args);
va_end(args);
}
/**
* Always logs message.
* If using syslog then this uses the LOG_ERR level.
* No newline is needed.
*/
void Logger::LogError(const char *format, ...)
{
Log::Type type = Log::Error;
LogAutoLock lock(&m_settingsLock, LogAutoLock::Read);
va_list args;
va_start(args, format);
logMsg(&m_types[type], format, args);
va_end(args);
}
void Logger::ErrnoError(int errnum, const char *mgs)
{
char buf[1024];
compat_strerror_r(errnum, buf, sizeof(buf));
LogError("%s: (%d) %s", mgs, errnum, buf);
}
/**
* Logs a message and exits the program.
* If using syslog then this uses the LOG_CRIT level.
* No newline is needed.
*/
void Logger::Fatal(const char *format, ...)
{
Log::Type type = Log::Critical;
LogAutoLock lock(&m_settingsLock, LogAutoLock::Read);
va_list args;
va_start(args, format);
logMsg(&m_types[type], format, args);
va_end(args);
exit(1);
}
void Logger::ThrowOnLogType(Log::Type type, bool shouldThrow)
{
LogAutoLock lock(&m_settingsLock, LogAutoLock::Write);
if (!isLogTypeValid(type))
return;
m_types[type].throws = shouldThrow;
}
bool Logger::ThrowOnLogTypeEnabled(Log::Type type)
{
LogAutoLock lock(&m_settingsLock, LogAutoLock::Read);
if (!isLogTypeValid(type))
return false;
return m_types[type].throws;
}
/**
* Maps type to level. Does not check ranges.
*
* @param type
* @param level
*
* @return bool
*/
bool Logger::isTypeInLevel(Log::Type type, Log::Level level)
{
return m_levelsMap[level].types[type];
}