-
Notifications
You must be signed in to change notification settings - Fork 52
/
cpplog.hpp
1256 lines (1042 loc) · 40.2 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 <fstream>
#include <sstream>
#include <cstring>
#include <ctime>
#include <vector>
#include <cstdlib>
#include <streambuf>
#include <ostream>
// 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_SYSTEM_IDS
// Enables capturing of the Process and Thread ID.
//
// #define CPPLOG_USE_SYSCALL_FOR_THREAD_ID
// Tries to use syscall(SYS_gettid) to get the current Thread ID. This is
// especially useful on systems where boost's get_current_thread_id()
// will return a structure (usually pthread_t), which isn't incredibly
// useful.
// NOTE: Only useful if you also #define CPPLOG_SYSTEM_IDS
//
// #define CPPLOG_THREADING
// Enables threading (BackgroundLogger). Note that defining this or
// CPPLOG_SYSTEM_IDS introduces a dependency on Boost;
// this means that the library is no longer truly header-only.
//
// #define CPPLOG_HELPER_MACROS
// Enables inclusion of the CHECK_* macros.
//
// #define CPPLOG_FATAL_EXIT
// Causes a fatal error to exit() the process.
//
// #define CPPLOG_FATAL_EXIT_DEBUG
// Causes a fatal error to exit() the process if in debug mode.
//
// # define CPPLOG_USE_OLD_BOOST
// Use the old Boost namespace for interprocess::ipcdetail. Define
// this if you're using version 1.47 of Boost or earlier.
// ------------------------------- 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
// ------------------------------ CONFIGURATION ------------------------------
//#define CPPLOG_FILTER_LEVEL LL_WARN
//#define CPPLOG_SYSTEM_IDS
//#define CPPLOG_USE_SYSCALL_FOR_THREAD_ID
//#define CPPLOG_THREADING
#define CPPLOG_HELPER_MACROS
#define CPPLOG_FATAL_EXIT
//#define CPPLOG_FATAL_EXIT_DEBUG
//#define CPPLOG_USE_OLD_BOOST
// ---------------------------------- CODE -----------------------------------
#ifdef CPPLOG_SYSTEM_IDS
#include <boost/interprocess/detail/os_thread_functions.hpp>
#ifdef CPPLOG_USE_SYSCALL_FOR_THREAD_ID
#include <unistd.h>
#include <sys/syscall.h>
#endif
#endif
#ifdef CPPLOG_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
// We don't have support for this in older versions of C++
#if __cplusplus >= 201103L
#define CPPLOG_NOEXCEPT_FALSE noexcept(false)
#else
#define CPPLOG_NOEXCEPT_FALSE
#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
}
// Below we have a bunch of macros, typedefs and such that make getting our
// current process/thread ID simpler.
#ifdef CPPLOG_SYSTEM_IDS
#ifdef CPPLOG_USE_OLD_BOOST
typedef boost::interprocess::detail::OS_process_id_t process_id_t;
inline process_id_t get_process_id()
{
return boost::interprocess::detail::get_current_process_id();
}
#else
typedef boost::interprocess::ipcdetail::OS_process_id_t process_id_t;
inline process_id_t get_process_id()
{
return boost::interprocess::ipcdetail::get_current_process_id();
}
#endif
#ifdef CPPLOG_USE_SYSCALL_FOR_THREAD_ID
typedef unsigned long thread_id_t;
inline thread_id_t get_thread_id()
{
return static_cast<unsigned long>(syscall(SYS_gettid));
}
inline void print_thread_id(std::ostream& stream, thread_id_t thread_id)
{
stream << std::setfill('0') << std::setw(8) << std::hex
<< thread_id;
}
#else // CPPLOG_USE_SYSCALL_FOR_THREAD_ID
#ifdef CPPLOG_USE_OLD_BOOST
typedef boost::interprocess::detail::OS_thread_id_t thread_id_t;
inline thread_id_t get_thread_id()
{
return boost::interprocess::detail::get_current_thread_id();
}
#else
typedef boost::interprocess::ipcdetail::OS_thread_id_t thread_id_t;
inline thread_id_t get_thread_id()
{
return boost::interprocess::ipcdetail::get_current_thread_id();
}
#endif // CPPLOG_USE_OLD_BOOST
// This function lets us print a thread ID in all cases, including on
// platforms where it's actually a structure (pthread_t, I'm looking
// at you...). Note that this kinda-sorta assumes a little-endian
// architecture, if we want meaningful results. Not super important,
// though, since the address of a structure isn't actually that useful.
// TODO: I might rewrite this using templates to print properly if it's
// an unsigned long, and fall back to this implementation otherwise.
inline void print_thread_id(std::ostream& stream, thread_id_t thread_id)
{
unsigned char* sptr = static_cast<unsigned char*>(
static_cast<void*>(&thread_id)
);
for( size_t i = sizeof(thread_id_t); i != 0; i-- )
{
stream << std::setfill('0') << std::setw(2) << std::hex
<< static_cast<unsigned>(sptr[i - 1]);
}
}
#endif // CPPLOG_USE_SYSCALL_FOR_THREAD_ID
#endif // CPPLOG_SYSTEM_IDS
// Simple class that allows us to evaluate a stream to void - prevents compiler errors.
class VoidStreamClass
{
public:
VoidStreamClass() { }
void operator&(std::ostream&) { }
};
// fixed_streambuf is a minimal implementation around std::basic_streambuf
// with a fixed size backing buffer. It implements additional functionality
// needed by cpplog and exposes the backing buffer in a safe way via c_str().
// This makes it possible to avoid extra copying.
class fixed_streambuf : public std::basic_streambuf<char, std::char_traits<char> >
{
private:
// Constant.
static const size_t k_logBufferCapacity = 20000;
// Leave room for terminating null character in case buffer fills up.
char m_buffer[k_logBufferCapacity+1];
public:
fixed_streambuf()
{
// Use allocated buffer as backing store.
setp(m_buffer, m_buffer + k_logBufferCapacity);
// Insert terminator at buffer end.
m_buffer[k_logBufferCapacity] = '\0';
}
std::streamsize length() const { return pptr() - pbase(); }
std::streamsize capacity() const { return k_logBufferCapacity; }
bool empty() const { return length() == 0; }
bool full() const { return length() == capacity(); }
// Unput one character.
int_type sunputc()
{
if( (!pptr()) || (pptr() == pbase()) )
return pbackfail();
pbump(-1);
// This is safe because *epptr() always is '\0' and inside
// the backing buffer.
return traits_type::to_int_type(*(pptr()+1));
}
// Peek at last inserted character.
int peek() const
{
if( (!pptr()) || (pptr() == pbase()) )
return std::char_traits<char>::eof();
return static_cast<int>(*(pptr()-1));
}
const char* c_str() const
{
// Add terminating null character.
// This is safe even if the buffer is full to its capacity since
// epptr() is inside the backing buffer.
*pptr() = '\0';
return pbase();
}
};
}
// Logger data. This is sent to a logger when a LogMessage is Flush()'ed, or
// when the destructor is called.
struct LogData
{
// Our streambuf & stream to log data to.
helpers::fixed_streambuf streamBuffer;
std::ostream stream;
// Captured data.
unsigned int level;
unsigned long line;
const char* fullPath;
const char* fileName;
time_t messageTime;
::tm utcTime;
#ifdef CPPLOG_SYSTEM_IDS
// Process/thread ID.
helpers::process_id_t processId;
helpers::thread_id_t threadId;
#endif
// Constructor that initializes our stream.
LogData(loglevel_t logLevel)
: streamBuffer(), stream(&streamBuffer), level(logLevel)
#ifdef CPPLOG_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;
bool m_flushed;
bool m_deleteMessage;
protected:
LogData* m_logData;
private:
// 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, bool useDefaultLogFormat=true)
: m_logger(outputLogger)
{
Init(file, line, logLevel, useDefaultLogFormat);
}
LogMessage(const char* file, unsigned int line, loglevel_t logLevel, BaseLogger& outputLogger, bool useDefaultLogFormat=true)
: m_logger(&outputLogger)
{
Init(file, line, logLevel, useDefaultLogFormat);
}
virtual ~LogMessage() CPPLOG_NOEXCEPT_FALSE
{
Flush();
if( m_deleteMessage )
{
delete m_logData;
}
}
inline std::ostream& getStream()
{
return m_logData->stream;
}
protected:
virtual void InitLogMessage()
{
// Log process ID and thread ID.
#ifdef CPPLOG_SYSTEM_IDS
m_logData->stream << "["
<< std::right << std::setfill('0') << std::setw(8) << std::hex
<< m_logData->processId << ".";
helpers::print_thread_id(m_logData->stream, m_logData->threadId);
m_logData->stream << "] ";
#endif
m_logData->stream << std::setfill(' ') << std::setw(5) << std::left << std::dec
<< LogMessage::getLevelName(m_logData->level) << " - "
<< m_logData->fileName << "(" << m_logData->line << "): ";
}
private:
void Init(const char* file, unsigned int line, loglevel_t logLevel, bool useDefaultLogFormat=true)
{
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;
cpplog::helpers::sgmtime(&gmt, &m_logData->messageTime);
memcpy(&m_logData->utcTime, &gmt, sizeof(tm));
#ifdef CPPLOG_SYSTEM_IDS
// Get process/thread ID.
m_logData->processId = helpers::get_process_id();
m_logData->threadId = helpers::get_thread_id();
#endif // CPPLOG_SYSTEM_IDS
if( useDefaultLogFormat )
{
InitLogMessage();
}
}
void Flush()
{
if( !m_flushed )
{
// Insert newline, if needed.
helpers::fixed_streambuf* const sb = &m_logData->streamBuffer;
if( sb->peek() != '\n' )
{
// If buffer is full, remove last char to leave room for newline.
if( sb->full() )
sb->sunputc();
// Insert newline
sb->sputc('\n');
}
// 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_EXIT_DEBUG is set.
#if defined(CPPLOG_FATAL_EXIT_DEBUG) || defined(CPPLOG_FATAL_EXIT)
std::exit(1);
#endif
#else //!_DEBUG
#ifdef CPPLOG_FATAL_EXIT_DEBUG
std::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
{
protected:
std::ostream& m_logStream;
public:
OstreamLogger(std::ostream& outStream)
: m_logStream(outStream)
{ }
virtual bool sendLogMessage(LogData* logData)
{
helpers::fixed_streambuf* const sb = &logData->streamBuffer;
m_logStream.write(sb->c_str(), sb->length());
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:
std::streamoff m_maxSize;
unsigned long m_logNumber;
SizeRotateFileLogger::pfBuildFileName m_buildFunc;
void* m_context;
std::ofstream m_outStream;
public:
SizeRotateFileLogger(pfBuildFileName nameFunc, std::streamoff 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,
std::streamoff 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);
unsigned long timeDiff = static_cast<unsigned long>(
difftime(currTime, m_lastRotateTime)
);
// Is the difference greater than our number of seconds?
if( timeDiff > 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;
}
void SetLevel(loglevel_t allowed)
{
m_lowestLevelAllowed = allowed;
}
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.
#ifdef CPPLOG_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);