-
Notifications
You must be signed in to change notification settings - Fork 0
/
easylogging++.cc
3120 lines (2847 loc) · 119 KB
/
easylogging++.cc
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
//
// Bismillah ar-Rahmaan ar-Raheem
//
// Easylogging++ v9.96.7
// Cross-platform logging library for C++ applications
//
// Copyright (c) 2012-2018 Amrayn Web Services
// Copyright (c) 2012-2018 @abumusamq
//
// This library is released under the MIT Licence.
// https://github.com/amrayn/easyloggingpp/blob/master/LICENSE
//
// https://amrayn.com
// http://muflihun.com
//
#include "easylogging++.h"
#if defined(AUTO_INITIALIZE_EASYLOGGINGPP)
INITIALIZE_EASYLOGGINGPP
#endif
namespace el {
// el::base
namespace base {
// el::base::consts
namespace consts {
// Level log values - These are values that are replaced in place of %level format specifier
// Extra spaces after format specifiers are only for readability purposes in log files
static const base::type::char_t* kInfoLevelLogValue = ELPP_LITERAL("INFO");
static const base::type::char_t* kDebugLevelLogValue = ELPP_LITERAL("DEBUG");
static const base::type::char_t* kWarningLevelLogValue = ELPP_LITERAL("WARNING");
static const base::type::char_t* kErrorLevelLogValue = ELPP_LITERAL("ERROR");
static const base::type::char_t* kFatalLevelLogValue = ELPP_LITERAL("FATAL");
static const base::type::char_t* kVerboseLevelLogValue =
ELPP_LITERAL("VERBOSE"); // will become VERBOSE-x where x = verbose level
static const base::type::char_t* kTraceLevelLogValue = ELPP_LITERAL("TRACE");
static const base::type::char_t* kInfoLevelShortLogValue = ELPP_LITERAL("I");
static const base::type::char_t* kDebugLevelShortLogValue = ELPP_LITERAL("D");
static const base::type::char_t* kWarningLevelShortLogValue = ELPP_LITERAL("W");
static const base::type::char_t* kErrorLevelShortLogValue = ELPP_LITERAL("E");
static const base::type::char_t* kFatalLevelShortLogValue = ELPP_LITERAL("F");
static const base::type::char_t* kVerboseLevelShortLogValue = ELPP_LITERAL("V");
static const base::type::char_t* kTraceLevelShortLogValue = ELPP_LITERAL("T");
// Format specifiers - These are used to define log format
static const base::type::char_t* kAppNameFormatSpecifier = ELPP_LITERAL("%app");
static const base::type::char_t* kLoggerIdFormatSpecifier = ELPP_LITERAL("%logger");
static const base::type::char_t* kThreadIdFormatSpecifier = ELPP_LITERAL("%thread");
static const base::type::char_t* kSeverityLevelFormatSpecifier = ELPP_LITERAL("%level");
static const base::type::char_t* kSeverityLevelShortFormatSpecifier = ELPP_LITERAL("%levshort");
static const base::type::char_t* kDateTimeFormatSpecifier = ELPP_LITERAL("%datetime");
static const base::type::char_t* kLogFileFormatSpecifier = ELPP_LITERAL("%file");
static const base::type::char_t* kLogFileBaseFormatSpecifier = ELPP_LITERAL("%fbase");
static const base::type::char_t* kLogLineFormatSpecifier = ELPP_LITERAL("%line");
static const base::type::char_t* kLogLocationFormatSpecifier = ELPP_LITERAL("%loc");
static const base::type::char_t* kLogFunctionFormatSpecifier = ELPP_LITERAL("%func");
static const base::type::char_t* kCurrentUserFormatSpecifier = ELPP_LITERAL("%user");
static const base::type::char_t* kCurrentHostFormatSpecifier = ELPP_LITERAL("%host");
static const base::type::char_t* kMessageFormatSpecifier = ELPP_LITERAL("%msg");
static const base::type::char_t* kVerboseLevelFormatSpecifier = ELPP_LITERAL("%vlevel");
static const char* kDateTimeFormatSpecifierForFilename = "%datetime";
// Date/time
static const char* kDays[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
static const char* kDaysAbbrev[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
static const char* kMonths[12] = { "January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"
};
static const char* kMonthsAbbrev[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
static const char* kDefaultDateTimeFormat = "%Y-%M-%d %H:%m:%s,%g";
static const char* kDefaultDateTimeFormatInFilename = "%Y-%M-%d_%H-%m";
static const int kYearBase = 1900;
static const char* kAm = "AM";
static const char* kPm = "PM";
// Miscellaneous constants
static const char* kNullPointer = "nullptr";
#if ELPP_VARIADIC_TEMPLATES_SUPPORTED
#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED
static const base::type::VerboseLevel kMaxVerboseLevel = 9;
static const char* kUnknownUser = "unknown-user";
static const char* kUnknownHost = "unknown-host";
//---------------- DEFAULT LOG FILE -----------------------
#if defined(ELPP_NO_DEFAULT_LOG_FILE)
# if ELPP_OS_UNIX
static const char* kDefaultLogFile = "/dev/null";
# elif ELPP_OS_WINDOWS
static const char* kDefaultLogFile = "nul";
# endif // ELPP_OS_UNIX
#elif defined(ELPP_DEFAULT_LOG_FILE)
static const char* kDefaultLogFile = ELPP_DEFAULT_LOG_FILE;
#else
static const char* kDefaultLogFile = "myeasylog.log";
#endif // defined(ELPP_NO_DEFAULT_LOG_FILE)
#if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)
static const char* kDefaultLogFileParam = "--default-log-file";
#endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)
#if defined(ELPP_LOGGING_FLAGS_FROM_ARG)
static const char* kLoggingFlagsParam = "--logging-flags";
#endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG)
static const char* kValidLoggerIdSymbols =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._";
static const char* kConfigurationComment = "##";
static const char* kConfigurationLevel = "*";
static const char* kConfigurationLoggerId = "--";
}
// el::base::utils
namespace utils {
/// @brief Aborts application due with user-defined status
static void abort(int status, const std::string& reason) {
// Both status and reason params are there for debugging with tools like gdb etc
ELPP_UNUSED(status);
ELPP_UNUSED(reason);
#if defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG)
// Ignore msvc critical error dialog - break instead (on debug mode)
_asm int 3
#else
::abort();
#endif // defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG)
}
} // namespace utils
} // namespace base
// el
// LevelHelper
const char* LevelHelper::convertToString(Level level) {
// Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet.
if (level == Level::Global) return "GLOBAL";
if (level == Level::Debug) return "DEBUG";
if (level == Level::Info) return "INFO";
if (level == Level::Warning) return "WARNING";
if (level == Level::Error) return "ERROR";
if (level == Level::Fatal) return "FATAL";
if (level == Level::Verbose) return "VERBOSE";
if (level == Level::Trace) return "TRACE";
return "UNKNOWN";
}
struct StringToLevelItem {
const char* levelString;
Level level;
};
static struct StringToLevelItem stringToLevelMap[] = {
{ "global", Level::Global },
{ "debug", Level::Debug },
{ "info", Level::Info },
{ "warning", Level::Warning },
{ "error", Level::Error },
{ "fatal", Level::Fatal },
{ "verbose", Level::Verbose },
{ "trace", Level::Trace }
};
Level LevelHelper::convertFromString(const char* levelStr) {
for (auto& item : stringToLevelMap) {
if (base::utils::Str::cStringCaseEq(levelStr, item.levelString)) {
return item.level;
}
}
return Level::Unknown;
}
void LevelHelper::forEachLevel(base::type::EnumType* startIndex, const std::function<bool(void)>& fn) {
base::type::EnumType lIndexMax = LevelHelper::kMaxValid;
do {
if (fn()) {
break;
}
*startIndex = static_cast<base::type::EnumType>(*startIndex << 1);
} while (*startIndex <= lIndexMax);
}
// ConfigurationTypeHelper
const char* ConfigurationTypeHelper::convertToString(ConfigurationType configurationType) {
// Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet.
if (configurationType == ConfigurationType::Enabled) return "ENABLED";
if (configurationType == ConfigurationType::Filename) return "FILENAME";
if (configurationType == ConfigurationType::Format) return "FORMAT";
if (configurationType == ConfigurationType::ToFile) return "TO_FILE";
if (configurationType == ConfigurationType::ToStandardOutput) return "TO_STANDARD_OUTPUT";
if (configurationType == ConfigurationType::SubsecondPrecision) return "SUBSECOND_PRECISION";
if (configurationType == ConfigurationType::PerformanceTracking) return "PERFORMANCE_TRACKING";
if (configurationType == ConfigurationType::MaxLogFileSize) return "MAX_LOG_FILE_SIZE";
if (configurationType == ConfigurationType::LogFlushThreshold) return "LOG_FLUSH_THRESHOLD";
return "UNKNOWN";
}
struct ConfigurationStringToTypeItem {
const char* configString;
ConfigurationType configType;
};
static struct ConfigurationStringToTypeItem configStringToTypeMap[] = {
{ "enabled", ConfigurationType::Enabled },
{ "to_file", ConfigurationType::ToFile },
{ "to_standard_output", ConfigurationType::ToStandardOutput },
{ "format", ConfigurationType::Format },
{ "filename", ConfigurationType::Filename },
{ "subsecond_precision", ConfigurationType::SubsecondPrecision },
{ "milliseconds_width", ConfigurationType::MillisecondsWidth },
{ "performance_tracking", ConfigurationType::PerformanceTracking },
{ "max_log_file_size", ConfigurationType::MaxLogFileSize },
{ "log_flush_threshold", ConfigurationType::LogFlushThreshold },
};
ConfigurationType ConfigurationTypeHelper::convertFromString(const char* configStr) {
for (auto& item : configStringToTypeMap) {
if (base::utils::Str::cStringCaseEq(configStr, item.configString)) {
return item.configType;
}
}
return ConfigurationType::Unknown;
}
void ConfigurationTypeHelper::forEachConfigType(base::type::EnumType* startIndex, const std::function<bool(void)>& fn) {
base::type::EnumType cIndexMax = ConfigurationTypeHelper::kMaxValid;
do {
if (fn()) {
break;
}
*startIndex = static_cast<base::type::EnumType>(*startIndex << 1);
} while (*startIndex <= cIndexMax);
}
// Configuration
Configuration::Configuration(const Configuration& c) :
m_level(c.m_level),
m_configurationType(c.m_configurationType),
m_value(c.m_value) {
}
Configuration& Configuration::operator=(const Configuration& c) {
if (&c != this) {
m_level = c.m_level;
m_configurationType = c.m_configurationType;
m_value = c.m_value;
}
return *this;
}
/// @brief Full constructor used to sets value of configuration
Configuration::Configuration(Level level, ConfigurationType configurationType, const std::string& value) :
m_level(level),
m_configurationType(configurationType),
m_value(value) {
}
void Configuration::log(el::base::type::ostream_t& os) const {
os << LevelHelper::convertToString(m_level)
<< ELPP_LITERAL(" ") << ConfigurationTypeHelper::convertToString(m_configurationType)
<< ELPP_LITERAL(" = ") << m_value.c_str();
}
/// @brief Used to find configuration from configuration (pointers) repository. Avoid using it.
Configuration::Predicate::Predicate(Level level, ConfigurationType configurationType) :
m_level(level),
m_configurationType(configurationType) {
}
bool Configuration::Predicate::operator()(const Configuration* conf) const {
return ((conf != nullptr) && (conf->level() == m_level) && (conf->configurationType() == m_configurationType));
}
// Configurations
Configurations::Configurations(void) :
m_configurationFile(std::string()),
m_isFromFile(false) {
}
Configurations::Configurations(const std::string& configurationFile, bool useDefaultsForRemaining,
Configurations* base) :
m_configurationFile(configurationFile),
m_isFromFile(false) {
parseFromFile(configurationFile, base);
if (useDefaultsForRemaining) {
setRemainingToDefault();
}
}
bool Configurations::parseFromFile(const std::string& configurationFile, Configurations* base) {
// We initial assertion with true because if we have assertion disabled, we want to pass this
// check and if assertion is enabled we will have values re-assigned any way.
bool assertionPassed = true;
ELPP_ASSERT((assertionPassed = base::utils::File::pathExists(configurationFile.c_str(), true)) == true,
"Configuration file [" << configurationFile << "] does not exist!");
if (!assertionPassed) {
return false;
}
bool success = Parser::parseFromFile(configurationFile, this, base);
m_isFromFile = success;
return success;
}
bool Configurations::parseFromText(const std::string& configurationsString, Configurations* base) {
bool success = Parser::parseFromText(configurationsString, this, base);
if (success) {
m_isFromFile = false;
}
return success;
}
void Configurations::setFromBase(Configurations* base) {
if (base == nullptr || base == this) {
return;
}
base::threading::ScopedLock scopedLock(base->lock());
for (Configuration*& conf : base->list()) {
set(conf);
}
}
bool Configurations::hasConfiguration(ConfigurationType configurationType) {
base::type::EnumType lIndex = LevelHelper::kMinValid;
bool result = false;
LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
if (hasConfiguration(LevelHelper::castFromInt(lIndex), configurationType)) {
result = true;
}
return result;
});
return result;
}
bool Configurations::hasConfiguration(Level level, ConfigurationType configurationType) {
base::threading::ScopedLock scopedLock(lock());
#if ELPP_COMPILER_INTEL
// We cant specify template types here, Intel C++ throws compilation error
// "error: type name is not allowed"
return RegistryWithPred::get(level, configurationType) != nullptr;
#else
return RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType) != nullptr;
#endif // ELPP_COMPILER_INTEL
}
void Configurations::set(Level level, ConfigurationType configurationType, const std::string& value) {
base::threading::ScopedLock scopedLock(lock());
unsafeSet(level, configurationType, value); // This is not unsafe anymore as we have locked mutex
if (level == Level::Global) {
unsafeSetGlobally(configurationType, value, false); // Again this is not unsafe either
}
}
void Configurations::set(Configuration* conf) {
if (conf == nullptr) {
return;
}
set(conf->level(), conf->configurationType(), conf->value());
}
void Configurations::setToDefault(void) {
setGlobally(ConfigurationType::Enabled, std::string("true"), true);
setGlobally(ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile), true);
#if defined(ELPP_NO_LOG_TO_FILE)
setGlobally(ConfigurationType::ToFile, std::string("false"), true);
#else
setGlobally(ConfigurationType::ToFile, std::string("true"), true);
#endif // defined(ELPP_NO_LOG_TO_FILE)
setGlobally(ConfigurationType::ToStandardOutput, std::string("true"), true);
setGlobally(ConfigurationType::SubsecondPrecision, std::string("3"), true);
setGlobally(ConfigurationType::PerformanceTracking, std::string("true"), true);
setGlobally(ConfigurationType::MaxLogFileSize, std::string("0"), true);
setGlobally(ConfigurationType::LogFlushThreshold, std::string("0"), true);
setGlobally(ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"), true);
set(Level::Debug, ConfigurationType::Format,
std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg"));
// INFO and WARNING are set to default by Level::Global
set(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
set(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
set(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg"));
set(Level::Trace, ConfigurationType::Format, std::string("%datetime %level [%logger] [%func] [%loc] %msg"));
}
void Configurations::setRemainingToDefault(void) {
base::threading::ScopedLock scopedLock(lock());
#if defined(ELPP_NO_LOG_TO_FILE)
unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("false"));
#else
unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("true"));
#endif // defined(ELPP_NO_LOG_TO_FILE)
unsafeSetIfNotExist(Level::Global, ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile));
unsafeSetIfNotExist(Level::Global, ConfigurationType::ToStandardOutput, std::string("true"));
unsafeSetIfNotExist(Level::Global, ConfigurationType::SubsecondPrecision, std::string("3"));
unsafeSetIfNotExist(Level::Global, ConfigurationType::PerformanceTracking, std::string("true"));
unsafeSetIfNotExist(Level::Global, ConfigurationType::MaxLogFileSize, std::string("0"));
unsafeSetIfNotExist(Level::Global, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
unsafeSetIfNotExist(Level::Debug, ConfigurationType::Format,
std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg"));
// INFO and WARNING are set to default by Level::Global
unsafeSetIfNotExist(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
unsafeSetIfNotExist(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
unsafeSetIfNotExist(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg"));
unsafeSetIfNotExist(Level::Trace, ConfigurationType::Format,
std::string("%datetime %level [%logger] [%func] [%loc] %msg"));
}
bool Configurations::Parser::parseFromFile(const std::string& configurationFile, Configurations* sender,
Configurations* base) {
sender->setFromBase(base);
std::ifstream fileStream_(configurationFile.c_str(), std::ifstream::in);
ELPP_ASSERT(fileStream_.is_open(), "Unable to open configuration file [" << configurationFile << "] for parsing.");
bool parsedSuccessfully = false;
std::string line = std::string();
Level currLevel = Level::Unknown;
std::string currConfigStr = std::string();
std::string currLevelStr = std::string();
while (fileStream_.good()) {
std::getline(fileStream_, line);
parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender);
ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line);
}
return parsedSuccessfully;
}
bool Configurations::Parser::parseFromText(const std::string& configurationsString, Configurations* sender,
Configurations* base) {
sender->setFromBase(base);
bool parsedSuccessfully = false;
std::stringstream ss(configurationsString);
std::string line = std::string();
Level currLevel = Level::Unknown;
std::string currConfigStr = std::string();
std::string currLevelStr = std::string();
while (std::getline(ss, line)) {
parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender);
ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line);
}
return parsedSuccessfully;
}
void Configurations::Parser::ignoreComments(std::string* line) {
std::size_t foundAt = 0;
std::size_t quotesStart = line->find("\"");
std::size_t quotesEnd = std::string::npos;
if (quotesStart != std::string::npos) {
quotesEnd = line->find("\"", quotesStart + 1);
while (quotesEnd != std::string::npos && line->at(quotesEnd - 1) == '\\') {
// Do not erase slash yet - we will erase it in parseLine(..) while loop
quotesEnd = line->find("\"", quotesEnd + 2);
}
}
if ((foundAt = line->find(base::consts::kConfigurationComment)) != std::string::npos) {
if (foundAt < quotesEnd) {
foundAt = line->find(base::consts::kConfigurationComment, quotesEnd + 1);
}
*line = line->substr(0, foundAt);
}
}
bool Configurations::Parser::isLevel(const std::string& line) {
return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLevel));
}
bool Configurations::Parser::isComment(const std::string& line) {
return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationComment));
}
bool Configurations::Parser::isConfig(const std::string& line) {
std::size_t assignment = line.find('=');
return line != "" &&
((line[0] >= 'A' && line[0] <= 'Z') || (line[0] >= 'a' && line[0] <= 'z')) &&
(assignment != std::string::npos) &&
(line.size() > assignment);
}
bool Configurations::Parser::parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr,
Level* currLevel,
Configurations* conf) {
ConfigurationType currConfig = ConfigurationType::Unknown;
std::string currValue = std::string();
*line = base::utils::Str::trim(*line);
if (isComment(*line)) return true;
ignoreComments(line);
*line = base::utils::Str::trim(*line);
if (line->empty()) {
// Comment ignored
return true;
}
if (isLevel(*line)) {
if (line->size() <= 2) {
return true;
}
*currLevelStr = line->substr(1, line->size() - 2);
*currLevelStr = base::utils::Str::toUpper(*currLevelStr);
*currLevelStr = base::utils::Str::trim(*currLevelStr);
*currLevel = LevelHelper::convertFromString(currLevelStr->c_str());
return true;
}
if (isConfig(*line)) {
std::size_t assignment = line->find('=');
*currConfigStr = line->substr(0, assignment);
*currConfigStr = base::utils::Str::toUpper(*currConfigStr);
*currConfigStr = base::utils::Str::trim(*currConfigStr);
currConfig = ConfigurationTypeHelper::convertFromString(currConfigStr->c_str());
currValue = line->substr(assignment + 1);
currValue = base::utils::Str::trim(currValue);
std::size_t quotesStart = currValue.find("\"", 0);
std::size_t quotesEnd = std::string::npos;
if (quotesStart != std::string::npos) {
quotesEnd = currValue.find("\"", quotesStart + 1);
while (quotesEnd != std::string::npos && currValue.at(quotesEnd - 1) == '\\') {
currValue = currValue.erase(quotesEnd - 1, 1);
quotesEnd = currValue.find("\"", quotesEnd + 2);
}
}
if (quotesStart != std::string::npos && quotesEnd != std::string::npos) {
// Quote provided - check and strip if valid
ELPP_ASSERT((quotesStart < quotesEnd), "Configuration error - No ending quote found in ["
<< currConfigStr << "]");
ELPP_ASSERT((quotesStart + 1 != quotesEnd), "Empty configuration value for [" << currConfigStr << "]");
if ((quotesStart != quotesEnd) && (quotesStart + 1 != quotesEnd)) {
// Explicit check in case if assertion is disabled
currValue = currValue.substr(quotesStart + 1, quotesEnd - 1);
}
}
}
ELPP_ASSERT(*currLevel != Level::Unknown, "Unrecognized severity level [" << *currLevelStr << "]");
ELPP_ASSERT(currConfig != ConfigurationType::Unknown, "Unrecognized configuration [" << *currConfigStr << "]");
if (*currLevel == Level::Unknown || currConfig == ConfigurationType::Unknown) {
return false; // unrecognizable level or config
}
conf->set(*currLevel, currConfig, currValue);
return true;
}
void Configurations::unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value) {
Configuration* conf = RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType);
if (conf == nullptr) {
unsafeSet(level, configurationType, value);
}
}
void Configurations::unsafeSet(Level level, ConfigurationType configurationType, const std::string& value) {
Configuration* conf = RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType);
if (conf == nullptr) {
registerNew(new Configuration(level, configurationType, value));
} else {
conf->setValue(value);
}
if (level == Level::Global) {
unsafeSetGlobally(configurationType, value, false);
}
}
void Configurations::setGlobally(ConfigurationType configurationType, const std::string& value,
bool includeGlobalLevel) {
if (includeGlobalLevel) {
set(Level::Global, configurationType, value);
}
base::type::EnumType lIndex = LevelHelper::kMinValid;
LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
set(LevelHelper::castFromInt(lIndex), configurationType, value);
return false; // Do not break lambda function yet as we need to set all levels regardless
});
}
void Configurations::unsafeSetGlobally(ConfigurationType configurationType, const std::string& value,
bool includeGlobalLevel) {
if (includeGlobalLevel) {
unsafeSet(Level::Global, configurationType, value);
}
base::type::EnumType lIndex = LevelHelper::kMinValid;
LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
unsafeSet(LevelHelper::castFromInt(lIndex), configurationType, value);
return false; // Do not break lambda function yet as we need to set all levels regardless
});
}
// LogBuilder
void LogBuilder::convertToColoredOutput(base::type::string_t* logLine, Level level) {
if (!m_termSupportsColor) return;
const base::type::char_t* resetColor = ELPP_LITERAL("\x1b[0m");
if (level == Level::Error || level == Level::Fatal)
*logLine = ELPP_LITERAL("\x1b[31m") + *logLine + resetColor;
else if (level == Level::Warning)
*logLine = ELPP_LITERAL("\x1b[33m") + *logLine + resetColor;
else if (level == Level::Debug)
*logLine = ELPP_LITERAL("\x1b[32m") + *logLine + resetColor;
else if (level == Level::Info)
*logLine = ELPP_LITERAL("\x1b[36m") + *logLine + resetColor;
else if (level == Level::Trace)
*logLine = ELPP_LITERAL("\x1b[35m") + *logLine + resetColor;
}
// Logger
Logger::Logger(const std::string& id, base::LogStreamsReferenceMapPtr logStreamsReference) :
m_id(id),
m_typedConfigurations(nullptr),
m_parentApplicationName(std::string()),
m_isConfigured(false),
m_logStreamsReference(logStreamsReference) {
initUnflushedCount();
}
Logger::Logger(const std::string& id, const Configurations& configurations,
base::LogStreamsReferenceMapPtr logStreamsReference) :
m_id(id),
m_typedConfigurations(nullptr),
m_parentApplicationName(std::string()),
m_isConfigured(false),
m_logStreamsReference(logStreamsReference) {
initUnflushedCount();
configure(configurations);
}
Logger::Logger(const Logger& logger) {
base::utils::safeDelete(m_typedConfigurations);
m_id = logger.m_id;
m_typedConfigurations = logger.m_typedConfigurations;
m_parentApplicationName = logger.m_parentApplicationName;
m_isConfigured = logger.m_isConfigured;
m_configurations = logger.m_configurations;
m_unflushedCount = logger.m_unflushedCount;
m_logStreamsReference = logger.m_logStreamsReference;
}
Logger& Logger::operator=(const Logger& logger) {
if (&logger != this) {
base::utils::safeDelete(m_typedConfigurations);
m_id = logger.m_id;
m_typedConfigurations = logger.m_typedConfigurations;
m_parentApplicationName = logger.m_parentApplicationName;
m_isConfigured = logger.m_isConfigured;
m_configurations = logger.m_configurations;
m_unflushedCount = logger.m_unflushedCount;
m_logStreamsReference = logger.m_logStreamsReference;
}
return *this;
}
void Logger::configure(const Configurations& configurations) {
m_isConfigured = false; // we set it to false in case if we fail
initUnflushedCount();
if (m_typedConfigurations != nullptr) {
Configurations* c = const_cast<Configurations*>(m_typedConfigurations->configurations());
if (c->hasConfiguration(Level::Global, ConfigurationType::Filename)) {
flush();
}
}
base::threading::ScopedLock scopedLock(lock());
if (m_configurations != configurations) {
m_configurations.setFromBase(const_cast<Configurations*>(&configurations));
}
base::utils::safeDelete(m_typedConfigurations);
m_typedConfigurations = new base::TypedConfigurations(&m_configurations, m_logStreamsReference);
resolveLoggerFormatSpec();
m_isConfigured = true;
}
void Logger::reconfigure(void) {
ELPP_INTERNAL_INFO(1, "Reconfiguring logger [" << m_id << "]");
configure(m_configurations);
}
bool Logger::isValidId(const std::string& id) {
for (std::string::const_iterator it = id.begin(); it != id.end(); ++it) {
if (!base::utils::Str::contains(base::consts::kValidLoggerIdSymbols, *it)) {
return false;
}
}
return true;
}
void Logger::flush(void) {
ELPP_INTERNAL_INFO(3, "Flushing logger [" << m_id << "] all levels");
base::threading::ScopedLock scopedLock(lock());
base::type::EnumType lIndex = LevelHelper::kMinValid;
LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
flush(LevelHelper::castFromInt(lIndex), nullptr);
return false;
});
}
void Logger::flush(Level level, base::type::fstream_t* fs) {
if (fs == nullptr && m_typedConfigurations->toFile(level)) {
fs = m_typedConfigurations->fileStream(level);
}
if (fs != nullptr) {
fs->flush();
std::unordered_map<Level, unsigned int>::iterator iter = m_unflushedCount.find(level);
if (iter != m_unflushedCount.end()) {
iter->second = 0;
}
Helpers::validateFileRolling(this, level);
}
}
void Logger::initUnflushedCount(void) {
m_unflushedCount.clear();
base::type::EnumType lIndex = LevelHelper::kMinValid;
LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
m_unflushedCount.insert(std::make_pair(LevelHelper::castFromInt(lIndex), 0));
return false;
});
}
void Logger::resolveLoggerFormatSpec(void) const {
base::type::EnumType lIndex = LevelHelper::kMinValid;
LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
base::LogFormat* logFormat =
const_cast<base::LogFormat*>(&m_typedConfigurations->logFormat(LevelHelper::castFromInt(lIndex)));
base::utils::Str::replaceFirstWithEscape(logFormat->m_format, base::consts::kLoggerIdFormatSpecifier, m_id);
return false;
});
}
// el::base
namespace base {
// el::base::utils
namespace utils {
// File
base::type::fstream_t* File::newFileStream(const std::string& filename) {
base::type::fstream_t *fs = new base::type::fstream_t(filename.c_str(),
base::type::fstream_t::out
#if !defined(ELPP_FRESH_LOG_FILE)
| base::type::fstream_t::app
#endif
);
#if defined(ELPP_UNICODE)
std::locale elppUnicodeLocale("");
# if ELPP_OS_WINDOWS
std::locale elppUnicodeLocaleWindows(elppUnicodeLocale, new std::codecvt_utf8_utf16<wchar_t>);
elppUnicodeLocale = elppUnicodeLocaleWindows;
# endif // ELPP_OS_WINDOWS
fs->imbue(elppUnicodeLocale);
#endif // defined(ELPP_UNICODE)
if (fs->is_open()) {
fs->flush();
} else {
base::utils::safeDelete(fs);
ELPP_INTERNAL_ERROR("Bad file [" << filename << "]", true);
}
return fs;
}
std::size_t File::getSizeOfFile(base::type::fstream_t* fs) {
if (fs == nullptr) {
return 0;
}
// Since the file stream is appended to or truncated, the current
// offset is the file size.
std::size_t size = static_cast<std::size_t>(fs->tellg());
return size;
}
bool File::pathExists(const char* path, bool considerFile) {
if (path == nullptr) {
return false;
}
#if ELPP_OS_UNIX
ELPP_UNUSED(considerFile);
struct stat st;
return (stat(path, &st) == 0);
#elif ELPP_OS_WINDOWS
DWORD fileType = GetFileAttributesA(path);
if (fileType == INVALID_FILE_ATTRIBUTES) {
return false;
}
return considerFile ? true : ((fileType & FILE_ATTRIBUTE_DIRECTORY) == 0 ? false : true);
#endif // ELPP_OS_UNIX
}
bool File::createPath(const std::string& path) {
if (path.empty()) {
return false;
}
if (base::utils::File::pathExists(path.c_str())) {
return true;
}
int status = -1;
char* currPath = const_cast<char*>(path.c_str());
std::string builtPath = std::string();
#if ELPP_OS_UNIX
if (path[0] == '/') {
builtPath = "/";
}
currPath = STRTOK(currPath, base::consts::kFilePathSeparator, 0);
#elif ELPP_OS_WINDOWS
// Use secure functions API
char* nextTok_ = nullptr;
currPath = STRTOK(currPath, base::consts::kFilePathSeparator, &nextTok_);
ELPP_UNUSED(nextTok_);
#endif // ELPP_OS_UNIX
while (currPath != nullptr) {
builtPath.append(currPath);
builtPath.append(base::consts::kFilePathSeparator);
#if ELPP_OS_UNIX
status = mkdir(builtPath.c_str(), ELPP_LOG_PERMS);
currPath = STRTOK(nullptr, base::consts::kFilePathSeparator, 0);
#elif ELPP_OS_WINDOWS
status = _mkdir(builtPath.c_str());
currPath = STRTOK(nullptr, base::consts::kFilePathSeparator, &nextTok_);
#endif // ELPP_OS_UNIX
}
if (status == -1) {
ELPP_INTERNAL_ERROR("Error while creating path [" << path << "]", true);
return false;
}
return true;
}
std::string File::extractPathFromFilename(const std::string& fullPath, const char* separator) {
if ((fullPath == "") || (fullPath.find(separator) == std::string::npos)) {
return fullPath;
}
std::size_t lastSlashAt = fullPath.find_last_of(separator);
if (lastSlashAt == 0) {
return std::string(separator);
}
return fullPath.substr(0, lastSlashAt + 1);
}
void File::buildStrippedFilename(const char* filename, char buff[], std::size_t limit) {
std::size_t sizeOfFilename = strlen(filename);
if (sizeOfFilename >= limit) {
filename += (sizeOfFilename - limit);
if (filename[0] != '.' && filename[1] != '.') { // prepend if not already
filename += 3; // 3 = '..'
STRCAT(buff, "..", limit);
}
}
STRCAT(buff, filename, limit);
}
void File::buildBaseFilename(const std::string& fullPath, char buff[], std::size_t limit, const char* separator) {
const char *filename = fullPath.c_str();
std::size_t lastSlashAt = fullPath.find_last_of(separator);
filename += lastSlashAt ? lastSlashAt+1 : 0;
std::size_t sizeOfFilename = strlen(filename);
if (sizeOfFilename >= limit) {
filename += (sizeOfFilename - limit);
if (filename[0] != '.' && filename[1] != '.') { // prepend if not already
filename += 3; // 3 = '..'
STRCAT(buff, "..", limit);
}
}
STRCAT(buff, filename, limit);
}
// Str
bool Str::wildCardMatch(const char* str, const char* pattern) {
while (*pattern) {
switch (*pattern) {
case '?':
if (!*str)
return false;
++str;
++pattern;
break;
case '*':
if (wildCardMatch(str, pattern + 1))
return true;
if (*str && wildCardMatch(str + 1, pattern))
return true;
return false;
default:
if (*str++ != *pattern++)
return false;
break;
}
}
return !*str && !*pattern;
}
std::string& Str::ltrim(std::string& str) {
str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](char c) {
return !std::isspace(c);
} ));
return str;
}
std::string& Str::rtrim(std::string& str) {
str.erase(std::find_if(str.rbegin(), str.rend(), [](char c) {
return !std::isspace(c);
}).base(), str.end());
return str;
}
std::string& Str::trim(std::string& str) {
return ltrim(rtrim(str));
}
bool Str::startsWith(const std::string& str, const std::string& start) {
return (str.length() >= start.length()) && (str.compare(0, start.length(), start) == 0);
}
bool Str::endsWith(const std::string& str, const std::string& end) {
return (str.length() >= end.length()) && (str.compare(str.length() - end.length(), end.length(), end) == 0);
}
std::string& Str::replaceAll(std::string& str, char replaceWhat, char replaceWith) {
std::replace(str.begin(), str.end(), replaceWhat, replaceWith);
return str;
}
std::string& Str::replaceAll(std::string& str, const std::string& replaceWhat,
const std::string& replaceWith) {
if (replaceWhat == replaceWith)
return str;
std::size_t foundAt = std::string::npos;
while ((foundAt = str.find(replaceWhat, foundAt + 1)) != std::string::npos) {
str.replace(foundAt, replaceWhat.length(), replaceWith);
}
return str;
}
void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
const base::type::string_t& replaceWith) {
std::size_t foundAt = base::type::string_t::npos;
while ((foundAt = str.find(replaceWhat, foundAt + 1)) != base::type::string_t::npos) {
if (foundAt > 0 && str[foundAt - 1] == base::consts::kFormatSpecifierChar) {
str.erase(foundAt - 1, 1);
++foundAt;
} else {
str.replace(foundAt, replaceWhat.length(), replaceWith);
return;
}
}
}
#if defined(ELPP_UNICODE)
void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
const std::string& replaceWith) {
replaceFirstWithEscape(str, replaceWhat, base::type::string_t(replaceWith.begin(), replaceWith.end()));
}
#endif // defined(ELPP_UNICODE)
std::string& Str::toUpper(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](char c) {
return static_cast<char>(::toupper(c));
});
return str;
}
bool Str::cStringEq(const char* s1, const char* s2) {
if (s1 == nullptr && s2 == nullptr) return true;
if (s1 == nullptr || s2 == nullptr) return false;
return strcmp(s1, s2) == 0;
}
bool Str::cStringCaseEq(const char* s1, const char* s2) {
if (s1 == nullptr && s2 == nullptr) return true;
if (s1 == nullptr || s2 == nullptr) return false;
// With thanks to cygwin for this code
int d = 0;
while (true) {
const int c1 = toupper(*s1++);
const int c2 = toupper(*s2++);
if (((d = c1 - c2) != 0) || (c2 == '\0')) {
break;
}
}
return d == 0;
}
bool Str::contains(const char* str, char c) {
for (; *str; ++str) {
if (*str == c)
return true;
}
return false;
}
char* Str::convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded) {
char localBuff[10] = "";
char* p = localBuff + sizeof(localBuff) - 2;
if (n > 0) {
for (; n > 0 && p > localBuff && len > 0; n /= 10, --len)
*--p = static_cast<char>(n % 10 + '0');
} else {
*--p = '0';
--len;
}
if (zeroPadded)
while (p > localBuff && len-- > 0) *--p = static_cast<char>('0');