forked from andrew-d/cpplog
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cpplog.hpp
1088 lines (894 loc) · 28.8 KB
/
cpplog.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
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
#ifndef _CPPLOG_H
#define _CPPLOG_H
#include <iostream>
#include <iomanip>
#include <string>
#include <strstream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <ctime>
#include <vector>
// The following #define's will change the behaviour of this library.
// #define CPPLOG_FILTER_LEVEL <level>
// Prevents all log messages with level less than <level> from being emitted.
//
// #define CPPLOG_NO_SYSTEM_IDS
// Disables capturing of the Process and Thread ID.
//
// #define CPPLOG_NO_THREADING
// Disables threading (BackgroundLogger). Note that defining this and
// CPPLOG_NO_SYSTEM_IDS means that the library is truly header-only,
// as it no longer depends on Boost.
//
// #define CPPLOG_NO_HELPER_MACROS
// Disables inclusion of the CHECK_* macros.
//
// #define CPPLOG_FATAL_NOEXIT
// Causes a fatal error to not exit() the process.
//
// #define CPPLOG_FATAL_NOEXIT_DEBUG
// As above, but only in debug mode.
// Note: Defined below by default.
// ------------------------------- DEFINITIONS -------------------------------
// Severity levels:
// Note: Giving a value for CPPLOG_FILTER_LEVEL will log all messages at
// or above that level.
// 0 - Trace
// 1 - Debug
// 2 - Info
// 3 - Warning
// 4 - Error
// 5 - Fatal (always logged)
#define LL_TRACE 0
#define LL_DEBUG 1
#define LL_INFO 2
#define LL_WARN 3
#define LL_ERROR 4
#define LL_FATAL 5
#ifndef CPPLOG_NO_THREADING
#define CPPLOG_NO_THREADING
#endif
#ifndef CPPLOG_NO_SYSTEM_IDS
#define CPPLOG_NO_SYSTEM_IDS
#endif
#ifndef CPPLOG_FATAL_NOEXIT
#define CPPLOG_FATAL_NOEXIT
#endif
#define CPPLOG_FILTER_LEVEL LL_WARN
// ------------------------------ CONFIGURATION ------------------------------
//#define CPPLOG_FILTER_LEVEL LL_WARN
//#define CPPLOG_NO_SYSTEM_IDS
//#define CPPLOG_NO_THREADING
//#define CPPLOG_NO_HELPER_MACROS
//#define CPPLOG_FATAL_NOEXIT
#define CPPLOG_FATAL_NOEXIT_DEBUG
// ---------------------------------- CODE -----------------------------------
#ifndef CPPLOG_NO_SYSTEM_IDS
#include <boost/interprocess/detail/os_thread_functions.hpp>
#endif
#ifndef CPPLOG_NO_THREADING
#include <boost/thread.hpp>
#include "concurrent_queue.hpp"
#endif
#ifdef _WIN32
#include "outputdebugstream.hpp"
#endif
#ifdef CPPLOG_WITH_SCRIBE_LOGGER
#include "scribestream.hpp"
#endif
// If we don't have a level defined, set it to CPPLOG_LEVEL_DEBUG (log all except trace statements)
#ifndef CPPLOG_FILTER_LEVEL
#define CPPLOG_FILTER_LEVEL LL_DEBUG
#endif
// The general concept for how logging works:
// - Every call to LOG(LEVEL, logger) works as follows:
// - Instantiates an object of type LogMessage.
// - LogMessage's constructor captures __FILE__, __LINE__, severity and our output logger.
// - LogMessage exposes a function getStream(), which is an ostringstream-style stream that
// client code can write debug information into.
// - When the sendToLogger() method of a LogMessage is called, all the buffered data in the
// messages' stream is sent to the specified logger.
// - When a LogMessage's destructor is called, it calls sendToLogger() to send all
// remaining data.
namespace cpplog
{
// Our log level type.
// NOTE: When C++11 becomes widely supported, convert this to "enum class LogLevel".
typedef unsigned int loglevel_t;
// Helper functions. Stuck these in their own namespace for simplicity.
namespace helpers
{
// Gets the filename from a path.
inline static const char* fileNameFromPath(const char* filePath)
{
const char* fileName = strrchr(filePath, '/');
#if defined(_WIN32)
if( !fileName )
fileName = strrchr(filePath, '\\');
#endif
return fileName ? fileName + 1 : filePath;
}
// Thread-safe version of localtime()
inline bool slocaltime(::tm* const out, const ::time_t* const in)
{
#if defined(_WIN32) && defined(_MSC_VER)
return ::localtime_s(out, in) == 0;
#elif defined(__MINGW32__)
// Warning - not entirely thread safe on MinGW
::tm * localOut = ::localtime(in);
if( localOut )
{
::memcpy(out, localOut, sizeof(::tm));
}
return localOut != NULL;
#else
// Default to SUSv2 (libc >= 5.2.5) function.
return ::localtime_r(in, out) != NULL;
#endif
}
// Thread-safe version of gmtime()
inline bool sgmtime(::tm* const out, const ::time_t* const in)
{
#if defined(_WIN32) && defined(_MSC_VER)
return ::gmtime_s(out, in) == 0;
#elif defined(__MINGW32__)
// Warning - not entirely thread safe on MinGW
::tm * localOut = ::gmtime(in);
if( localOut )
{
::memcpy(out, localOut, sizeof(::tm));
}
return localOut != NULL;
#else
// Default to SUSv2 (libc >= 5.2.5) function.
return ::gmtime_r(in, out) != NULL;
#endif
}
// Simple class that allows us to evaluate a stream to void - prevents compiler errors.
class VoidStreamClass
{
public:
VoidStreamClass() { }
void operator&(std::ostream&) { }
};
};
// Logger data. This is sent to a logger when a LogMessage is Flush()'ed, or
// when the destructor is called.
struct LogData
{
// Constant.
static const size_t k_logBufferSize = 20000;
// Our stream to log data to.
std::ostrstream stream;
// Captured data.
unsigned int level;
unsigned long line;
const char* fullPath;
const char* fileName;
time_t messageTime;
::tm utcTime;
#ifndef CPPLOG_NO_SYSTEM_IDS
// Process/thread ID.
unsigned long processId;
unsigned long threadId;
#endif //CPPLOG_NO_SYSTEM_IDS
// Buffer for our text.
char buffer[k_logBufferSize];
// Constructor that initializes our stream.
LogData(loglevel_t logLevel)
: stream(buffer, k_logBufferSize), level(logLevel)
#ifndef CPPLOG_NO_SYSTEM_IDS
, processId(0), threadId(0)
#endif
{
}
virtual ~LogData()
{ }
};
// Base interface for a logger.
class BaseLogger
{
public:
// All loggers must provide an interface to log a message to.
// The return value of this function indicates whether to delete
// the log message.
virtual bool sendLogMessage(LogData* logData) = 0;
virtual ~BaseLogger() { }
};
// Log message - this is instantiated upon every call to LOG(logger)
class LogMessage
{
private:
BaseLogger* m_logger;
LogData* m_logData;
bool m_flushed;
bool m_deleteMessage;
// Flag for if a fatal message has been logged already.
// This prevents us from calling exit(), which calls something,
// which then logs a fatal message, which cause an infinite loop.
// TODO: this should probably be thread-safe...
static bool getSetFatal(bool get, bool val)
{
static bool m_fatalFlag = false;
if( !get )
m_fatalFlag = val;
return m_fatalFlag;
}
public:
LogMessage(const char* file, unsigned int line, loglevel_t logLevel, BaseLogger* outputLogger)
: m_logger(outputLogger)
{
Init(file, line, logLevel);
}
LogMessage(const char* file, unsigned int line, loglevel_t logLevel, BaseLogger& outputLogger)
: m_logger(&outputLogger)
{
Init(file, line, logLevel);
}
virtual ~LogMessage()
{
Flush();
if( m_deleteMessage )
{
delete m_logData;
}
}
inline std::ostream& getStream()
{
return m_logData->stream;
}
private:
void Init(const char* file, unsigned int line, loglevel_t logLevel)
{
m_logData = new LogData(logLevel);
m_flushed = false;
m_deleteMessage = false;
// Capture data.
m_logData->fullPath = file;
m_logData->fileName = cpplog::helpers::fileNameFromPath(file);
m_logData->line = line;
m_logData->messageTime = ::time(NULL);
// Get current time.
::tm* gmt = ::gmtime(&m_logData->messageTime);
memcpy(&m_logData->utcTime, gmt, sizeof(tm));
#ifndef CPPLOG_NO_SYSTEM_IDS
// Get process/thread ID.
m_logData->processId = boost::interprocess::detail::get_current_process_id();
m_logData->threadId = (unsigned long)boost::interprocess::detail::get_current_thread_id();
#endif
InitLogMessage();
}
void InitLogMessage()
{
// Log process ID and thread ID.
#ifndef CPPLOG_NO_SYSTEM_IDS
m_logData->stream << "["
<< std::right << std::setfill('0') << std::setw(8) << std::hex
<< m_logData->processId << "."
<< std::setfill('0') << std::setw(8) << std::hex
<< m_logData->threadId << "] ";
#endif
m_logData->stream << std::setfill(' ') << std::setw(5) << std::left << std::dec
<< LogMessage::getLevelName(m_logData->level) << " - "
<< m_logData->fileName << "(" << m_logData->line << "): ";
}
void Flush()
{
if( !m_flushed )
{
// Check if we have a newline.
char lastChar = m_logData->buffer[m_logData->stream.pcount() - 1];
if( lastChar != '\n' )
m_logData->stream << std::endl;
// Null-terminate.
m_logData->stream << '\0';
// Save the log level.
loglevel_t savedLogLevel = m_logData->level;
// Send the message, set flushed=true.
m_deleteMessage = m_logger->sendLogMessage(m_logData);
m_flushed = true;
// Note: We cannot touch m_logData after the above call. By the
// time it returns, we have to assume it has already been freed.
// If this is a fatal message...
if( savedLogLevel == LL_FATAL && !getSetFatal(true, true) )
{
// Set our fatal flag.
getSetFatal(false, true);
#ifdef _DEBUG
// Only exit in debug mode if CPPLOG_FATAL_NOEXIT_DEBUG is not set.
#if !defined(CPPLOG_FATAL_NOEXIT_DEBUG) && !defined(CPPLOG_FATAL_NOEXIT)
::exit(1);
#endif
#else //!_DEBUG
#if !defined(CPPLOG_FATAL_NOEXIT_DEBUG)
::exit(1)
#endif
#endif
}
}
}
public:
static const char* getLevelName(loglevel_t level)
{
switch( level )
{
case LL_TRACE:
return "TRACE";
case LL_DEBUG:
return "DEBUG";
case LL_INFO:
return "INFO";
case LL_WARN:
return "WARN";
case LL_ERROR:
return "ERROR";
case LL_FATAL:
return "FATAL";
default:
return "OTHER";
};
};
};
// Generic class - logs to a given std::ostream.
class OstreamLogger : public BaseLogger
{
private:
std::ostream& m_logStream;
public:
OstreamLogger(std::ostream& outStream)
: m_logStream(outStream)
{ }
virtual bool sendLogMessage(LogData* logData)
{
m_logStream << logData->buffer;
m_logStream << std::flush;
return true;
}
virtual ~OstreamLogger() { }
};
// Simple implementation - logs to stderr.
class StdErrLogger : public OstreamLogger
{
public:
StdErrLogger()
: OstreamLogger(std::cerr)
{ }
};
// Simple implementation - logs to a string, provides the ability to get that string.
class StringLogger : public OstreamLogger
{
private:
std::ostringstream m_stream;
public:
StringLogger()
: OstreamLogger(m_stream)
{ }
std::string getString()
{
return m_stream.str();
}
void clear()
{
m_stream.str("");
m_stream.clear();
}
};
#ifdef _WIN32
class OutputDebugStringLogger : public OstreamLogger
{
private:
dbgwin_stream m_stream;
public:
OutputDebugStringLogger() : OstreamLogger(m_stream)
{ }
};
#endif
// Log to file.
class FileLogger : public OstreamLogger
{
private:
std::string m_path;
std::ofstream m_outStream;
public:
FileLogger(std::string logFilePath)
: OstreamLogger(m_outStream), m_path(logFilePath), m_outStream(logFilePath.c_str(), std::ios_base::out)
{
}
FileLogger(std::string logFilePath, bool append)
: OstreamLogger(m_outStream), m_path(logFilePath), m_outStream(logFilePath.c_str(), append ? std::ios_base::app : std::ios_base::out)
{
}
};
// Log to file, rotate when the log reaches a given size.
class SizeRotateFileLogger : public OstreamLogger
{
public:
typedef void (*pfBuildFileName)(unsigned long logNumber, std::string& newFileName, void* context);
private:
size_t m_maxSize;
unsigned long m_logNumber;
SizeRotateFileLogger::pfBuildFileName m_buildFunc;
void* m_context;
std::ofstream m_outStream;
public:
SizeRotateFileLogger(pfBuildFileName nameFunc, size_t maxSize)
: OstreamLogger(m_outStream), m_maxSize(maxSize), m_logNumber(0),
m_buildFunc(nameFunc), m_context(NULL),
m_outStream()
{
// "Rotate" to open our initial log.
RotateLog();
}
SizeRotateFileLogger(pfBuildFileName nameFunc, void* context, size_t maxSize)
: OstreamLogger(m_outStream), m_maxSize(maxSize), m_logNumber(0),
m_buildFunc(nameFunc), m_context(context),
m_outStream()
{
// "Rotate" to open our initial log.
RotateLog();
}
virtual ~SizeRotateFileLogger()
{ }
virtual bool sendLogMessage(LogData* logData)
{
// Call the actual logger.
bool deleteMessage = OstreamLogger::sendLogMessage(logData);
// Check if we're over our limit.
if( m_outStream.tellp() > m_maxSize )
{
// Yep, increment our log number and rotate.
m_logNumber++;
m_outStream << std::flush;
RotateLog();
}
return deleteMessage;
}
private:
void RotateLog()
{
// Build the file name.
std::string newFileName;
m_buildFunc(m_logNumber, newFileName, m_context);
// Close old file, open new file.
m_outStream.close();
m_outStream.open(newFileName.c_str(), std::ios_base::out);
}
};
// Log to file, rotate every "x" seconds.
class TimeRotateFileLogger : public OstreamLogger
{
public:
typedef void (*pfBuildFileName)(::tm* time, unsigned long logNumber,
std::string& newFileName, void* context);
private:
unsigned long m_rotateInterval;
::time_t m_lastRotateTime;
unsigned long m_logNumber;
cpplog::TimeRotateFileLogger::pfBuildFileName m_buildFunc;
void* m_context;
std::ofstream m_outStream;
public:
TimeRotateFileLogger(pfBuildFileName nameFunc, unsigned long intervalSeconds)
: OstreamLogger(m_outStream), m_rotateInterval(intervalSeconds), m_logNumber(0),
m_buildFunc(nameFunc), m_context(NULL)
{
// "Rotate" to open our initial log.
RotateLog(::time(NULL));
}
TimeRotateFileLogger(pfBuildFileName nameFunc, void* context, unsigned long intervalSeconds)
: OstreamLogger(m_outStream), m_rotateInterval(intervalSeconds), m_logNumber(0),
m_buildFunc(nameFunc), m_context(context)
{
// "Rotate" to open our initial log.
RotateLog(::time(NULL));
}
virtual ~TimeRotateFileLogger()
{
}
virtual bool sendLogMessage(LogData* logData)
{
// Get the current time.
::time_t currTime;
::time(&currTime);
// Is the difference greater than our number of seconds?
if( (unsigned long)difftime(currTime, m_lastRotateTime) > m_rotateInterval )
{
// Yep, increment our log number and rotate.
m_logNumber++;
m_outStream << std::flush;
RotateLog(currTime);
}
// Call the actual logger.
return OstreamLogger::sendLogMessage(logData);
}
private:
void RotateLog(time_t currTime)
{
// Get the current time.
::tm timeInfo;
cpplog::helpers::slocaltime(&timeInfo, &currTime);
// Build a new file name.
std::string newFileName;
m_buildFunc(&timeInfo, m_logNumber, newFileName, m_context);
// Close old file, open new file.
m_outStream.close();
m_outStream.open(newFileName.c_str(), std::ios_base::out);
// Reset the rotate time.
::time(&m_lastRotateTime);
}
};
#ifdef CPPLOG_WITH_SCRIBE_LOGGER
// Given a Scribe node, will send log messages there with the given category.
class ScribeLogger : public OstreamLogger
{
private:
scribe_stream m_outStream;
public:
ScribeLogger(std::string host, unsigned short port, std::string category, int timeout)
: OstreamLogger(m_outStream)
{
m_outStream.open(host, port, category, timeout);
}
};
#endif
// Tee logger - given two loggers, will forward a message to both.
class TeeLogger : public BaseLogger
{
private:
BaseLogger* m_logger1;
BaseLogger* m_logger2;
bool m_logger1Owned;
bool m_logger2Owned;
public:
TeeLogger(BaseLogger* one, BaseLogger* two)
: m_logger1(one), m_logger2(two),
m_logger1Owned(false), m_logger2Owned(false)
{ }
TeeLogger(BaseLogger* one, bool ownOne, BaseLogger* two, bool ownTwo)
: m_logger1(one), m_logger2(two),
m_logger1Owned(ownOne), m_logger2Owned(ownTwo)
{ }
TeeLogger(BaseLogger& one, BaseLogger& two)
: m_logger1(&one), m_logger2(&two),
m_logger1Owned(false), m_logger2Owned(false)
{ }
TeeLogger(BaseLogger& one, bool ownOne, BaseLogger& two, bool ownTwo)
: m_logger1(&one), m_logger2(&two),
m_logger1Owned(ownOne), m_logger2Owned(ownTwo)
{ }
~TeeLogger()
{
if( m_logger1Owned )
delete m_logger1;
if( m_logger2Owned )
delete m_logger2;
}
virtual bool sendLogMessage(LogData* logData)
{
bool deleteMessage = true;
deleteMessage = deleteMessage && m_logger1->sendLogMessage(logData);
deleteMessage = deleteMessage && m_logger2->sendLogMessage(logData);
return deleteMessage;
}
};
// Multiplex logger - will forward a log message to all loggers.
class MultiplexLogger : public BaseLogger
{
struct LoggerInfo
{
BaseLogger* logger;
bool owned;
LoggerInfo(BaseLogger* l, bool o)
: logger(l), owned(o)
{ }
};
std::vector<LoggerInfo> m_loggers;
public:
MultiplexLogger()
{ }
MultiplexLogger(BaseLogger* one)
{
m_loggers.push_back(LoggerInfo(one, false));
}
MultiplexLogger(BaseLogger& one)
{
m_loggers.push_back(LoggerInfo(&one, false));
}
MultiplexLogger(BaseLogger* one, bool owned)
{
m_loggers.push_back(LoggerInfo(one, owned));
}
MultiplexLogger(BaseLogger& one, bool owned)
{
m_loggers.push_back(LoggerInfo(&one, owned));
}
MultiplexLogger(BaseLogger* one, BaseLogger* two)
{
m_loggers.push_back(LoggerInfo(one, false));
m_loggers.push_back(LoggerInfo(two, false));
}
MultiplexLogger(BaseLogger* one, bool ownOne, BaseLogger* two, bool ownTwo)
{
m_loggers.push_back(LoggerInfo(one, ownOne));
m_loggers.push_back(LoggerInfo(two, ownTwo));
}
MultiplexLogger(BaseLogger& one, bool ownOne, BaseLogger& two, bool ownTwo)
{
m_loggers.push_back(LoggerInfo(&one, ownOne));
m_loggers.push_back(LoggerInfo(&two, ownTwo));
}
~MultiplexLogger()
{
for( std::vector<LoggerInfo>::iterator It = m_loggers.begin();
It != m_loggers.end();
It++ )
{
if( (*It).owned )
delete (*It).logger;
}
}
void addLogger(BaseLogger* logger) { m_loggers.push_back(LoggerInfo(logger, false)); }
void addLogger(BaseLogger& logger) { m_loggers.push_back(LoggerInfo(&logger, false)); }
void addLogger(BaseLogger* logger, bool owned) { m_loggers.push_back(LoggerInfo(logger, owned)); }
void addLogger(BaseLogger& logger, bool owned) { m_loggers.push_back(LoggerInfo(&logger, owned)); }
virtual bool sendLogMessage(LogData* logData)
{
bool deleteMessage = true;
for( std::vector<LoggerInfo>::iterator It = m_loggers.begin();
It != m_loggers.end();
It++ )
{
deleteMessage = deleteMessage && (*It).logger->sendLogMessage(logData);
}
return deleteMessage;
}
};
// Filtering logger. Will not forward all messages less than a given level.
class FilteringLogger : public BaseLogger
{
private:
loglevel_t m_lowestLevelAllowed;
BaseLogger* m_forwardTo;
bool m_owned;
public:
FilteringLogger(loglevel_t level, BaseLogger* forwardTo)
: m_lowestLevelAllowed(level), m_forwardTo(forwardTo), m_owned(false)
{ }
FilteringLogger(loglevel_t level, BaseLogger& forwardTo)
: m_lowestLevelAllowed(level), m_forwardTo(&forwardTo), m_owned(false)
{ }
FilteringLogger(loglevel_t level, BaseLogger* forwardTo, bool owned)
: m_lowestLevelAllowed(level), m_forwardTo(forwardTo), m_owned(owned)
{ }
FilteringLogger(loglevel_t level, BaseLogger& forwardTo, bool owned)
: m_lowestLevelAllowed(level), m_forwardTo(&forwardTo), m_owned(owned)
{ }
~FilteringLogger()
{
if( m_owned )
delete m_forwardTo;
}
virtual bool sendLogMessage(LogData* logData)
{
if( logData->level >= m_lowestLevelAllowed )
return m_forwardTo->sendLogMessage(logData);
else
return true;
}
};
// Logger that moves all processing of log messages to a background thread.
// Only include if we have support for threading.
#ifndef CPPLOG_NO_THREADING
class BackgroundLogger : public BaseLogger
{
private:
BaseLogger* m_forwardTo;
concurrent_queue<LogData*> m_queue;
boost::thread m_backgroundThread;
LogData* m_dummyItem;
void backgroundFunction()
{
LogData* nextLogEntry;
bool deleteMessage = true;
do
{
m_queue.wait_and_pop(nextLogEntry);
if( nextLogEntry != m_dummyItem )
deleteMessage = m_forwardTo->sendLogMessage(nextLogEntry);
if( deleteMessage )
delete nextLogEntry;
} while( nextLogEntry != m_dummyItem );
}
void Init()
{
// Create dummy item.
m_dummyItem = new LogData(LL_TRACE);
// And create background thread.
m_backgroundThread = boost::thread(&BackgroundLogger::backgroundFunction, this);
}
public:
BackgroundLogger(BaseLogger* forwardTo)
: m_forwardTo(forwardTo)
{
Init();
}
BackgroundLogger(BaseLogger& forwardTo)
: m_forwardTo(&forwardTo)
{
Init();
}
~BackgroundLogger()
{
// Push our "dummy" item on the queue ...
m_queue.push(m_dummyItem);
// ... and wait for thread to terminate.
m_backgroundThread.join();
// NOTE: The loop will free the dummy item for us, we can ignore it.
}
virtual bool sendLogMessage(LogData* logData)
{
m_queue.push(logData);
// Don't delete - the background thread should handle this.
return false;
}
};
#endif //CPPLOG_NO_THREADING
// Seperate namespace for loggers that use templates.
namespace templated
{
// Filtering logger that accepts the level as a template parameter.
// This will be slightly faster at runtime, as the if statement will
// be performed on a constant value, as opposed to needing a memory
// lookup (as with FilteringLogger)
template <loglevel_t lowestLevel = LL_TRACE>
class TFilteringLogger : public BaseLogger
{
BaseLogger* m_forwardTo;
public:
TFilteringLogger(BaseLogger* forwardTo)
: m_forwardTo(forwardTo)
{ }
virtual bool sendLogMessage(LogData* logData)
{
if( logData->level >= lowestLevel )
return m_forwardTo->sendLogMessage(logData);
else
return true;
}
};
// TODO: Implement others?
};
};
// Our logging macros.
// Default macros - log, and don't log something.
#define LOG_LEVEL(level, logger) cpplog::LogMessage(__FILE__, __LINE__, (level), logger).getStream()
#define LOG_NOTHING(level, logger) true ? (void)0 : cpplog::helpers::VoidStreamClass() & LOG_LEVEL(level, logger)
// Series of debug macros, depending on what we log.
#if CPPLOG_FILTER_LEVEL <= LL_TRACE
#define LOG_TRACE(logger) LOG_LEVEL(LL_TRACE, logger)
#else
#define LOG_TRACE(logger) LOG_NOTHING(LL_TRACE, logger)
#endif
#if CPPLOG_FILTER_LEVEL <= LL_DEBUG
#define LOG_DEBUG(logger) LOG_LEVEL(LL_DEBUG, logger)
#else
#define LOG_DEBUG(logger) LOG_NOTHING(LL_DEBUG, logger)
#endif
#if CPPLOG_FILTER_LEVEL <= LL_INFO
#define LOG_INFO(logger) LOG_LEVEL(LL_INFO, logger)
#else
#define LOG_INFO(logger) LOG_NOTHING(LL_INFO, logger)
#endif
#if CPPLOG_FILTER_LEVEL <= LL_WARN
#define LOG_WARN(logger) LOG_LEVEL(LL_WARN, logger)
#else
#define LOG_WARN(logger) LOG_NOTHING(LL_WARN, logger)
#endif
#if CPPLOG_FILTER_LEVEL <= LL_ERROR
#define LOG_ERROR(logger) LOG_LEVEL(LL_ERROR, logger)
#else
#define LOG_ERROR(logger) LOG_NOTHING(LL_ERROR, logger)
#endif
// Note: Always logged.
#define LOG_FATAL(logger) LOG_LEVEL(LL_FATAL, logger)
// Debug macros - only logged in debug mode.
#ifdef _DEBUG
#define DLOG_TRACE(logger) LOG_TRACE(logger)
#define DLOG_DEBUG(logger) LOG_DEBUG(logger)
#define DLOG_INFO(logger) LOG_INFO(logger)
#define DLOG_WARN(logger) LOG_WARN(logger)
#define DLOG_ERROR(logger) LOG_ERROR(logger)
#else
#define DLOG_TRACE(logger) LOG_NOTHING(LL_TRACE, logger)
#define DLOG_DEBUG(logger) LOG_NOTHING(LL_DEBUG, logger)
#define DLOG_INFO(logger) LOG_NOTHING(LL_INFO, logger)
#define DLOG_WARN(logger) LOG_NOTHING(LL_WARN, logger)
#define DLOG_ERROR(logger) LOG_NOTHING(LL_ERROR, logger)
#endif
// Note: Always logged.
#define DLOG_FATAL(logger) LOG_FATAL(logger)
// Aliases - so we can do:
// LOG(LL_FATAL, logger)
#define LOG_LL_TRACE(logger) LOG_TRACE(logger)
#define LOG_LL_DEBUG(logger) LOG_DEBUG(logger)
#define LOG_LL_INFO(logger) LOG_INFO(logger)
#define LOG_LL_WARN(logger) LOG_WARN(logger)
#define LOG_LL_ERROR(logger) LOG_ERROR(logger)
#define LOG_LL_FATAL(logger) LOG_FATAL(logger)
#define DLOG_LL_TRACE(logger) DLOG_TRACE(logger)
#define DLOG_LL_DEBUG(logger) DLOG_DEBUG(logger)
#define DLOG_LL_INFO(logger) DLOG_INFO(logger)
#define DLOG_LL_WARN(logger) DLOG_WARN(logger)
#define DLOG_LL_ERROR(logger) DLOG_ERROR(logger)
#define DLOG_LL_FATAL(logger) DLOG_FATAL(logger)
// Helper - if you want to do:
// LOG(LL_FATAL, logger)