-
Notifications
You must be signed in to change notification settings - Fork 0
/
Logger.hpp
590 lines (468 loc) · 17.9 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
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
/*
* @author: Aaron Bacher
* @date: 2022-10-25
*
* @brief: Logger module for text and csv logging
* provides possibility for multithreading
*
* @note: -
*
*/
#pragma once
#include <string>
#include <fstream>
#include <vector>
#include <queue>
#include <memory>
#include <ctime>
#include <iostream>
#include <unistd.h>
#include <filesystem>
#define ENABLE_MULTITHREADING 1
#if ENABLE_MULTITHREADING
#include <mutex>
#include <thread>
#include <chrono>
// used by everybody (each class) which prints to console
// can (should) be used also outside this header file
std::mutex consoleMutex;
#endif
namespace fs = std::filesystem;
class LogEntry{
public:
LogEntry(const std::string& entry)
:m_entry(entry)
{}
virtual void constructEntry() {
// nothing to do here, just for derived classes to implement something
}
std::string getEntry() { return m_entry; }
protected:
LogEntry(){} // default constructor can only be called by derived classes
std::string m_entry;
};
// logger class
class Logger{
public:
Logger(bool enableConsolePrinting=false)
:m_enableConsolePrinting(enableConsolePrinting), m_isHandledByThreader(false)
{}
~Logger(){
m_logFile.close();
// remove logfile from s_openLogFiles
s_openLogFiles.erase(std::find(s_openLogFiles.begin(), s_openLogFiles.end(), m_logFilePath));
}
bool isHandledByThreader() { return m_isHandledByThreader; }
protected:
bool m_enableConsolePrinting;
std::string m_logFilePath;
std::ofstream m_logFile;
// method to intialize file
void setup(std::string logFileName, bool logFileNameIsAbsolutePath){
std::string logFileDir;
std::string dirSeparator;
#ifdef __linux__
dirSeparator = std::string("/");
#elif _WIN32
dirSeparator = std::string("\\");
#endif
if(!logFileNameIsAbsolutePath){
// compose logFile path
char cwd[256];
getcwd(cwd, 256);
logFileDir = std::string(cwd) + dirSeparator + "log";
m_logFilePath = logFileDir + dirSeparator + logFileName;
}
else{
m_logFilePath = logFileName;
std::size_t found = logFileName.rfind(dirSeparator);
if(found != std::string::npos){
logFileDir = logFileName.substr(0, found);
}
else{
logFileDir = dirSeparator;
}
}
// check that no other logger is already writing to that file
if (std::find(s_openLogFiles.begin(), s_openLogFiles.end(), m_logFilePath) != s_openLogFiles.end()){
std::string errMsg = "-----------\nERROR: log-file (" + m_logFilePath + ") already in use by other Logger!\n-----------";
printToConsole(errMsg);
}
else{
s_openLogFiles.push_back(m_logFilePath);
}
// check if log directory exists and create it if not
if(!fs::exists(logFileDir)){
fs::create_directory(logFileDir);
}
if(m_logFilePath.substr(m_logFilePath.size()-4, 4) == ".log"){ // append mode
m_logFile.open(m_logFilePath, std::ios::out | std::ios::app);
}
else if(m_logFilePath.substr(m_logFilePath.size()-4, 4) == ".csv"){ // delete file content and write afterwards
m_logFile.open(m_logFilePath, std::ios::out);
}
else{
std::string errMsg = "-----------\nERROR: Unknown log-file type!\n-----------";
printToConsole(errMsg);
}
// check if logfile creation and opening as been successful
if(!m_logFile.is_open()){
std::string errMsg = "-----------\nERROR: Could not open log-file! " + m_logFilePath + "\n-----------";
printToConsole(errMsg);
}
else{
std::string infoMsg = "Logging to file " + m_logFilePath;
printToConsole(infoMsg);
}
}
// handle printing to console with time stamps etc.
void printToConsole(const std::string& msg){
// note: I used to differentiate between error messages (then printed with cerr <<) and non-error messages (printed with cout <<)
// but as this might affect printing order (which was initially the objective of differentiating), I removed it
#if ENABLE_MULTITHREADING
consoleMutex.lock();
#endif
std::cout << msg << std::endl;
#if ENABLE_MULTITHREADING
consoleMutex.unlock();
#endif
}
// prints entry to logfile
void printToFile(const std::string& msg){
// print to file
m_logFile << msg << std::endl;
}
private:
bool m_isHandledByThreader; // defines if logger should work on its own (false) or if logging is done by LogThreader in separate thread (true)
inline static std::vector<std::string> s_openLogFiles; // holds paths to all currently open log files in order to make sure that not two loggers are writing to same one
// construct entry, give command to write to console and/or file
virtual void print(std::unique_ptr<LogEntry> entry, bool enforceConsoleWriting=false) = 0;
#if ENABLE_MULTITHREADING
public:
// removes first item in queue and passes it to caller (e.g. LogThreader) (returns nullptr if queue empty)
std::unique_ptr<LogEntry> getQueueItem(){
std::unique_ptr<LogEntry> entry;
m_queueMutex.lock();
if(m_logEntries.size() == 0){
return std::unique_ptr<LogEntry>(nullptr);
}
else{
entry = move(m_logEntries.front());
m_logEntries.pop();
}
m_queueMutex.unlock();
return move(entry);
}
int getQueueSize(){
int size;
// needed for stability, else it often pauses on exception during runtime (and for a try-catch block I would need a exception transport system between the threads
// with which I don't want to be bothered right now)
std::this_thread::sleep_for(std::chrono::nanoseconds(1));
m_queueMutex.lock();
size = m_logEntries.size();
m_queueMutex.unlock();
return size;
}
protected:
std::mutex m_queueMutex; // controls queue access
std::queue<std::unique_ptr<LogEntry>> m_logEntries; // if handled by LogThreader, log-method writes into this buffer instead of writing directly to file and/or console
private:
// LogThreader needs to access print function
friend class LogThreader;
#endif
};
// selection from https://www.ibm.com/docs/en/cognos-analytics/10.2.2?topic=SSEP7J_10.2.2/com.ibm.swg.ba.cognos.ug_rtm_wb.10.2.2.doc/c_n30e74.html
enum LogLevel {
Error,
Warning,
Info,
Debug
};
inline bool logLevelToStr(std::string& str, LogLevel logLevel){
switch (logLevel)
{
case LogLevel::Error:
str = "ERROR";
return true;
case LogLevel::Warning:
str = "WARNING";
return true;
case LogLevel::Info:
str = "INFO";
return true;
case LogLevel::Debug:
str = "DEBUG";
return true;
}
str = "UNDEFINED";
return false;
}
/* Derived Logger class to represend log-entries in normal text log */
class LogEntryText : public LogEntry{
public:
LogEntryText(LogLevel logLevel,
std::string msg,
std::string customTimeStr = "",
time_t rawTime = 0)
:m_logLevel(logLevel), m_msg(msg), m_customTimeStr(customTimeStr), m_rawTime(rawTime)
{}
void constructEntry() override{
m_entry = m_msg;
// add logLevel as string at front
addLogLevel(m_entry);
// add time as string at front
addTime(m_entry);
}
private:
// adds log Level as string in front of message
void addLogLevel(std::string& msg){
// create empty string and write LogLevel into it
std::string levelStr = "";
logLevelToStr(levelStr, m_logLevel);
// add colon
levelStr += ":";
// all log entries should have same length, so fill up space
// TODO does not work properly for Warnings
for(int i = 0; i < 12-levelStr.length(); ++i){
levelStr += " ";
}
// combine everything
msg = levelStr + msg;
}
// adds time as string in front of message
void addTime(std::string& msg){
// custom time
std::string customTimeStr = "";
if(m_customTimeStr != ""){
// TODO format
if(m_customTimeStr != " "){
msg = m_customTimeStr + " - " + msg;
}
}
else{
// real time
std::string rawTimeStr = "";
if(m_rawTime == 0){
time(&m_rawTime);
}
struct tm * timeinfo;
char buffer[80];
timeinfo = localtime(&m_rawTime);
strftime(buffer,sizeof(buffer),"%d-%m-%Y %H:%M:%S",timeinfo);
rawTimeStr = std::string(buffer);
// TODO format
msg = rawTimeStr + " - " + msg;
}
}
LogLevel m_logLevel;
std::string m_msg;
std::string m_customTimeStr = "";
time_t m_rawTime = 0;
};
/* Derived Logger class to handle text logging (normal .log-files) */
class TextLogger : public Logger{
public:
TextLogger(std::string logFileName, LogLevel newLogLevel, bool logFileNameIsAbsolutePath=false, bool enableConsolePrinting=false, bool useCustomTime=false) // for normal text logs
:Logger(enableConsolePrinting), m_logLevel(newLogLevel), m_useCustomTime(useCustomTime)
{
// if no specific logFileName provided, use default
if(logFileName == ""){
logFileName = "log0.log";
}
// if logfile has no file extension, add it
if(logFileName.substr(logFileName.size()-4, 4) != ".log"){
logFileName += ".log";
}
setup(logFileName, logFileNameIsAbsolutePath);
// check if passed log-level is valid (and get loglevel as string), else return
std::string levelStr = "";
if(!logLevelToStr(levelStr, m_logLevel)){
std::string errMsg = "Undefined LogLevel. Logger is terminating.";
std::unique_ptr<LogEntryText> entry = std::make_unique<LogEntryText>(LogLevel::Error, errMsg, "", 0);
print(move(entry));
return;
}
std::string initMsg = "Starting logger with log level " + levelStr;
std::unique_ptr<LogEntryText> entry = std::make_unique<LogEntryText>(LogLevel::Info, initMsg, "", 0);
print(move(entry));
}
~TextLogger(){
std::string infoMsg = "TextLogger has been shut down";
std::unique_ptr<LogEntryText> entry = std::make_unique<LogEntryText>(LogLevel::Info, infoMsg, "", 0);
print(move(entry), true);
m_logFile << "------------------------------------------\n\n";
}
// create log entries
// write entries to m_logEntries
void log(const std::string &logEntry, LogLevel logLevel, std::string timeStr = ""){
if(logLevel <= m_logLevel) {
time_t rawTime = 0;
if(!m_useCustomTime){
time (&rawTime);
}
std::unique_ptr<LogEntryText> entry = std::make_unique<LogEntryText>(logLevel, logEntry, timeStr, rawTime);
if(isHandledByThreader()){
#if ENABLE_MULTITHREADING
// write to queue
m_queueMutex.lock();
m_logEntries.push(move(entry));
m_queueMutex.unlock();
#endif
} else {
// write to log
print(move(entry));
}
}
}
// wrapper for above method
void log(const char* logEntry, LogLevel logLevel, std::string timeStr = ""){
std::string msg(logEntry); // convert char* to std::string
log(msg, logLevel, timeStr);
}
// allows to change loglevel after logger-construction.
// e.g. to increase loglevel temporarely
void setLogLevel(LogLevel newLogLevel){
m_logLevel = newLogLevel;
}
private:
LogLevel m_logLevel;
bool m_useCustomTime;
// construct entry, give command to write to console and/or file
void print(std::unique_ptr<LogEntry> entry, bool enforceConsoleWriting=false) override{
entry->constructEntry();
std::string msg = entry->getEntry();
// make entries at different locations
if(m_enableConsolePrinting || enforceConsoleWriting){
printToConsole(msg);
}
printToFile(msg);
}
};
/* Derived Logger class to handle text logging (normal .log-files) */
class CsvLogger : public Logger{
public:
CsvLogger(std::string logFileName, bool logFileNameIsAbsolutePath=false)
:Logger(false){
// if no specific logFileName provided, use default
if(logFileName == ""){
logFileName = "csv0.csv";
}
// if logfile has no file extension, add it
if(logFileName.substr(logFileName.size()-4, 4) != ".csv"){
logFileName += ".csv";
}
setup(logFileName, logFileNameIsAbsolutePath);
}
~CsvLogger(){
std::string infoMsg = "CsvLogger has been shut down";
printToConsole(infoMsg);
}
// create log entries
// write entries to m_logEntries
void log(const std::string &logEntry){
std::unique_ptr<LogEntry> entry = std::make_unique<LogEntry>(logEntry);
if(isHandledByThreader()){
#if ENABLE_MULTITHREADING
// write to queue
m_queueMutex.lock();
m_logEntries.push(move(entry));
m_queueMutex.unlock();
#endif
} else {
// write to log
print(move(entry));
}
}
void log(const char* logEntry){
std::string msg(logEntry); // convert char* to std::string
log(msg);
}
private:
// construct entry, give command to write to console and/or file
void print(std::unique_ptr<LogEntry> entry, bool enforceConsoleWriting=false) override{
entry->constructEntry();
std::string msg = entry->getEntry();
// check amount of columns
if(m_nColumns == 0){ // first time
for (int i = 0; i < msg.size(); ++i){
if(msg[i] == ',') ++m_nColumns;
}
++m_nColumns; // there is always one more column than semicolons
}
else { // every other time
int count = 1; // there is always one more column than semicolons
for (int i = 0; i < msg.size(); ++i){
if(msg[i] == ',') ++count;
}
if(count != m_nColumns){
std::string warningMsg = "WARNING! Amount of columns (" + std::to_string(count) + ") does not correspond to columns in first row (" + std::to_string(m_nColumns) + ")";
printToConsole(warningMsg);
}
}
if(enforceConsoleWriting) printToConsole(msg);
printToFile(msg);
}
// amount of columns; gets set on first entry according to amount of semicolons
int m_nColumns = 0;
};
#if ENABLE_MULTITHREADING
/* Class to handle multiple log-files in single thread */
class LogThreader {
public:
LogThreader(){
m_loggerRunning = true;
consoleMutex.lock();
std::cout << "LogThreader INFO: starting threader from thread id " << std::this_thread::get_id() << std::endl;
consoleMutex.unlock();
m_thread = std::thread(&LogThreader::logging, this);
}
~LogThreader(){
m_loggerRunning = false;
m_thread.join(); // wait for logging method to finish
consoleMutex.lock();
std::cout << "LogThreader INFO: threader has been shut down" << std::endl;
consoleMutex.unlock();
}
// add new logger to be handled
void addLogger(std::shared_ptr<Logger> logger){
m_handledLoggers.push_back(logger);
logger->m_isHandledByThreader = true;
std::string msgString = "Logger is now handled by LogThreader in separate thread";
// if csv file write to console only
if(logger->m_logFilePath.substr(logger->m_logFilePath.size()-4, 4) == ".csv"){
logger->printToConsole(msgString);
}
if(logger->m_logFilePath.substr(logger->m_logFilePath.size()-4, 4) == ".log"){
std::unique_ptr<LogEntryText> msg = std::make_unique<LogEntryText>(LogLevel::Info, msgString);
logger->print(move(msg));
}
}
private:
// runs in separate thread; continuously writes entries of m_logEntries to file and/or console
void logging(){
consoleMutex.lock();
std::cout << "LogThreader INFO: logging on thread id " << std::this_thread::get_id() << std::endl;
consoleMutex.unlock();
while(true){
bool canExit = !m_loggerRunning; // if logger is still running, no chance for exit
for(int i = 0; i < m_handledLoggers.size(); ++i){
// do one item per queue per iteration, so that every logger gets processed equally
int size = m_handledLoggers[i]->getQueueSize();
if(size > 0){
std::unique_ptr<LogEntry> entry = m_handledLoggers[i]->getQueueItem();
// wirte to console and/or file
m_handledLoggers[i]->print(move(entry));
size--;
}
if(size > 0) canExit = false; // if m_loggerRunning is false, then even if only one logger has some items in it's queue, a new iteration is needed
}
if(canExit){
break;
}
}
}
bool m_loggerRunning; // is set to true by constructor and to false by destructor; keeps logging() function running
std::thread m_thread; // logging thread: started in constructor, joined in destructor
std::vector<std::shared_ptr<Logger>> m_handledLoggers;
};
#endif