Debian Codegraph @

external/easylogging++/easylogging++.cc

raw symbols SCIP
1 //
2 // Bismillah ar-Rahmaan ar-Raheem
3 //
4 // Easylogging++ v9.96.7
5 // Cross-platform logging library for C++ applications
6 //
7 // Copyright (c) 2012-2018 Zuhd Web Services
8 // Copyright (c) 2012-2018 @abumusamq
9 //
10 // This library is released under the MIT Licence.
11 // https://github.com/zuhd-org/easyloggingpp/blob/master/LICENSE
12 //
13 // https://zuhd.org
14 // http://muflihun.com
15 //
16
17 #define EASYLOGGING_CC
18 #include "easylogging++.h"
19
20 #include <atomic>
21 #include <unistd.h>
22
23 #if defined(AUTO_INITIALIZE_EASYLOGGINGPP)
24 INITIALIZE_EASYLOGGINGPP
25 #endif
26
27 namespace el {
28
29 // el::base
30 namespace base {
31 // el::base::consts
32 namespace consts {
33
34 // Level log values - These are values that are replaced in place of %level format specifier
35 // Extra spaces after format specifiers are only for readability purposes in log files
36 static const base::type::char_t* kInfoLevelLogValue = ELPP_LITERAL("INFO");
37 static const base::type::char_t* kDebugLevelLogValue = ELPP_LITERAL("DEBUG");
38 static const base::type::char_t* kWarningLevelLogValue = ELPP_LITERAL("WARNING");
39 static const base::type::char_t* kErrorLevelLogValue = ELPP_LITERAL("ERROR");
40 static const base::type::char_t* kFatalLevelLogValue = ELPP_LITERAL("FATAL");
41 static const base::type::char_t* kVerboseLevelLogValue =
42 ELPP_LITERAL("VERBOSE"); // will become VERBOSE-x where x = verbose level
43 static const base::type::char_t* kTraceLevelLogValue = ELPP_LITERAL("TRACE");
44 static const base::type::char_t* kInfoLevelShortLogValue = ELPP_LITERAL("I");
45 static const base::type::char_t* kDebugLevelShortLogValue = ELPP_LITERAL("D");
46 static const base::type::char_t* kWarningLevelShortLogValue = ELPP_LITERAL("W");
47 static const base::type::char_t* kErrorLevelShortLogValue = ELPP_LITERAL("E");
48 static const base::type::char_t* kFatalLevelShortLogValue = ELPP_LITERAL("F");
49 static const base::type::char_t* kVerboseLevelShortLogValue = ELPP_LITERAL("V");
50 static const base::type::char_t* kTraceLevelShortLogValue = ELPP_LITERAL("T");
51 // Format specifiers - These are used to define log format
52 static const base::type::char_t* kAppNameFormatSpecifier = ELPP_LITERAL("%app");
53 static const base::type::char_t* kLoggerIdFormatSpecifier = ELPP_LITERAL("%logger");
54 static const base::type::char_t* kThreadIdFormatSpecifier = ELPP_LITERAL("%thread");
55 static const base::type::char_t* kSeverityLevelFormatSpecifier = ELPP_LITERAL("%level");
56 static const base::type::char_t* kSeverityLevelShortFormatSpecifier = ELPP_LITERAL("%levshort");
57 static const base::type::char_t* kDateTimeFormatSpecifier = ELPP_LITERAL("%datetime");
58 static const base::type::char_t* kLogFileFormatSpecifier = ELPP_LITERAL("%file");
59 static const base::type::char_t* kLogFileBaseFormatSpecifier = ELPP_LITERAL("%fbase");
60 static const base::type::char_t* kLogLineFormatSpecifier = ELPP_LITERAL("%line");
61 static const base::type::char_t* kLogLocationFormatSpecifier = ELPP_LITERAL("%loc");
62 static const base::type::char_t* kLogFunctionFormatSpecifier = ELPP_LITERAL("%func");
63 static const base::type::char_t* kCurrentUserFormatSpecifier = ELPP_LITERAL("%user");
64 static const base::type::char_t* kCurrentHostFormatSpecifier = ELPP_LITERAL("%host");
65 static const base::type::char_t* kMessageFormatSpecifier = ELPP_LITERAL("%msg");
66 static const base::type::char_t* kVerboseLevelFormatSpecifier = ELPP_LITERAL("%vlevel");
67 static const char* kDateTimeFormatSpecifierForFilename = "%datetime";
68 // Date/time
69 static const char* kDays[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
70 static const char* kDaysAbbrev[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
71 static const char* kMonths[12] = { "January", "February", "March", "Apri", "May", "June", "July", "August",
72 "September", "October", "November", "December"
73 };
74 static const char* kMonthsAbbrev[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
75 static const char* kDefaultDateTimeFormat = "%Y-%M-%d %H:%m:%s,%g";
76 static const char* kDefaultDateTimeFormatInFilename = "%Y-%M-%d_%H-%m";
77 static const int kYearBase = 1900;
78 static const char* kAm = "AM";
79 static const char* kPm = "PM";
80 // Miscellaneous constants
81
82 static const char* kNullPointer = "nullptr";
83 #if ELPP_VARIADIC_TEMPLATES_SUPPORTED
84 #endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED
85 static const base::type::VerboseLevel kMaxVerboseLevel = 9;
86 static const char* kUnknownUser = "user";
87 static const char* kUnknownHost = "unknown-host";
88
89
90 //---------------- DEFAULT LOG FILE -----------------------
91
92 #if defined(ELPP_NO_DEFAULT_LOG_FILE)
93 # if ELPP_OS_UNIX
94 static const char* kDefaultLogFile = "/dev/null";
95 # elif ELPP_OS_WINDOWS
96 static const char* kDefaultLogFile = "nul";
97 # endif // ELPP_OS_UNIX
98 #elif defined(ELPP_DEFAULT_LOG_FILE)
99 static const char* kDefaultLogFile = ELPP_DEFAULT_LOG_FILE;
100 #else
101 static const char* kDefaultLogFile = "myeasylog.log";
102 #endif // defined(ELPP_NO_DEFAULT_LOG_FILE)
103
104
105 #if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)
106 static const char* kDefaultLogFileParam = "--default-log-file";
107 #endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)
108 #if defined(ELPP_LOGGING_FLAGS_FROM_ARG)
109 static const char* kLoggingFlagsParam = "--logging-flags";
110 #endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG)
111 static const char* kValidLoggerIdSymbols =
112 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._";
113 static const char* kConfigurationComment = "##";
114 static const char* kConfigurationLevel = "*";
115 static const char* kConfigurationLoggerId = "--";
116 }
117 // el::base::utils
118 namespace utils {
119
120 /// @brief Aborts application due with user-defined status
121 static void abort(int status, const std::string& reason) {
122 // Both status and reason params are there for debugging with tools like gdb etc
123 ELPP_UNUSED(status);
124 ELPP_UNUSED(reason);
125 #if defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG)
126 // Ignore msvc critical error dialog - break instead (on debug mode)
127 _asm int 3
128 #else
129 #ifdef NDEBUG
130 ::_exit(1);
131 #else
132 ::abort();
133 #endif
134 #endif // defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG)
135 }
136
137 static el::Color colorFromLevel(el::Level level)
138 {
139 switch (level)
140 {
141 case Level::Error: case Level::Fatal: return el::Color::Red;
142 case Level::Warning: return el::Color::Yellow;
143 case Level::Debug: return el::Color::Green;
144 case Level::Info: return el::Color::Cyan;
145 case Level::Trace: return el::Color::Magenta;
146 default: return el::Color::Default;
147 }
148 }
149
150 static void setConsoleColor(el::Color color, bool bright)
151 {
152 static const char *no_color_var = getenv("NO_COLOR");
153 static const bool no_color = no_color_var && *no_color_var; // apparently, NO_COLOR=0 means no color too (as per no-color.org)
154 if (no_color)
155 return;
156
157 #if ELPP_OS_WINDOWS
158 HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
159 switch (color)
160 {
161 case el::Color::Red: SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | (bright ? FOREGROUND_INTENSITY:0)); break;
162 case el::Color::Green: SetConsoleTextAttribute(h_stdout, FOREGROUND_GREEN | (bright ? FOREGROUND_INTENSITY:0)); break;
163 case el::Color::Yellow: SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | (bright ? FOREGROUND_INTENSITY:0)); break;
164 case el::Color::Blue: SetConsoleTextAttribute(h_stdout, FOREGROUND_BLUE | (bright ? FOREGROUND_INTENSITY:0)); break;
165 case el::Color::Magenta: SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_BLUE | (bright ? FOREGROUND_INTENSITY:0)); break;
166 case el::Color::Cyan: SetConsoleTextAttribute(h_stdout, FOREGROUND_GREEN | FOREGROUND_BLUE | (bright ? FOREGROUND_INTENSITY:0)); break;
167 case el::Color::Default: default: SetConsoleTextAttribute(h_stdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | (bright ? FOREGROUND_INTENSITY:0)); break;
168 }
169 #else
170 if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput))
171 {
172 switch (color)
173 {
174 case el::Color::Red: ELPP_COUT << (bright ? "\033[1;31m" : "\033[0;31m"); break;
175 case el::Color::Green: ELPP_COUT << (bright ? "\033[1;32m" : "\033[0;32m"); break;
176 case el::Color::Yellow: ELPP_COUT << (bright ? "\033[1;33m" : "\033[0;33m"); break;
177 case el::Color::Blue: ELPP_COUT << (bright ? "\033[1;34m" : "\033[0;34m"); break;
178 case el::Color::Magenta: ELPP_COUT << (bright ? "\033[1;35m" : "\033[0;35m"); break;
179 case el::Color::Cyan: ELPP_COUT << (bright ? "\033[1;36m" : "\033[0;36m"); break;
180 case el::Color::Default: default: ELPP_COUT << "\033[0m"; break;
181 }
182 }
183 #endif
184 }
185
186 } // namespace utils
187 } // namespace base
188
189 // el
190
191 // LevelHelper
192
193 const char* LevelHelper::convertToString(Level level) {
194 // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet.
195 if (level == Level::Global) return "GLOBAL";
196 if (level == Level::Debug) return "DEBUG";
197 if (level == Level::Info) return "INFO";
198 if (level == Level::Warning) return "WARNING";
199 if (level == Level::Error) return "ERROR";
200 if (level == Level::Fatal) return "FATAL";
201 if (level == Level::Verbose) return "VERBOSE";
202 if (level == Level::Trace) return "TRACE";
203 return "UNKNOWN";
204 }
205
206 struct StringToLevelItem {
207 const char* levelString;
208 Level level;
209 };
210
211 static struct StringToLevelItem stringToLevelMap[] = {
212 { "global", Level::Global },
213 { "debug", Level::Debug },
214 { "info", Level::Info },
215 { "warning", Level::Warning },
216 { "error", Level::Error },
217 { "fatal", Level::Fatal },
218 { "verbose", Level::Verbose },
219 { "trace", Level::Trace }
220 };
221
222 Level LevelHelper::convertFromString(const char* levelStr) {
223 for (auto& item : stringToLevelMap) {
224 if (base::utils::Str::cStringCaseEq(levelStr, item.levelString)) {
225 return item.level;
226 }
227 }
228 return Level::Unknown;
229 }
230
231 Level LevelHelper::convertFromStringPrefix(const char* levelStr) {
232 if ((strncmp(levelStr, "GLOBAL", 6) == 0) || (strncmp(levelStr, "global", 6) == 0))
233 return Level::Global;
234 if ((strncmp(levelStr, "DEBUG", 5) == 0) || (strncmp(levelStr, "debug", 5) == 0))
235 return Level::Debug;
236 if ((strncmp(levelStr, "INFO", 4) == 0) || (strncmp(levelStr, "info", 4) == 0))
237 return Level::Info;
238 if ((strncmp(levelStr, "WARNING", 7) == 0) || (strncmp(levelStr, "warning", 7) == 0))
239 return Level::Warning;
240 if ((strncmp(levelStr, "ERROR", 5) == 0) || (strncmp(levelStr, "error", 5) == 0))
241 return Level::Error;
242 if ((strncmp(levelStr, "FATAL", 5) == 0) || (strncmp(levelStr, "fatal", 5) == 0))
243 return Level::Fatal;
244 if ((strncmp(levelStr, "VERBOSE", 7) == 0) || (strncmp(levelStr, "verbose", 7) == 0))
245 return Level::Verbose;
246 if ((strncmp(levelStr, "TRACE", 5) == 0) || (strncmp(levelStr, "trace", 5) == 0))
247 return Level::Trace;
248 return Level::Unknown;
249 }
250
251 void LevelHelper::forEachLevel(base::type::EnumType* startIndex, const std::function<bool(void)>& fn) {
252 base::type::EnumType lIndexMax = LevelHelper::kMaxValid;
253 do {
254 if (fn()) {
255 break;
256 }
257 *startIndex = static_cast<base::type::EnumType>(*startIndex << 1);
258 } while (*startIndex <= lIndexMax);
259 }
260
261 // ConfigurationTypeHelper
262
263 const char* ConfigurationTypeHelper::convertToString(ConfigurationType configurationType) {
264 // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet.
265 if (configurationType == ConfigurationType::Enabled) return "ENABLED";
266 if (configurationType == ConfigurationType::Filename) return "FILENAME";
267 if (configurationType == ConfigurationType::Format) return "FORMAT";
268 if (configurationType == ConfigurationType::ToFile) return "TO_FILE";
269 if (configurationType == ConfigurationType::ToStandardOutput) return "TO_STANDARD_OUTPUT";
270 if (configurationType == ConfigurationType::SubsecondPrecision) return "SUBSECOND_PRECISION";
271 if (configurationType == ConfigurationType::PerformanceTracking) return "PERFORMANCE_TRACKING";
272 if (configurationType == ConfigurationType::MaxLogFileSize) return "MAX_LOG_FILE_SIZE";
273 if (configurationType == ConfigurationType::LogFlushThreshold) return "LOG_FLUSH_THRESHOLD";
274 return "UNKNOWN";
275 }
276
277 struct ConfigurationStringToTypeItem {
278 const char* configString;
279 ConfigurationType configType;
280 };
281
282 static struct ConfigurationStringToTypeItem configStringToTypeMap[] = {
283 { "enabled", ConfigurationType::Enabled },
284 { "to_file", ConfigurationType::ToFile },
285 { "to_standard_output", ConfigurationType::ToStandardOutput },
286 { "format", ConfigurationType::Format },
287 { "filename", ConfigurationType::Filename },
288 { "subsecond_precision", ConfigurationType::SubsecondPrecision },
289 { "milliseconds_width", ConfigurationType::MillisecondsWidth },
290 { "performance_tracking", ConfigurationType::PerformanceTracking },
291 { "max_log_file_size", ConfigurationType::MaxLogFileSize },
292 { "log_flush_threshold", ConfigurationType::LogFlushThreshold },
293 };
294
295 ConfigurationType ConfigurationTypeHelper::convertFromString(const char* configStr) {
296 for (auto& item : configStringToTypeMap) {
297 if (base::utils::Str::cStringCaseEq(configStr, item.configString)) {
298 return item.configType;
299 }
300 }
301 return ConfigurationType::Unknown;
302 }
303
304 void ConfigurationTypeHelper::forEachConfigType(base::type::EnumType* startIndex, const std::function<bool(void)>& fn) {
305 base::type::EnumType cIndexMax = ConfigurationTypeHelper::kMaxValid;
306 do {
307 if (fn()) {
308 break;
309 }
310 *startIndex = static_cast<base::type::EnumType>(*startIndex << 1);
311 } while (*startIndex <= cIndexMax);
312 }
313
314 // Configuration
315
316 Configuration::Configuration(const Configuration& c) :
317 m_level(c.m_level),
318 m_configurationType(c.m_configurationType),
319 m_value(c.m_value) {
320 }
321
322 Configuration& Configuration::operator=(const Configuration& c) {
323 if (&c != this) {
324 m_level = c.m_level;
325 m_configurationType = c.m_configurationType;
326 m_value = c.m_value;
327 }
328 return *this;
329 }
330
331 /// @brief Full constructor used to sets value of configuration
332 Configuration::Configuration(Level level, ConfigurationType configurationType, const std::string& value) :
333 m_level(level),
334 m_configurationType(configurationType),
335 m_value(value) {
336 }
337
338 void Configuration::log(el::base::type::ostream_t& os) const {
339 os << LevelHelper::convertToString(m_level)
340 << ELPP_LITERAL(" ") << ConfigurationTypeHelper::convertToString(m_configurationType)
341 << ELPP_LITERAL(" = ") << m_value.c_str();
342 }
343
344 /// @brief Used to find configuration from configuration (pointers) repository. Avoid using it.
345 Configuration::Predicate::Predicate(Level level, ConfigurationType configurationType) :
346 m_level(level),
347 m_configurationType(configurationType) {
348 }
349
350 bool Configuration::Predicate::operator()(const Configuration* conf) const {
351 return ((conf != nullptr) && (conf->level() == m_level) && (conf->configurationType() == m_configurationType));
352 }
353
354 // Configurations
355
356 Configurations::Configurations(void) :
357 m_configurationFile(std::string()),
358 m_isFromFile(false) {
359 }
360
361 Configurations::Configurations(const std::string& configurationFile, bool useDefaultsForRemaining,
362 Configurations* base) :
363 m_configurationFile(configurationFile),
364 m_isFromFile(false) {
365 parseFromFile(configurationFile, base);
366 if (useDefaultsForRemaining) {
367 setRemainingToDefault();
368 }
369 }
370
371 bool Configurations::parseFromFile(const std::string& configurationFile, Configurations* base) {
372 // We initial assertion with true because if we have assertion diabled, we want to pass this
373 // check and if assertion is enabled we will have values re-assigned any way.
374 bool assertionPassed = true;
375 ELPP_ASSERT((assertionPassed = base::utils::File::pathExists(configurationFile.c_str(), true)) == true,
376 "Configuration file [" << configurationFile << "] does not exist!");
377 if (!assertionPassed) {
378 return false;
379 }
380 bool success = Parser::parseFromFile(configurationFile, this, base);
381 m_isFromFile = success;
382 return success;
383 }
384
385 bool Configurations::parseFromText(const std::string& configurationsString, Configurations* base) {
386 bool success = Parser::parseFromText(configurationsString, this, base);
387 if (success) {
388 m_isFromFile = false;
389 }
390 return success;
391 }
392
393 void Configurations::setFromBase(Configurations* base) {
394 if (base == nullptr || base == this) {
395 return;
396 }
397 base::threading::ScopedLock scopedLock(base->lock());
398 for (Configuration*& conf : base->list()) {
399 set(conf);
400 }
401 }
402
403 bool Configurations::hasConfiguration(ConfigurationType configurationType) {
404 base::type::EnumType lIndex = LevelHelper::kMinValid;
405 bool result = false;
406 LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
407 if (hasConfiguration(LevelHelper::castFromInt(lIndex), configurationType)) {
408 result = true;
409 }
410 return result;
411 });
412 return result;
413 }
414
415 bool Configurations::hasConfiguration(Level level, ConfigurationType configurationType) {
416 base::threading::ScopedLock scopedLock(lock());
417 #if ELPP_COMPILER_INTEL
418 // We cant specify template types here, Intel C++ throws compilation error
419 // "error: type name is not allowed"
420 return RegistryWithPred::get(level, configurationType) != nullptr;
421 #else
422 return RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType) != nullptr;
423 #endif // ELPP_COMPILER_INTEL
424 }
425
426 void Configurations::set(Level level, ConfigurationType configurationType, const std::string& value) {
427 base::threading::ScopedLock scopedLock(lock());
428 unsafeSet(level, configurationType, value); // This is not unsafe anymore as we have locked mutex
429 if (level == Level::Global) {
430 unsafeSetGlobally(configurationType, value, false); // Again this is not unsafe either
431 }
432 }
433
434 void Configurations::set(Configuration* conf) {
435 if (conf == nullptr) {
436 return;
437 }
438 set(conf->level(), conf->configurationType(), conf->value());
439 }
440
441 void Configurations::setToDefault(void) {
442 setGlobally(ConfigurationType::Enabled, std::string("true"), true);
443 setGlobally(ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile), true);
444 #if defined(ELPP_NO_LOG_TO_FILE)
445 setGlobally(ConfigurationType::ToFile, std::string("false"), true);
446 #else
447 setGlobally(ConfigurationType::ToFile, std::string("true"), true);
448 #endif // defined(ELPP_NO_LOG_TO_FILE)
449 setGlobally(ConfigurationType::ToStandardOutput, std::string("true"), true);
450 setGlobally(ConfigurationType::SubsecondPrecision, std::string("3"), true);
451 setGlobally(ConfigurationType::PerformanceTracking, std::string("true"), true);
452 setGlobally(ConfigurationType::MaxLogFileSize, std::string("0"), true);
453 setGlobally(ConfigurationType::LogFlushThreshold, std::string("0"), true);
454
455 setGlobally(ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"), true);
456 set(Level::Debug, ConfigurationType::Format,
457 std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg"));
458 // INFO and WARNING are set to default by Level::Global
459 set(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
460 set(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
461 set(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg"));
462 set(Level::Trace, ConfigurationType::Format, std::string("%datetime %level [%logger] [%func] [%loc] %msg"));
463 }
464
465 void Configurations::setRemainingToDefault(void) {
466 base::threading::ScopedLock scopedLock(lock());
467 #if defined(ELPP_NO_LOG_TO_FILE)
468 unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("false"));
469 #else
470 unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("true"));
471 #endif // defined(ELPP_NO_LOG_TO_FILE)
472 unsafeSetIfNotExist(Level::Global, ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile));
473 unsafeSetIfNotExist(Level::Global, ConfigurationType::ToStandardOutput, std::string("true"));
474 unsafeSetIfNotExist(Level::Global, ConfigurationType::SubsecondPrecision, std::string("3"));
475 unsafeSetIfNotExist(Level::Global, ConfigurationType::PerformanceTracking, std::string("true"));
476 unsafeSetIfNotExist(Level::Global, ConfigurationType::MaxLogFileSize, std::string("0"));
477 unsafeSetIfNotExist(Level::Global, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
478 unsafeSetIfNotExist(Level::Debug, ConfigurationType::Format,
479 std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg"));
480 // INFO and WARNING are set to default by Level::Global
481 unsafeSetIfNotExist(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
482 unsafeSetIfNotExist(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
483 unsafeSetIfNotExist(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg"));
484 unsafeSetIfNotExist(Level::Trace, ConfigurationType::Format,
485 std::string("%datetime %level [%logger] [%func] [%loc] %msg"));
486 }
487
488 bool Configurations::Parser::parseFromFile(const std::string& configurationFile, Configurations* sender,
489 Configurations* base) {
490 sender->setFromBase(base);
491 std::ifstream fileStream_(configurationFile.c_str(), std::ifstream::in);
492 ELPP_ASSERT(fileStream_.is_open(), "Unable to open configuration file [" << configurationFile << "] for parsing.");
493 bool parsedSuccessfully = false;
494 std::string line = std::string();
495 Level currLevel = Level::Unknown;
496 std::string currConfigStr = std::string();
497 std::string currLevelStr = std::string();
498 while (fileStream_.good()) {
499 std::getline(fileStream_, line);
500 parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender);
501 ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line);
502 }
503 return parsedSuccessfully;
504 }
505
506 bool Configurations::Parser::parseFromText(const std::string& configurationsString, Configurations* sender,
507 Configurations* base) {
508 sender->setFromBase(base);
509 bool parsedSuccessfully = false;
510 std::stringstream ss(configurationsString);
511 std::string line = std::string();
512 Level currLevel = Level::Unknown;
513 std::string currConfigStr = std::string();
514 std::string currLevelStr = std::string();
515 while (std::getline(ss, line)) {
516 parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender);
517 ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line);
518 }
519 return parsedSuccessfully;
520 }
521
522 void Configurations::Parser::ignoreComments(std::string* line) {
523 std::size_t foundAt = 0;
524 std::size_t quotesStart = line->find("\"");
525 std::size_t quotesEnd = std::string::npos;
526 if (quotesStart != std::string::npos) {
527 quotesEnd = line->find("\"", quotesStart + 1);
528 while (quotesEnd != std::string::npos && line->at(quotesEnd - 1) == '\\') {
529 // Do not erase slash yet - we will erase it in parseLine(..) while loop
530 quotesEnd = line->find("\"", quotesEnd + 2);
531 }
532 }
533 if ((foundAt = line->find(base::consts::kConfigurationComment)) != std::string::npos) {
534 if (foundAt < quotesEnd) {
535 foundAt = line->find(base::consts::kConfigurationComment, quotesEnd + 1);
536 }
537 *line = line->substr(0, foundAt);
538 }
539 }
540
541 bool Configurations::Parser::isLevel(const std::string& line) {
542 return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLevel));
543 }
544
545 bool Configurations::Parser::isComment(const std::string& line) {
546 return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationComment));
547 }
548
549 bool Configurations::Parser::isConfig(const std::string& line) {
550 std::size_t assignment = line.find('=');
551 return line != "" &&
552 ((line[0] >= 'A' && line[0] <= 'Z') || (line[0] >= 'a' && line[0] <= 'z')) &&
553 (assignment != std::string::npos) &&
554 (line.size() > assignment);
555 }
556
557 bool Configurations::Parser::parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr,
558 Level* currLevel,
559 Configurations* conf) {
560 ConfigurationType currConfig = ConfigurationType::Unknown;
561 std::string currValue = std::string();
562 *line = base::utils::Str::trim(*line);
563 if (isComment(*line)) return true;
564 ignoreComments(line);
565 *line = base::utils::Str::trim(*line);
566 if (line->empty()) {
567 // Comment ignored
568 return true;
569 }
570 if (isLevel(*line)) {
571 if (line->size() <= 2) {
572 return true;
573 }
574 *currLevelStr = line->substr(1, line->size() - 2);
575 *currLevelStr = base::utils::Str::toUpper(*currLevelStr);
576 *currLevelStr = base::utils::Str::trim(*currLevelStr);
577 *currLevel = LevelHelper::convertFromString(currLevelStr->c_str());
578 return true;
579 }
580 if (isConfig(*line)) {
581 std::size_t assignment = line->find('=');
582 *currConfigStr = line->substr(0, assignment);
583 *currConfigStr = base::utils::Str::toUpper(*currConfigStr);
584 *currConfigStr = base::utils::Str::trim(*currConfigStr);
585 currConfig = ConfigurationTypeHelper::convertFromString(currConfigStr->c_str());
586 currValue = line->substr(assignment + 1);
587 currValue = base::utils::Str::trim(currValue);
588 std::size_t quotesStart = currValue.find("\"", 0);
589 std::size_t quotesEnd = std::string::npos;
590 if (quotesStart != std::string::npos) {
591 quotesEnd = currValue.find("\"", quotesStart + 1);
592 while (quotesEnd != std::string::npos && currValue.at(quotesEnd - 1) == '\\') {
593 currValue = currValue.erase(quotesEnd - 1, 1);
594 quotesEnd = currValue.find("\"", quotesEnd + 2);
595 }
596 }
597 if (quotesStart != std::string::npos && quotesEnd != std::string::npos) {
598 // Quote provided - check and strip if valid
599 ELPP_ASSERT((quotesStart < quotesEnd), "Configuration error - No ending quote found in ["
600 << currConfigStr << "]");
601 ELPP_ASSERT((quotesStart + 1 != quotesEnd), "Empty configuration value for [" << currConfigStr << "]");
602 if ((quotesStart != quotesEnd) && (quotesStart + 1 != quotesEnd)) {
603 // Explicit check in case if assertion is disabled
604 currValue = currValue.substr(quotesStart + 1, quotesEnd - 1);
605 }
606 }
607 }
608 ELPP_ASSERT(*currLevel != Level::Unknown, "Unrecognized severity level [" << *currLevelStr << "]");
609 ELPP_ASSERT(currConfig != ConfigurationType::Unknown, "Unrecognized configuration [" << *currConfigStr << "]");
610 if (*currLevel == Level::Unknown || currConfig == ConfigurationType::Unknown) {
611 return false; // unrecognizable level or config
612 }
613 conf->set(*currLevel, currConfig, currValue);
614 return true;
615 }
616
617 void Configurations::unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value) {
618 Configuration* conf = RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType);
619 if (conf == nullptr) {
620 unsafeSet(level, configurationType, value);
621 }
622 }
623
624 void Configurations::unsafeSet(Level level, ConfigurationType configurationType, const std::string& value) {
625 Configuration* conf = RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType);
626 if (conf == nullptr) {
627 registerNew(new Configuration(level, configurationType, value));
628 } else {
629 conf->setValue(value);
630 }
631 if (level == Level::Global) {
632 unsafeSetGlobally(configurationType, value, false);
633 }
634 }
635
636 void Configurations::setGlobally(ConfigurationType configurationType, const std::string& value,
637 bool includeGlobalLevel) {
638 if (includeGlobalLevel) {
639 set(Level::Global, configurationType, value);
640 }
641 base::type::EnumType lIndex = LevelHelper::kMinValid;
642 LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
643 set(LevelHelper::castFromInt(lIndex), configurationType, value);
644 return false; // Do not break lambda function yet as we need to set all levels regardless
645 });
646 }
647
648 void Configurations::unsafeSetGlobally(ConfigurationType configurationType, const std::string& value,
649 bool includeGlobalLevel) {
650 if (includeGlobalLevel) {
651 unsafeSet(Level::Global, configurationType, value);
652 }
653 base::type::EnumType lIndex = LevelHelper::kMinValid;
654 LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
655 unsafeSet(LevelHelper::castFromInt(lIndex), configurationType, value);
656 return false; // Do not break lambda function yet as we need to set all levels regardless
657 });
658 }
659
660 // LogBuilder
661
662 void LogBuilder::convertToColoredOutput(base::type::string_t* logLine, Level level, Color color) {
663 if (!m_termSupportsColor) return;
664 const base::type::char_t* resetColor = ELPP_LITERAL("\x1b[0m");
665 if (color == Color::Red)
666 *logLine = ELPP_LITERAL("\x1b[1;31m") + *logLine + resetColor;
667 else if (color == Color::Yellow)
668 *logLine = ELPP_LITERAL("\x1b[1;33m") + *logLine + resetColor;
669 else if (color == Color::Green)
670 *logLine = ELPP_LITERAL("\x1b[1;32m") + *logLine + resetColor;
671 else if (color == Color::Cyan)
672 *logLine = ELPP_LITERAL("\x1b[1;36m") + *logLine + resetColor;
673 else if (color == Color::Magenta)
674 *logLine = ELPP_LITERAL("\x1b[1;35m") + *logLine + resetColor;
675 else if (color == Color::Blue)
676 *logLine = ELPP_LITERAL("\x1b[1;34m") + *logLine + resetColor;
677 else if (color == Color::Default)
678 {
679 if (level == Level::Error || level == Level::Fatal)
680 *logLine = ELPP_LITERAL("\x1b[31m") + *logLine + resetColor;
681 else if (level == Level::Warning)
682 *logLine = ELPP_LITERAL("\x1b[33m") + *logLine + resetColor;
683 else if (level == Level::Debug)
684 *logLine = ELPP_LITERAL("\x1b[32m") + *logLine + resetColor;
685 else if (level == Level::Info)
686 *logLine = ELPP_LITERAL("\x1b[36m") + *logLine + resetColor;
687 else if (level == Level::Trace)
688 *logLine = ELPP_LITERAL("\x1b[35m") + *logLine + resetColor;
689 }
690 }
691
692 void LogBuilder::setColor(Color color, bool bright) {
693 #if !ELPP_OS_WINDOWS
694 if (m_termSupportsColor)
695 #endif
696 el::base::utils::setConsoleColor(color, bright);
697 }
698
699 // Logger
700
701 Logger::Logger(const std::string& id, base::LogStreamsReferenceMap* logStreamsReference) :
702 m_id(id),
703 m_typedConfigurations(nullptr),
704 m_parentApplicationName(std::string()),
705 m_isConfigured(false),
706 m_logStreamsReference(logStreamsReference) {
707 initUnflushedCount();
708 }
709
710 Logger::Logger(const std::string& id, const Configurations& configurations,
711 base::LogStreamsReferenceMap* logStreamsReference) :
712 m_id(id),
713 m_typedConfigurations(nullptr),
714 m_parentApplicationName(std::string()),
715 m_isConfigured(false),
716 m_logStreamsReference(logStreamsReference) {
717 initUnflushedCount();
718 configure(configurations);
719 }
720
721 Logger::Logger(const Logger& logger) {
722 m_id = logger.m_id;
723 m_typedConfigurations = logger.m_typedConfigurations ? new base::TypedConfigurations(*logger.m_typedConfigurations) : nullptr;
724 m_parentApplicationName = logger.m_parentApplicationName;
725 m_isConfigured = logger.m_isConfigured;
726 m_configurations = logger.m_configurations;
727 m_unflushedCount = logger.m_unflushedCount;
728 m_logStreamsReference = logger.m_logStreamsReference;
729 }
730
731 Logger& Logger::operator=(const Logger& logger) {
732 if (&logger != this) {
733 base::utils::safeDelete(m_typedConfigurations);
734 m_id = logger.m_id;
735 m_typedConfigurations = logger.m_typedConfigurations ? new base::TypedConfigurations(*logger.m_typedConfigurations) : nullptr;
736 m_parentApplicationName = logger.m_parentApplicationName;
737 m_isConfigured = logger.m_isConfigured;
738 m_configurations = logger.m_configurations;
739 m_unflushedCount = logger.m_unflushedCount;
740 m_logStreamsReference = logger.m_logStreamsReference;
741 }
742 return *this;
743 }
744
745 void Logger::configure(const Configurations& configurations) {
746 m_isConfigured = false; // we set it to false in case if we fail
747 initUnflushedCount();
748 if (m_typedConfigurations != nullptr) {
749 Configurations* c = const_cast<Configurations*>(m_typedConfigurations->configurations());
750 if (c->hasConfiguration(Level::Global, ConfigurationType::Filename)) {
751 flush();
752 }
753 }
754 base::threading::ScopedLock scopedLock(lock());
755 if (m_configurations != configurations) {
756 m_configurations.setFromBase(const_cast<Configurations*>(&configurations));
757 }
758 base::utils::safeDelete(m_typedConfigurations);
759 m_typedConfigurations = new base::TypedConfigurations(&m_configurations, m_logStreamsReference);
760 resolveLoggerFormatSpec();
761 m_isConfigured = true;
762 }
763
764 void Logger::reconfigure(void) {
765 ELPP_INTERNAL_INFO(1, "Reconfiguring logger [" << m_id << "]");
766 configure(m_configurations);
767 }
768
769 bool Logger::isValidId(const std::string& id) {
770 for (std::string::const_iterator it = id.begin(); it != id.end(); ++it) {
771 if (!base::utils::Str::contains(base::consts::kValidLoggerIdSymbols, *it)) {
772 return false;
773 }
774 }
775 return true;
776 }
777
778 void Logger::flush(void) {
779 ELPP_INTERNAL_INFO(3, "Flushing logger [" << m_id << "] all levels");
780 base::threading::ScopedLock scopedLock(lock());
781 base::type::EnumType lIndex = LevelHelper::kMinValid;
782 LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
783 flush(LevelHelper::castFromInt(lIndex), nullptr);
784 return false;
785 });
786 }
787
788 void Logger::flush(Level level, base::type::fstream_t* fs) {
789 if (fs == nullptr && m_typedConfigurations->toFile(level)) {
790 fs = m_typedConfigurations->fileStream(level);
791 }
792 if (fs != nullptr) {
793 fs->flush();
794 std::unordered_map<Level, unsigned int>::iterator iter = m_unflushedCount.find(level);
795 if (iter != m_unflushedCount.end()) {
796 iter->second = 0;
797 }
798 Helpers::validateFileRolling(this, level);
799 }
800 }
801
802 void Logger::initUnflushedCount(void) {
803 m_unflushedCount.clear();
804 base::type::EnumType lIndex = LevelHelper::kMinValid;
805 LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
806 m_unflushedCount.insert(std::make_pair(LevelHelper::castFromInt(lIndex), 0));
807 return false;
808 });
809 }
810
811 void Logger::resolveLoggerFormatSpec(void) const {
812 base::type::EnumType lIndex = LevelHelper::kMinValid;
813 LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
814 base::LogFormat* logFormat =
815 const_cast<base::LogFormat*>(&m_typedConfigurations->logFormat(LevelHelper::castFromInt(lIndex)));
816 base::utils::Str::replaceFirstWithEscape(logFormat->m_format, base::consts::kLoggerIdFormatSpecifier, m_id);
817 return false;
818 });
819 }
820
821 // el::base
822 namespace base {
823
824 // el::base::utils
825 namespace utils {
826
827 // File
828
829 base::type::fstream_t* File::newFileStream(const std::string& filename) {
830 base::type::fstream_t *fs = new base::type::fstream_t(filename.c_str(),
831 base::type::fstream_t::out
832 #if !defined(ELPP_FRESH_LOG_FILE)
833 | base::type::fstream_t::app
834 #endif
835 );
836 #if defined(ELPP_UNICODE)
837 std::locale elppUnicodeLocale("");
838 # if ELPP_OS_WINDOWS
839 std::locale elppUnicodeLocaleWindows(elppUnicodeLocale, new std::codecvt_utf8_utf16<wchar_t>);
840 elppUnicodeLocale = elppUnicodeLocaleWindows;
841 # endif // ELPP_OS_WINDOWS
842 fs->imbue(elppUnicodeLocale);
843 #endif // defined(ELPP_UNICODE)
844 if (fs->is_open()) {
845 fs->flush();
846 } else {
847 base::utils::safeDelete(fs);
848 ELPP_INTERNAL_ERROR("Bad file [" << filename << "]", true);
849 }
850 return fs;
851 }
852
853 std::size_t File::getSizeOfFile(base::type::fstream_t* fs) {
854 if (fs == nullptr) {
855 return 0;
856 }
857 // Since the file stream is appended to or truncated, the current
858 // offset is the file size.
859 std::size_t size = static_cast<std::size_t>(fs->tellg());
860 return size;
861 }
862
863 bool File::pathExists(const char* path, bool considerFile) {
864 if (path == nullptr) {
865 return false;
866 }
867 #if ELPP_OS_UNIX
868 ELPP_UNUSED(considerFile);
869 struct stat st;
870 return (stat(path, &st) == 0);
871 #elif ELPP_OS_WINDOWS
872 DWORD fileType = GetFileAttributesA(path);
873 if (fileType == INVALID_FILE_ATTRIBUTES) {
874 return false;
875 }
876 return considerFile ? true : ((fileType & FILE_ATTRIBUTE_DIRECTORY) == 0 ? false : true);
877 #endif // ELPP_OS_UNIX
878 }
879
880 bool File::createPath(const std::string& path) {
881 if (path.empty()) {
882 return false;
883 }
884 if (base::utils::File::pathExists(path.c_str())) {
885 return true;
886 }
887 int status = -1;
888
889 char* currPath = const_cast<char*>(path.c_str());
890 std::string builtPath = std::string();
891 #if ELPP_OS_UNIX
892 if (path[0] == '/') {
893 builtPath = "/";
894 }
895 currPath = STRTOK(currPath, base::consts::kFilePathSeperator, 0);
896 #elif ELPP_OS_WINDOWS
897 // Use secure functions API
898 char* nextTok_ = nullptr;
899 currPath = STRTOK(currPath, base::consts::kFilePathSeperator, &nextTok_);
900 ELPP_UNUSED(nextTok_);
901 #endif // ELPP_OS_UNIX
902 while (currPath != nullptr) {
903 builtPath.append(currPath);
904 builtPath.append(base::consts::kFilePathSeperator);
905 #if ELPP_OS_UNIX
906 status = mkdir(builtPath.c_str(), ELPP_LOG_PERMS);
907 currPath = STRTOK(nullptr, base::consts::kFilePathSeperator, 0);
908 #elif ELPP_OS_WINDOWS
909 status = _mkdir(builtPath.c_str());
910 currPath = STRTOK(nullptr, base::consts::kFilePathSeperator, &nextTok_);
911 #endif // ELPP_OS_UNIX
912 }
913 if (status == -1) {
914 ELPP_INTERNAL_ERROR("Error while creating path [" << path << "]", true);
915 return false;
916 }
917 return true;
918 }
919
920 std::string File::extractPathFromFilename(const std::string& fullPath, const char* separator) {
921 if ((fullPath == "") || (fullPath.find(separator) == std::string::npos)) {
922 return fullPath;
923 }
924 std::size_t lastSlashAt = fullPath.find_last_of(separator);
925 if (lastSlashAt == 0) {
926 return std::string(separator);
927 }
928 return fullPath.substr(0, lastSlashAt + 1);
929 }
930
931 void File::buildStrippedFilename(const char* filename, char buff[], const std::string &commonPrefix, std::size_t limit) {
932 if (!commonPrefix.empty()) {
933 if (!strncmp(filename, commonPrefix.c_str(), commonPrefix.size()))
934 filename += commonPrefix.size();
935 }
936 std::size_t sizeOfFilename = strlen(filename);
937 if (sizeOfFilename >= limit) {
938 filename += (sizeOfFilename - limit);
939 if (filename[0] != '.' && filename[1] != '.') { // prepend if not already
940 filename += 3; // 3 = '..'
941 STRCAT(buff, "..", limit);
942 }
943 }
944 STRCAT(buff, filename, limit);
945 }
946
947 void File::buildBaseFilename(const std::string& fullPath, char buff[], std::size_t limit, const char* separator) {
948 const char *filename = fullPath.c_str();
949 std::size_t lastSlashAt = fullPath.find_last_of(separator);
950 filename += lastSlashAt ? lastSlashAt+1 : 0;
951 std::size_t sizeOfFilename = strlen(filename);
952 if (sizeOfFilename >= limit) {
953 filename += (sizeOfFilename - limit);
954 if (filename[0] != '.' && filename[1] != '.') { // prepend if not already
955 filename += 3; // 3 = '..'
956 STRCAT(buff, "..", limit);
957 }
958 }
959 STRCAT(buff, filename, limit);
960 }
961
962 // Str
963
964 bool Str::wildCardMatch(const char* str, const char* pattern) {
965 while (*pattern) {
966 switch (*pattern) {
967 case '?':
968 if (!*str)
969 return false;
970 ++str;
971 ++pattern;
972 break;
973 case '*':
974 if (wildCardMatch(str, pattern + 1))
975 return true;
976 if (*str && wildCardMatch(str + 1, pattern))
977 return true;
978 return false;
979 default:
980 if (*str++ != *pattern++)
981 return false;
982 break;
983 }
984 }
985 return !*str && !*pattern;
986 }
987
988 std::string& Str::ltrim(std::string& str) {
989 str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](char c) {
990 return !std::isspace(c);
991 } ));
992 return str;
993 }
994
995 std::string& Str::rtrim(std::string& str) {
996 str.erase(std::find_if(str.rbegin(), str.rend(), [](char c) {
997 return !std::isspace(c);
998 }).base(), str.end());
999 return str;
1000 }
1001
1002 std::string& Str::trim(std::string& str) {
1003 return ltrim(rtrim(str));
1004 }
1005
1006 bool Str::startsWith(const std::string& str, const std::string& start) {
1007 return (str.length() >= start.length()) && (str.compare(0, start.length(), start) == 0);
1008 }
1009
1010 bool Str::endsWith(const std::string& str, const std::string& end) {
1011 return (str.length() >= end.length()) && (str.compare(str.length() - end.length(), end.length(), end) == 0);
1012 }
1013
1014 std::string& Str::replaceAll(std::string& str, char replaceWhat, char replaceWith) {
1015 std::replace(str.begin(), str.end(), replaceWhat, replaceWith);
1016 return str;
1017 }
1018
1019 std::string& Str::replaceAll(std::string& str, const std::string& replaceWhat,
1020 const std::string& replaceWith) {
1021 if (replaceWhat == replaceWith)
1022 return str;
1023 std::size_t foundAt = std::string::npos;
1024 while ((foundAt = str.find(replaceWhat, foundAt + 1)) != std::string::npos) {
1025 str.replace(foundAt, replaceWhat.length(), replaceWith);
1026 }
1027 return str;
1028 }
1029
1030 void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
1031 const base::type::string_t& replaceWith) {
1032 std::size_t foundAt = base::type::string_t::npos;
1033 while ((foundAt = str.find(replaceWhat, foundAt + 1)) != base::type::string_t::npos) {
1034 if (foundAt > 0 && str[foundAt - 1] == base::consts::kFormatSpecifierChar) {
1035 str.erase(foundAt - 1, 1);
1036 ++foundAt;
1037 } else {
1038 str.replace(foundAt, replaceWhat.length(), replaceWith);
1039 return;
1040 }
1041 }
1042 }
1043 #if defined(ELPP_UNICODE)
1044 void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
1045 const std::string& replaceWith) {
1046 replaceFirstWithEscape(str, replaceWhat, base::type::string_t(replaceWith.begin(), replaceWith.end()));
1047 }
1048 #endif // defined(ELPP_UNICODE)
1049
1050 std::string& Str::toUpper(std::string& str) {
1051 std::transform(str.begin(), str.end(), str.begin(),
1052 [](char c) {
1053 return static_cast<char>(::toupper(c));
1054 });
1055 return str;
1056 }
1057
1058 bool Str::cStringEq(const char* s1, const char* s2) {
1059 if (s1 == nullptr && s2 == nullptr) return true;
1060 if (s1 == nullptr || s2 == nullptr) return false;
1061 return strcmp(s1, s2) == 0;
1062 }
1063
1064 bool Str::cStringCaseEq(const char* s1, const char* s2) {
1065 if (s1 == nullptr && s2 == nullptr) return true;
1066 if (s1 == nullptr || s2 == nullptr) return false;
1067
1068 // With thanks to cygwin for this code
1069 int d = 0;
1070
1071 while (true) {
1072 const int c1 = toupper(*s1++);
1073 const int c2 = toupper(*s2++);
1074
1075 if (((d = c1 - c2) != 0) || (c2 == '\0')) {
1076 break;
1077 }
1078 }
1079
1080 return d == 0;
1081 }
1082
1083 bool Str::contains(const char* str, char c) {
1084 for (; *str; ++str) {
1085 if (*str == c)
1086 return true;
1087 }
1088 return false;
1089 }
1090
1091 char* Str::convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded) {
1092 char localBuff[10] = "";
1093 char* p = localBuff + sizeof(localBuff) - 2;
1094 if (n > 0) {
1095 for (; n > 0 && p > localBuff && len > 0; n /= 10, --len)
1096 *--p = static_cast<char>(n % 10 + '0');
1097 } else {
1098 *--p = '0';
1099 --len;
1100 }
1101 if (zeroPadded)
1102 while (p > localBuff && len-- > 0) *--p = static_cast<char>('0');
1103 return addToBuff(p, buf, bufLim);
1104 }
1105
1106 char* Str::addToBuff(const char* str, char* buf, const char* bufLim) {
1107 while ((buf < bufLim) && ((*buf = *str++) != '\0'))
1108 ++buf;
1109 return buf;
1110 }
1111
1112 char* Str::clearBuff(char buff[], std::size_t lim) {
1113 STRCPY(buff, "", lim);
1114 ELPP_UNUSED(lim); // For *nix we dont have anything using lim in above STRCPY macro
1115 return buff;
1116 }
1117
1118 /// @brief Converst wchar* to char*
1119 /// NOTE: Need to free return value after use!
1120 char* Str::wcharPtrToCharPtr(const wchar_t* line) {
1121 std::size_t len_ = wcslen(line) + 1;
1122 char* buff_ = static_cast<char*>(malloc(len_ + 1));
1123 # if ELPP_OS_UNIX || (ELPP_OS_WINDOWS && !ELPP_CRT_DBG_WARNINGS)
1124 std::wcstombs(buff_, line, len_);
1125 # elif ELPP_OS_WINDOWS
1126 std::size_t convCount_ = 0;
1127 mbstate_t mbState_;
1128 ::memset(static_cast<void*>(&mbState_), 0, sizeof(mbState_));
1129 wcsrtombs_s(&convCount_, buff_, len_, &line, len_, &mbState_);
1130 # endif // ELPP_OS_UNIX || (ELPP_OS_WINDOWS && !ELPP_CRT_DBG_WARNINGS)
1131 return buff_;
1132 }
1133
1134 // OS
1135
1136 #if ELPP_OS_WINDOWS
1137 /// @brief Gets environment variables for Windows based OS.
1138 /// We are not using <code>getenv(const char*)</code> because of CRT deprecation
1139 /// @param varname Variable name to get environment variable value for
1140 /// @return If variable exist the value of it otherwise nullptr
1141 const char* OS::getWindowsEnvironmentVariable(const char* varname) {
1142 const DWORD bufferLen = 50;
1143 static char buffer[bufferLen];
1144 if (GetEnvironmentVariableA(varname, buffer, bufferLen)) {
1145 return buffer;
1146 }
1147 return nullptr;
1148 }
1149 #endif // ELPP_OS_WINDOWS
1150 #if ELPP_OS_ANDROID
1151 std::string OS::getProperty(const char* prop) {
1152 char propVal[PROP_VALUE_MAX + 1];
1153 int ret = __system_property_get(prop, propVal);
1154 return ret == 0 ? std::string() : std::string(propVal);
1155 }
1156
1157 std::string OS::getDeviceName(void) {
1158 std::stringstream ss;
1159 std::string manufacturer = getProperty("ro.product.manufacturer");
1160 std::string model = getProperty("ro.product.model");
1161 if (manufacturer.empty() || model.empty()) {
1162 return std::string();
1163 }
1164 ss << manufacturer << "-" << model;
1165 return ss.str();
1166 }
1167 #endif // ELPP_OS_ANDROID
1168
1169 const std::string OS::getBashOutput(const char* command) {
1170 #if (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN)
1171 if (command == nullptr) {
1172 return std::string();
1173 }
1174 FILE* proc = nullptr;
1175 if ((proc = popen(command, "r")) == nullptr) {
1176 ELPP_INTERNAL_ERROR("\nUnable to run command [" << command << "]", true);
1177 return std::string();
1178 }
1179 char hBuff[4096];
1180 if (fgets(hBuff, sizeof(hBuff), proc) != nullptr) {
1181 pclose(proc);
1182 const std::size_t buffLen = strlen(hBuff);
1183 if (buffLen > 0 && hBuff[buffLen - 1] == '\n') {
1184 hBuff[buffLen- 1] = '\0';
1185 }
1186 return std::string(hBuff);
1187 } else {
1188 pclose(proc);
1189 }
1190 return std::string();
1191 #else
1192 ELPP_UNUSED(command);
1193 return std::string();
1194 #endif // (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN)
1195 }
1196
1197 std::string OS::getEnvironmentVariable(const char* variableName, const char* defaultVal,
1198 const char* alternativeBashCommand) {
1199 #if ELPP_OS_UNIX
1200 const char* val = getenv(variableName);
1201 #elif ELPP_OS_WINDOWS
1202 const char* val = getWindowsEnvironmentVariable(variableName);
1203 #endif // ELPP_OS_UNIX
1204 if ((val == nullptr) || ((strcmp(val, "") == 0))) {
1205 #if ELPP_OS_UNIX && defined(ELPP_FORCE_ENV_VAR_FROM_BASH)
1206 // Try harder on unix-based systems
1207 std::string valBash = base::utils::OS::getBashOutput(alternativeBashCommand);
1208 if (valBash.empty()) {
1209 return std::string(defaultVal);
1210 } else {
1211 return valBash;
1212 }
1213 #elif ELPP_OS_WINDOWS || ELPP_OS_UNIX
1214 ELPP_UNUSED(alternativeBashCommand);
1215 return std::string(defaultVal);
1216 #endif // ELPP_OS_UNIX && defined(ELPP_FORCE_ENV_VAR_FROM_BASH)
1217 }
1218 return std::string(val);
1219 }
1220
1221 std::string OS::currentUser(void) {
1222 #if ELPP_OS_UNIX && !ELPP_OS_ANDROID
1223 return getEnvironmentVariable("USER", base::consts::kUnknownUser, "whoami");
1224 #elif ELPP_OS_WINDOWS
1225 return getEnvironmentVariable("USERNAME", base::consts::kUnknownUser);
1226 #elif ELPP_OS_ANDROID
1227 ELPP_UNUSED(base::consts::kUnknownUser);
1228 return std::string("android");
1229 #else
1230 return std::string();
1231 #endif // ELPP_OS_UNIX && !ELPP_OS_ANDROID
1232 }
1233
1234 std::string OS::currentHost(void) {
1235 #if ELPP_OS_UNIX && !ELPP_OS_ANDROID
1236 return getEnvironmentVariable("HOSTNAME", base::consts::kUnknownHost, "hostname");
1237 #elif ELPP_OS_WINDOWS
1238 return getEnvironmentVariable("COMPUTERNAME", base::consts::kUnknownHost);
1239 #elif ELPP_OS_ANDROID
1240 ELPP_UNUSED(base::consts::kUnknownHost);
1241 return getDeviceName();
1242 #else
1243 return std::string();
1244 #endif // ELPP_OS_UNIX && !ELPP_OS_ANDROID
1245 }
1246
1247 static bool endswith(const std::string &s, const std::string &ending)
1248 {
1249 return s.size() >= ending.size() && s.substr(s.size() - ending.size()) == ending;
1250 }
1251
1252 bool OS::termSupportsColor(std::string& term) {
1253 return term == "xterm" || term == "screen" || term == "linux" || term == "cygwin"
1254 || endswith(term, "-color") || endswith(term, "-256color");
1255 }
1256
1257 bool OS::termSupportsColor(void) {
1258 std::string term = getEnvironmentVariable("TERM", "");
1259 return termSupportsColor(term);
1260 }
1261
1262 // DateTime
1263
1264 void DateTime::gettimeofday(struct timeval* tv) {
1265 #if ELPP_OS_WINDOWS
1266 if (tv != nullptr) {
1267 # if ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS)
1268 const unsigned __int64 delta_ = 11644473600000000Ui64;
1269 # else
1270 const unsigned __int64 delta_ = 11644473600000000ULL;
1271 # endif // ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS)
1272 const double secOffSet = 0.000001;
1273 const unsigned long usecOffSet = 1000000;
1274 FILETIME fileTime;
1275 GetSystemTimeAsFileTime(&fileTime);
1276 unsigned __int64 present = 0;
1277 present |= fileTime.dwHighDateTime;
1278 present = present << 32;
1279 present |= fileTime.dwLowDateTime;
1280 present /= 10; // mic-sec
1281 // Subtract the difference
1282 present -= delta_;
1283 tv->tv_sec = static_cast<long>(present * secOffSet);
1284 tv->tv_usec = static_cast<long>(present % usecOffSet);
1285 }
1286 #else
1287 ::gettimeofday(tv, nullptr);
1288 #endif // ELPP_OS_WINDOWS
1289 }
1290
1291 std::string DateTime::getDateTime(const char* format, const base::SubsecondPrecision* ssPrec) {
1292 struct timeval currTime;
1293 gettimeofday(&currTime);
1294 return timevalToString(currTime, format, ssPrec);
1295 }
1296
1297 std::string DateTime::timevalToString(struct timeval tval, const char* format,
1298 const el::base::SubsecondPrecision* ssPrec) {
1299 struct ::tm timeInfo;
1300 buildTimeInfo(&tval, &timeInfo);
1301 const int kBuffSize = 30;
1302 char buff_[kBuffSize] = "";
1303 parseFormat(buff_, kBuffSize, format, &timeInfo, static_cast<std::size_t>(tval.tv_usec / ssPrec->m_offset),
1304 ssPrec);
1305 return std::string(buff_);
1306 }
1307
1308 base::type::string_t DateTime::formatTime(unsigned long long time, base::TimestampUnit timestampUnit) {
1309 base::type::EnumType start = static_cast<base::type::EnumType>(timestampUnit);
1310 const base::type::char_t* unit = base::consts::kTimeFormats[start].unit;
1311 for (base::type::EnumType i = start; i < base::consts::kTimeFormatsCount - 1; ++i) {
1312 if (time <= base::consts::kTimeFormats[i].value) {
1313 break;
1314 }
1315 if (base::consts::kTimeFormats[i].value == 1000.0f && time / 1000.0f < 1.9f) {
1316 break;
1317 }
1318 time /= static_cast<decltype(time)>(base::consts::kTimeFormats[i].value);
1319 unit = base::consts::kTimeFormats[i + 1].unit;
1320 }
1321 base::type::stringstream_t ss;
1322 ss << time << " " << unit;
1323 return ss.str();
1324 }
1325
1326 unsigned long long DateTime::getTimeDifference(const struct timeval& endTime, const struct timeval& startTime,
1327 base::TimestampUnit timestampUnit) {
1328 if (timestampUnit == base::TimestampUnit::Microsecond) {
1329 return static_cast<unsigned long long>(static_cast<unsigned long long>(1000000 * endTime.tv_sec + endTime.tv_usec) -
1330 static_cast<unsigned long long>(1000000 * startTime.tv_sec + startTime.tv_usec));
1331 }
1332 // milliseconds
1333 auto conv = [](const struct timeval& tim) {
1334 return static_cast<unsigned long long>((tim.tv_sec * 1000) + (tim.tv_usec / 1000));
1335 };
1336 return static_cast<unsigned long long>(conv(endTime) - conv(startTime));
1337 }
1338
1339 struct ::tm* DateTime::buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo) {
1340 #if ELPP_OS_UNIX
1341 time_t rawTime = currTime->tv_sec;
1342 ::elpptime_r(&rawTime, timeInfo);
1343 return timeInfo;
1344 #else
1345 # if ELPP_COMPILER_MSVC
1346 ELPP_UNUSED(currTime);
1347 time_t t;
1348 # if defined(_USE_32BIT_TIME_T)
1349 _time32(&t);
1350 # else
1351 _time64(&t);
1352 # endif
1353 elpptime_s(timeInfo, &t);
1354 return timeInfo;
1355 # else
1356 // For any other compilers that don't have CRT warnings issue e.g, MinGW or TDM GCC- we use different method
1357 time_t rawTime = currTime->tv_sec;
1358 struct tm* tmInf = elpptime(&rawTime);
1359 *timeInfo = *tmInf;
1360 return timeInfo;
1361 # endif // ELPP_COMPILER_MSVC
1362 #endif // ELPP_OS_UNIX
1363 }
1364
1365 char* DateTime::parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo,
1366 std::size_t msec, const base::SubsecondPrecision* ssPrec) {
1367 const char* bufLim = buf + bufSz;
1368 for (; *format; ++format) {
1369 if (*format == base::consts::kFormatSpecifierChar) {
1370 switch (*++format) {
1371 case base::consts::kFormatSpecifierChar: // Escape
1372 break;
1373 case '\0': // End
1374 --format;
1375 break;
1376 case 'd': // Day
1377 buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mday, 2, buf, bufLim);
1378 continue;
1379 case 'a': // Day of week (short)
1380 buf = base::utils::Str::addToBuff(base::consts::kDaysAbbrev[tInfo->tm_wday], buf, bufLim);
1381 continue;
1382 case 'A': // Day of week (long)
1383 buf = base::utils::Str::addToBuff(base::consts::kDays[tInfo->tm_wday], buf, bufLim);
1384 continue;
1385 case 'M': // month
1386 buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mon + 1, 2, buf, bufLim);
1387 continue;
1388 case 'b': // month (short)
1389 buf = base::utils::Str::addToBuff(base::consts::kMonthsAbbrev[tInfo->tm_mon], buf, bufLim);
1390 continue;
1391 case 'B': // month (long)
1392 buf = base::utils::Str::addToBuff(base::consts::kMonths[tInfo->tm_mon], buf, bufLim);
1393 continue;
1394 case 'y': // year (two digits)
1395 buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 2, buf, bufLim);
1396 continue;
1397 case 'Y': // year (four digits)
1398 buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 4, buf, bufLim);
1399 continue;
1400 case 'h': // hour (12-hour)
1401 buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour % 12, 2, buf, bufLim);
1402 continue;
1403 case 'H': // hour (24-hour)
1404 buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour, 2, buf, bufLim);
1405 continue;
1406 case 'm': // minute
1407 buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_min, 2, buf, bufLim);
1408 continue;
1409 case 's': // second
1410 buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_sec, 2, buf, bufLim);
1411 continue;
1412 case 'z': // subsecond part
1413 case 'g':
1414 buf = base::utils::Str::convertAndAddToBuff(msec, ssPrec->m_width, buf, bufLim);
1415 continue;
1416 case 'F': // AM/PM
1417 buf = base::utils::Str::addToBuff((tInfo->tm_hour >= 12) ? base::consts::kPm : base::consts::kAm, buf, bufLim);
1418 continue;
1419 default:
1420 continue;
1421 }
1422 }
1423 if (buf == bufLim) break;
1424 *buf++ = *format;
1425 }
1426 return buf;
1427 }
1428
1429 // CommandLineArgs
1430
1431 void CommandLineArgs::setArgs(int argc, char** argv) {
1432 m_params.clear();
1433 m_paramsWithValue.clear();
1434 if (argc == 0 || argv == nullptr) {
1435 return;
1436 }
1437 m_argc = argc;
1438 m_argv = argv;
1439 for (int i = 1; i < m_argc; ++i) {
1440 const char* v = (strstr(m_argv[i], "="));
1441 if (v != nullptr && strlen(v) > 0) {
1442 std::string key = std::string(m_argv[i]);
1443 key = key.substr(0, key.find_first_of('='));
1444 if (hasParamWithValue(key.c_str())) {
1445 ELPP_INTERNAL_INFO(1, "Skipping [" << key << "] arg since it already has value ["
1446 << getParamValue(key.c_str()) << "]");
1447 } else {
1448 m_paramsWithValue.insert(std::make_pair(key, std::string(v + 1)));
1449 }
1450 }
1451 if (v == nullptr) {
1452 if (hasParam(m_argv[i])) {
1453 ELPP_INTERNAL_INFO(1, "Skipping [" << m_argv[i] << "] arg since it already exists");
1454 } else {
1455 m_params.push_back(std::string(m_argv[i]));
1456 }
1457 }
1458 }
1459 }
1460
1461 bool CommandLineArgs::hasParamWithValue(const char* paramKey) const {
1462 return m_paramsWithValue.find(std::string(paramKey)) != m_paramsWithValue.end();
1463 }
1464
1465 const char* CommandLineArgs::getParamValue(const char* paramKey) const {
1466 std::unordered_map<std::string, std::string>::const_iterator iter = m_paramsWithValue.find(std::string(paramKey));
1467 return iter != m_paramsWithValue.end() ? iter->second.c_str() : "";
1468 }
1469
1470 bool CommandLineArgs::hasParam(const char* paramKey) const {
1471 return std::find(m_params.begin(), m_params.end(), std::string(paramKey)) != m_params.end();
1472 }
1473
1474 bool CommandLineArgs::empty(void) const {
1475 return m_params.empty() && m_paramsWithValue.empty();
1476 }
1477
1478 std::size_t CommandLineArgs::size(void) const {
1479 return m_params.size() + m_paramsWithValue.size();
1480 }
1481
1482 base::type::ostream_t& operator<<(base::type::ostream_t& os, const CommandLineArgs& c) {
1483 for (int i = 1; i < c.m_argc; ++i) {
1484 os << ELPP_LITERAL("[") << c.m_argv[i] << ELPP_LITERAL("]");
1485 if (i < c.m_argc - 1) {
1486 os << ELPP_LITERAL(" ");
1487 }
1488 }
1489 return os;
1490 }
1491
1492 } // namespace utils
1493
1494 // el::base::threading
1495 namespace threading {
1496
1497 #if ELPP_THREADING_ENABLED
1498 # if ELPP_USE_STD_THREADING
1499 # if ELPP_ASYNC_LOGGING
1500 static void msleep(int ms) {
1501 // Only when async logging enabled - this is because async is strict on compiler
1502 # if defined(ELPP_NO_SLEEP_FOR)
1503 usleep(ms * 1000);
1504 # else
1505 std::this_thread::sleep_for(std::chrono::milliseconds(ms));
1506 # endif // defined(ELPP_NO_SLEEP_FOR)
1507 }
1508 # endif // ELPP_ASYNC_LOGGING
1509 # endif // !ELPP_USE_STD_THREADING
1510 #endif // ELPP_THREADING_ENABLED
1511
1512 } // namespace threading
1513
1514 // el::base
1515
1516 // SubsecondPrecision
1517
1518 void SubsecondPrecision::init(int width) {
1519 if (width < 1 || width > 6) {
1520 width = base::consts::kDefaultSubsecondPrecision;
1521 }
1522 m_width = width;
1523 switch (m_width) {
1524 case 3:
1525 m_offset = 1000;
1526 break;
1527 case 4:
1528 m_offset = 100;
1529 break;
1530 case 5:
1531 m_offset = 10;
1532 break;
1533 case 6:
1534 m_offset = 1;
1535 break;
1536 default:
1537 m_offset = 1000;
1538 break;
1539 }
1540 }
1541
1542 // LogFormat
1543
1544 LogFormat::LogFormat(void) :
1545 m_level(Level::Unknown),
1546 m_userFormat(base::type::string_t()),
1547 m_format(base::type::string_t()),
1548 m_dateTimeFormat(std::string()),
1549 m_flags(0x0),
1550 m_currentUser(base::utils::OS::currentUser()),
1551 m_currentHost(base::utils::OS::currentHost()) {
1552 }
1553
1554 LogFormat::LogFormat(Level level, const base::type::string_t& format)
1555 : m_level(level), m_userFormat(format), m_currentUser(base::utils::OS::currentUser()),
1556 m_currentHost(base::utils::OS::currentHost()) {
1557 parseFromFormat(m_userFormat);
1558 }
1559
1560 LogFormat::LogFormat(const LogFormat& logFormat):
1561 m_level(logFormat.m_level),
1562 m_userFormat(logFormat.m_userFormat),
1563 m_format(logFormat.m_format),
1564 m_dateTimeFormat(logFormat.m_dateTimeFormat),
1565 m_flags(logFormat.m_flags),
1566 m_currentUser(logFormat.m_currentUser),
1567 m_currentHost(logFormat.m_currentHost) {
1568 }
1569
1570 LogFormat::LogFormat(LogFormat&& logFormat) {
1571 m_level = std::move(logFormat.m_level);
1572 m_userFormat = std::move(logFormat.m_userFormat);
1573 m_format = std::move(logFormat.m_format);
1574 m_dateTimeFormat = std::move(logFormat.m_dateTimeFormat);
1575 m_flags = std::move(logFormat.m_flags);
1576 m_currentUser = std::move(logFormat.m_currentUser);
1577 m_currentHost = std::move(logFormat.m_currentHost);
1578 }
1579
1580 LogFormat& LogFormat::operator=(const LogFormat& logFormat) {
1581 if (&logFormat != this) {
1582 m_level = logFormat.m_level;
1583 m_userFormat = logFormat.m_userFormat;
1584 m_dateTimeFormat = logFormat.m_dateTimeFormat;
1585 m_flags = logFormat.m_flags;
1586 m_currentUser = logFormat.m_currentUser;
1587 m_currentHost = logFormat.m_currentHost;
1588 }
1589 return *this;
1590 }
1591
1592 bool LogFormat::operator==(const LogFormat& other) {
1593 return m_level == other.m_level && m_userFormat == other.m_userFormat && m_format == other.m_format &&
1594 m_dateTimeFormat == other.m_dateTimeFormat && m_flags == other.m_flags;
1595 }
1596
1597 /// @brief Updates format to be used while logging.
1598 /// @param userFormat User provided format
1599 void LogFormat::parseFromFormat(const base::type::string_t& userFormat) {
1600 // We make copy because we will be changing the format
1601 // i.e, removing user provided date format from original format
1602 // and then storing it.
1603 base::type::string_t formatCopy = userFormat;
1604 m_flags = 0x0;
1605 auto conditionalAddFlag = [&](const base::type::char_t* specifier, base::FormatFlags flag) {
1606 std::size_t foundAt = base::type::string_t::npos;
1607 while ((foundAt = formatCopy.find(specifier, foundAt + 1)) != base::type::string_t::npos) {
1608 if (foundAt > 0 && formatCopy[foundAt - 1] == base::consts::kFormatSpecifierChar) {
1609 if (hasFlag(flag)) {
1610 // If we already have flag we remove the escape chars so that '%%' is turned to '%'
1611 // even after specifier resolution - this is because we only replaceFirst specifier
1612 formatCopy.erase(foundAt - 1, 1);
1613 ++foundAt;
1614 }
1615 } else {
1616 if (!hasFlag(flag)) addFlag(flag);
1617 }
1618 }
1619 };
1620 conditionalAddFlag(base::consts::kAppNameFormatSpecifier, base::FormatFlags::AppName);
1621 conditionalAddFlag(base::consts::kSeverityLevelFormatSpecifier, base::FormatFlags::Level);
1622 conditionalAddFlag(base::consts::kSeverityLevelShortFormatSpecifier, base::FormatFlags::LevelShort);
1623 conditionalAddFlag(base::consts::kLoggerIdFormatSpecifier, base::FormatFlags::LoggerId);
1624 conditionalAddFlag(base::consts::kThreadIdFormatSpecifier, base::FormatFlags::ThreadId);
1625 conditionalAddFlag(base::consts::kLogFileFormatSpecifier, base::FormatFlags::File);
1626 conditionalAddFlag(base::consts::kLogFileBaseFormatSpecifier, base::FormatFlags::FileBase);
1627 conditionalAddFlag(base::consts::kLogLineFormatSpecifier, base::FormatFlags::Line);
1628 conditionalAddFlag(base::consts::kLogLocationFormatSpecifier, base::FormatFlags::Location);
1629 conditionalAddFlag(base::consts::kLogFunctionFormatSpecifier, base::FormatFlags::Function);
1630 conditionalAddFlag(base::consts::kCurrentUserFormatSpecifier, base::FormatFlags::User);
1631 conditionalAddFlag(base::consts::kCurrentHostFormatSpecifier, base::FormatFlags::Host);
1632 conditionalAddFlag(base::consts::kMessageFormatSpecifier, base::FormatFlags::LogMessage);
1633 conditionalAddFlag(base::consts::kVerboseLevelFormatSpecifier, base::FormatFlags::VerboseLevel);
1634 // For date/time we need to extract user's date format first
1635 std::size_t dateIndex = std::string::npos;
1636 if ((dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier)) != std::string::npos) {
1637 while (dateIndex > 0 && formatCopy[dateIndex - 1] == base::consts::kFormatSpecifierChar) {
1638 dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier, dateIndex + 1);
1639 }
1640 if (dateIndex != std::string::npos) {
1641 addFlag(base::FormatFlags::DateTime);
1642 updateDateFormat(dateIndex, formatCopy);
1643 }
1644 }
1645 m_format = formatCopy;
1646 updateFormatSpec();
1647 }
1648
1649 void LogFormat::updateDateFormat(std::size_t index, base::type::string_t& currFormat) {
1650 if (hasFlag(base::FormatFlags::DateTime)) {
1651 index += ELPP_STRLEN(base::consts::kDateTimeFormatSpecifier);
1652 }
1653 const base::type::char_t* ptr = currFormat.c_str() + index;
1654 if ((currFormat.size() > index) && (ptr[0] == '{')) {
1655 // User has provided format for date/time
1656 ++ptr;
1657 int count = 1; // Start by 1 in order to remove starting brace
1658 std::stringstream ss;
1659 for (; *ptr; ++ptr, ++count) {
1660 if (*ptr == '}') {
1661 ++count; // In order to remove ending brace
1662 break;
1663 }
1664 ss << static_cast<char>(*ptr);
1665 }
1666 currFormat.erase(index, count);
1667 m_dateTimeFormat = ss.str();
1668 } else {
1669 // No format provided, use default
1670 if (hasFlag(base::FormatFlags::DateTime)) {
1671 m_dateTimeFormat = std::string(base::consts::kDefaultDateTimeFormat);
1672 }
1673 }
1674 }
1675
1676 void LogFormat::updateFormatSpec(void) {
1677 // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet.
1678 if (m_level == Level::Debug) {
1679 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
1680 base::consts::kDebugLevelLogValue);
1681 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
1682 base::consts::kDebugLevelShortLogValue);
1683 } else if (m_level == Level::Info) {
1684 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
1685 base::consts::kInfoLevelLogValue);
1686 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
1687 base::consts::kInfoLevelShortLogValue);
1688 } else if (m_level == Level::Warning) {
1689 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
1690 base::consts::kWarningLevelLogValue);
1691 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
1692 base::consts::kWarningLevelShortLogValue);
1693 } else if (m_level == Level::Error) {
1694 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
1695 base::consts::kErrorLevelLogValue);
1696 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
1697 base::consts::kErrorLevelShortLogValue);
1698 } else if (m_level == Level::Fatal) {
1699 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
1700 base::consts::kFatalLevelLogValue);
1701 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
1702 base::consts::kFatalLevelShortLogValue);
1703 } else if (m_level == Level::Verbose) {
1704 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
1705 base::consts::kVerboseLevelLogValue);
1706 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
1707 base::consts::kVerboseLevelShortLogValue);
1708 } else if (m_level == Level::Trace) {
1709 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
1710 base::consts::kTraceLevelLogValue);
1711 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
1712 base::consts::kTraceLevelShortLogValue);
1713 }
1714 if (hasFlag(base::FormatFlags::User)) {
1715 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentUserFormatSpecifier,
1716 m_currentUser);
1717 }
1718 if (hasFlag(base::FormatFlags::Host)) {
1719 base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentHostFormatSpecifier,
1720 m_currentHost);
1721 }
1722 // Ignore Level::Global and Level::Unknown
1723 }
1724
1725 // TypedConfigurations
1726
1727 TypedConfigurations::TypedConfigurations(Configurations* configurations,
1728 base::LogStreamsReferenceMap* logStreamsReference) {
1729 m_configurations = configurations;
1730 m_logStreamsReference = logStreamsReference;
1731 build(m_configurations);
1732 }
1733
1734 TypedConfigurations::TypedConfigurations(const TypedConfigurations& other) {
1735 this->m_configurations = other.m_configurations;
1736 this->m_logStreamsReference = other.m_logStreamsReference;
1737 build(m_configurations);
1738 }
1739
1740 bool TypedConfigurations::enabled(Level level) {
1741 return getConfigByVal<bool>(level, &m_enabledMap, "enabled");
1742 }
1743
1744 bool TypedConfigurations::toFile(Level level) {
1745 return getConfigByVal<bool>(level, &m_toFileMap, "toFile");
1746 }
1747
1748 const std::string& TypedConfigurations::filename(Level level) {
1749 return getConfigByRef<std::string>(level, &m_filenameMap, "filename");
1750 }
1751
1752 bool TypedConfigurations::toStandardOutput(Level level) {
1753 return getConfigByVal<bool>(level, &m_toStandardOutputMap, "toStandardOutput");
1754 }
1755
1756 const base::LogFormat& TypedConfigurations::logFormat(Level level) {
1757 return getConfigByRef<base::LogFormat>(level, &m_logFormatMap, "logFormat");
1758 }
1759
1760 const base::SubsecondPrecision& TypedConfigurations::subsecondPrecision(Level level) {
1761 return getConfigByRef<base::SubsecondPrecision>(level, &m_subsecondPrecisionMap, "subsecondPrecision");
1762 }
1763
1764 const base::MillisecondsWidth& TypedConfigurations::millisecondsWidth(Level level) {
1765 return getConfigByRef<base::MillisecondsWidth>(level, &m_subsecondPrecisionMap, "millisecondsWidth");
1766 }
1767
1768 bool TypedConfigurations::performanceTracking(Level level) {
1769 return getConfigByVal<bool>(level, &m_performanceTrackingMap, "performanceTracking");
1770 }
1771
1772 base::type::fstream_t* TypedConfigurations::fileStream(Level level) {
1773 return getConfigByRef<base::FileStreamPtr>(level, &m_fileStreamMap, "fileStream").get();
1774 }
1775
1776 std::size_t TypedConfigurations::maxLogFileSize(Level level) {
1777 return getConfigByVal<std::size_t>(level, &m_maxLogFileSizeMap, "maxLogFileSize");
1778 }
1779
1780 std::size_t TypedConfigurations::logFlushThreshold(Level level) {
1781 return getConfigByVal<std::size_t>(level, &m_logFlushThresholdMap, "logFlushThreshold");
1782 }
1783
1784 void TypedConfigurations::build(Configurations* configurations) {
1785 base::threading::ScopedLock scopedLock(lock());
1786 auto getBool = [] (std::string boolStr) -> bool { // Pass by value for trimming
1787 base::utils::Str::trim(boolStr);
1788 return (boolStr == "TRUE" || boolStr == "true" || boolStr == "1");
1789 };
1790 setValue(Level::Global, base::FileStreamPtr(NULL), &m_fileStreamMap);
1791 std::vector<Configuration*> withFileSizeLimit;
1792 for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) {
1793 Configuration* conf = *it;
1794 // We cannot use switch on strong enums because Intel C++ dont support them yet
1795 if (conf->configurationType() == ConfigurationType::Enabled) {
1796 setValue(conf->level(), getBool(conf->value()), &m_enabledMap);
1797 } else if (conf->configurationType() == ConfigurationType::ToFile) {
1798 setValue(conf->level(), getBool(conf->value()), &m_toFileMap);
1799 } else if (conf->configurationType() == ConfigurationType::ToStandardOutput) {
1800 setValue(conf->level(), getBool(conf->value()), &m_toStandardOutputMap);
1801 } else if (conf->configurationType() == ConfigurationType::Filename) {
1802 // We do not yet configure filename but we will configure in another
1803 // loop. This is because if file cannot be created, we will force ToFile
1804 // to be false. Because configuring logger is not necessarily performance
1805 // sensative operation, we can live with another loop; (by the way this loop
1806 // is not very heavy either)
1807 } else if (conf->configurationType() == ConfigurationType::Format) {
1808 setValue(conf->level(), base::LogFormat(conf->level(),
1809 base::type::string_t(conf->value().begin(), conf->value().end())), &m_logFormatMap);
1810 } else if (conf->configurationType() == ConfigurationType::SubsecondPrecision) {
1811 setValue(Level::Global,
1812 base::SubsecondPrecision(static_cast<int>(getULong(conf->value()))), &m_subsecondPrecisionMap);
1813 } else if (conf->configurationType() == ConfigurationType::PerformanceTracking) {
1814 setValue(Level::Global, getBool(conf->value()), &m_performanceTrackingMap);
1815 } else if (conf->configurationType() == ConfigurationType::MaxLogFileSize) {
1816 auto v = getULong(conf->value());
1817 setValue(conf->level(), static_cast<std::size_t>(v), &m_maxLogFileSizeMap);
1818 if (v != 0) {
1819 withFileSizeLimit.push_back(conf);
1820 }
1821 } else if (conf->configurationType() == ConfigurationType::LogFlushThreshold) {
1822 setValue(conf->level(), static_cast<std::size_t>(getULong(conf->value())), &m_logFlushThresholdMap);
1823 }
1824 }
1825 // As mentioned earlier, we will now set filename configuration in separate loop to deal with non-existent files
1826 for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) {
1827 Configuration* conf = *it;
1828 if (conf->configurationType() == ConfigurationType::Filename) {
1829 insertFile(conf->level(), conf->value());
1830 }
1831 }
1832 for (std::vector<Configuration*>::iterator conf = withFileSizeLimit.begin();
1833 conf != withFileSizeLimit.end(); ++conf) {
1834 // This is not unsafe as mutex is locked in currect scope
1835 unsafeValidateFileRolling((*conf)->level(), base::defaultPreRollOutCallback);
1836 }
1837 }
1838
1839 unsigned long TypedConfigurations::getULong(std::string confVal) {
1840 bool valid = true;
1841 base::utils::Str::trim(confVal);
1842 valid = !confVal.empty() && std::find_if(confVal.begin(), confVal.end(),
1843 [](char c) {
1844 return !base::utils::Str::isDigit(c);
1845 }) == confVal.end();
1846 if (!valid) {
1847 valid = false;
1848 ELPP_ASSERT(valid, "Configuration value not a valid integer [" << confVal << "]");
1849 return 0;
1850 }
1851 return atol(confVal.c_str());
1852 }
1853
1854 std::string TypedConfigurations::resolveFilename(const std::string& filename) {
1855 std::string resultingFilename = filename;
1856 std::size_t dateIndex = std::string::npos;
1857 std::string dateTimeFormatSpecifierStr = std::string(base::consts::kDateTimeFormatSpecifierForFilename);
1858 if ((dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str())) != std::string::npos) {
1859 while (dateIndex > 0 && resultingFilename[dateIndex - 1] == base::consts::kFormatSpecifierChar) {
1860 dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str(), dateIndex + 1);
1861 }
1862 if (dateIndex != std::string::npos) {
1863 const char* ptr = resultingFilename.c_str() + dateIndex;
1864 // Goto end of specifier
1865 ptr += dateTimeFormatSpecifierStr.size();
1866 std::string fmt;
1867 if ((resultingFilename.size() > dateIndex) && (ptr[0] == '{')) {
1868 // User has provided format for date/time
1869 ++ptr;
1870 int count = 1; // Start by 1 in order to remove starting brace
1871 std::stringstream ss;
1872 for (; *ptr; ++ptr, ++count) {
1873 if (*ptr == '}') {
1874 ++count; // In order to remove ending brace
1875 break;
1876 }
1877 ss << *ptr;
1878 }
1879 resultingFilename.erase(dateIndex + dateTimeFormatSpecifierStr.size(), count);
1880 fmt = ss.str();
1881 } else {
1882 fmt = std::string(base::consts::kDefaultDateTimeFormatInFilename);
1883 }
1884 base::SubsecondPrecision ssPrec(3);
1885 std::string now = base::utils::DateTime::getDateTime(fmt.c_str(), &ssPrec);
1886 base::utils::Str::replaceAll(now, '/', '-'); // Replace path element since we are dealing with filename
1887 base::utils::Str::replaceAll(resultingFilename, dateTimeFormatSpecifierStr, now);
1888 }
1889 }
1890 return resultingFilename;
1891 }
1892
1893 void TypedConfigurations::insertFile(Level level, const std::string& fullFilename) {
1894 if (fullFilename.empty())
1895 return;
1896 std::string resolvedFilename = resolveFilename(fullFilename);
1897 if (resolvedFilename.empty()) {
1898 std::cerr << "Could not load empty file for logging, please re-check your configurations for level ["
1899 << LevelHelper::convertToString(level) << "]";
1900 }
1901 std::string filePath = base::utils::File::extractPathFromFilename(resolvedFilename, base::consts::kFilePathSeperator);
1902 if (filePath.size() < resolvedFilename.size()) {
1903 base::utils::File::createPath(filePath);
1904 }
1905 auto create = [&](Level level) {
1906 base::LogStreamsReferenceMap::iterator filestreamIter = m_logStreamsReference->find(resolvedFilename);
1907 base::type::fstream_t* fs = nullptr;
1908 if (filestreamIter == m_logStreamsReference->end()) {
1909 // We need a completely new stream, nothing to share with
1910 fs = base::utils::File::newFileStream(resolvedFilename);
1911 m_filenameMap.insert(std::make_pair(level, resolvedFilename));
1912 m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(fs)));
1913 m_logStreamsReference->insert(std::make_pair(resolvedFilename, base::FileStreamPtr(m_fileStreamMap.at(level))));
1914 } else {
1915 // Woops! we have an existing one, share it!
1916 m_filenameMap.insert(std::make_pair(level, filestreamIter->first));
1917 m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(filestreamIter->second)));
1918 fs = filestreamIter->second.get();
1919 }
1920 if (fs == nullptr) {
1921 // We display bad file error from newFileStream()
1922 ELPP_INTERNAL_ERROR("Setting [TO_FILE] of ["
1923 << LevelHelper::convertToString(level) << "] to FALSE", false);
1924 setValue(level, false, &m_toFileMap);
1925 }
1926 };
1927 // If we dont have file conf for any level, create it for Level::Global first
1928 // otherwise create for specified level
1929 create(m_filenameMap.empty() && m_fileStreamMap.empty() ? Level::Global : level);
1930 }
1931
1932 bool TypedConfigurations::unsafeValidateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback) {
1933 base::type::fstream_t* fs = unsafeGetConfigByRef(level, &m_fileStreamMap, "fileStream").get();
1934 if (fs == nullptr) {
1935 return true;
1936 }
1937 std::size_t maxLogFileSize = unsafeGetConfigByVal(level, &m_maxLogFileSizeMap, "maxLogFileSize");
1938 std::size_t currFileSize = base::utils::File::getSizeOfFile(fs);
1939 if (maxLogFileSize != 0 && currFileSize >= maxLogFileSize) {
1940 std::string fname = unsafeGetConfigByRef(level, &m_filenameMap, "filename");
1941 ELPP_INTERNAL_INFO(1, "Truncating log file [" << fname << "] as a result of configurations for level ["
1942 << LevelHelper::convertToString(level) << "]");
1943 fs->close();
1944 preRollOutCallback(fname.c_str(), currFileSize);
1945 fs->open(fname, std::fstream::out | std::fstream::trunc);
1946 return true;
1947 }
1948 return false;
1949 }
1950
1951 // RegisteredHitCounters
1952
1953 bool RegisteredHitCounters::validateEveryN(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
1954 base::threading::ScopedLock scopedLock(lock());
1955 base::HitCounter* counter = get(filename, lineNumber);
1956 if (counter == nullptr) {
1957 registerNew(counter = new base::HitCounter(filename, lineNumber));
1958 }
1959 counter->validateHitCounts(n);
1960 bool result = (n >= 1 && counter->hitCounts() != 0 && counter->hitCounts() % n == 0);
1961 return result;
1962 }
1963
1964 /// @brief Validates counter for hits >= N, i.e, registers new if does not exist otherwise updates original one
1965 /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned
1966 bool RegisteredHitCounters::validateAfterN(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
1967 base::threading::ScopedLock scopedLock(lock());
1968 base::HitCounter* counter = get(filename, lineNumber);
1969 if (counter == nullptr) {
1970 registerNew(counter = new base::HitCounter(filename, lineNumber));
1971 }
1972 // Do not use validateHitCounts here since we do not want to reset counter here
1973 // Note the >= instead of > because we are incrementing
1974 // after this check
1975 if (counter->hitCounts() >= n)
1976 return true;
1977 counter->increment();
1978 return false;
1979 }
1980
1981 /// @brief Validates counter for hits are <= n, i.e, registers new if does not exist otherwise updates original one
1982 /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned
1983 bool RegisteredHitCounters::validateNTimes(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
1984 base::threading::ScopedLock scopedLock(lock());
1985 base::HitCounter* counter = get(filename, lineNumber);
1986 if (counter == nullptr) {
1987 registerNew(counter = new base::HitCounter(filename, lineNumber));
1988 }
1989 counter->increment();
1990 // Do not use validateHitCounts here since we do not want to reset counter here
1991 if (counter->hitCounts() <= n)
1992 return true;
1993 return false;
1994 }
1995
1996 // RegisteredLoggers
1997
1998 RegisteredLoggers::RegisteredLoggers(const LogBuilderPtr& defaultLogBuilder) :
1999 m_defaultLogBuilder(defaultLogBuilder) {
2000 m_defaultConfigurations.setToDefault();
2001 }
2002
2003 Logger* RegisteredLoggers::get(const std::string& id, bool forceCreation) {
2004 base::threading::ScopedLock scopedLock(lock());
2005 Logger* logger_ = base::utils::Registry<Logger, std::string>::get(id);
2006 if (logger_ == nullptr && forceCreation) {
2007 bool validId = Logger::isValidId(id);
2008 if (!validId) {
2009 ELPP_ASSERT(validId, "Invalid logger ID [" << id << "]. Not registering this logger.");
2010 return nullptr;
2011 }
2012 logger_ = new Logger(id, m_defaultConfigurations, &m_logStreamsReference);
2013 logger_->m_logBuilder = m_defaultLogBuilder;
2014 registerNew(id, logger_);
2015 LoggerRegistrationCallback* callback = nullptr;
2016 for (const std::pair<std::string, base::type::LoggerRegistrationCallbackPtr>& h
2017 : m_loggerRegistrationCallbacks) {
2018 callback = h.second.get();
2019 if (callback != nullptr && callback->enabled()) {
2020 callback->handle(logger_);
2021 }
2022 }
2023 }
2024 return logger_;
2025 }
2026
2027 bool RegisteredLoggers::remove(const std::string& id) {
2028 if (id == base::consts::kDefaultLoggerId) {
2029 return false;
2030 }
2031 // get has internal lock
2032 Logger* logger = base::utils::Registry<Logger, std::string>::get(id);
2033 if (logger != nullptr) {
2034 // unregister has internal lock
2035 unregister(logger);
2036 }
2037 return true;
2038 }
2039
2040 void RegisteredLoggers::unsafeFlushAll(void) {
2041 ELPP_INTERNAL_INFO(1, "Flushing all log files");
2042 for (base::LogStreamsReferenceMap::iterator it = m_logStreamsReference.begin();
2043 it != m_logStreamsReference.end(); ++it) {
2044 if (it->second.get() == nullptr) continue;
2045 it->second->flush();
2046 }
2047 }
2048
2049 // VRegistry
2050
2051 VRegistry::VRegistry(base::type::VerboseLevel level, base::type::EnumType* pFlags) : m_level(level), m_pFlags(pFlags) {
2052 }
2053
2054 /// @brief Sets verbose level. Accepted range is 0-9
2055 void VRegistry::setLevel(base::type::VerboseLevel level) {
2056 base::threading::ScopedLock scopedLock(lock());
2057 if (level > 9)
2058 m_level = base::consts::kMaxVerboseLevel;
2059 else
2060 m_level = level;
2061 }
2062
2063 void VRegistry::setModules(const char* modules) {
2064 base::threading::ScopedLock scopedLock(lock());
2065 auto addSuffix = [](std::stringstream& ss, const char* sfx, const char* prev) {
2066 if (prev != nullptr && base::utils::Str::endsWith(ss.str(), std::string(prev))) {
2067 std::string chr(ss.str().substr(0, ss.str().size() - strlen(prev)));
2068 ss.str(std::string(""));
2069 ss << chr;
2070 }
2071 if (base::utils::Str::endsWith(ss.str(), std::string(sfx))) {
2072 std::string chr(ss.str().substr(0, ss.str().size() - strlen(sfx)));
2073 ss.str(std::string(""));
2074 ss << chr;
2075 }
2076 ss << sfx;
2077 };
2078 auto insert = [&](std::stringstream& ss, base::type::VerboseLevel level) {
2079 if (!base::utils::hasFlag(LoggingFlag::DisableVModulesExtensions, *m_pFlags)) {
2080 addSuffix(ss, ".h", nullptr);
2081 m_modules.insert(std::make_pair(ss.str(), level));
2082 addSuffix(ss, ".c", ".h");
2083 m_modules.insert(std::make_pair(ss.str(), level));
2084 addSuffix(ss, ".cpp", ".c");
2085 m_modules.insert(std::make_pair(ss.str(), level));
2086 addSuffix(ss, ".cc", ".cpp");
2087 m_modules.insert(std::make_pair(ss.str(), level));
2088 addSuffix(ss, ".cxx", ".cc");
2089 m_modules.insert(std::make_pair(ss.str(), level));
2090 addSuffix(ss, ".-inl.h", ".cxx");
2091 m_modules.insert(std::make_pair(ss.str(), level));
2092 addSuffix(ss, ".hxx", ".-inl.h");
2093 m_modules.insert(std::make_pair(ss.str(), level));
2094 addSuffix(ss, ".hpp", ".hxx");
2095 m_modules.insert(std::make_pair(ss.str(), level));
2096 addSuffix(ss, ".hh", ".hpp");
2097 }
2098 m_modules.insert(std::make_pair(ss.str(), level));
2099 };
2100 bool isMod = true;
2101 bool isLevel = false;
2102 std::stringstream ss;
2103 int level = -1;
2104 for (; *modules; ++modules) {
2105 switch (*modules) {
2106 case '=':
2107 isLevel = true;
2108 isMod = false;
2109 break;
2110 case ',':
2111 isLevel = false;
2112 isMod = true;
2113 if (!ss.str().empty() && level != -1) {
2114 insert(ss, static_cast<base::type::VerboseLevel>(level));
2115 ss.str(std::string(""));
2116 level = -1;
2117 }
2118 break;
2119 default:
2120 if (isMod) {
2121 ss << *modules;
2122 } else if (isLevel) {
2123 if (isdigit(*modules)) {
2124 level = static_cast<base::type::VerboseLevel>(*modules) - 48;
2125 }
2126 }
2127 break;
2128 }
2129 }
2130 if (!ss.str().empty() && level != -1) {
2131 insert(ss, static_cast<base::type::VerboseLevel>(level));
2132 }
2133 }
2134
2135 // Log levels are sorted in a weird way...
2136 static int priority(Level level) {
2137 if (level == Level::Fatal) return 0;
2138 if (level == Level::Error) return 1;
2139 if (level == Level::Warning) return 2;
2140 if (level == Level::Info) return 3;
2141 if (level == Level::Debug) return 4;
2142 if (level == Level::Verbose) return 5;
2143 if (level == Level::Trace) return 6;
2144 return 7;
2145 }
2146
2147 namespace
2148 {
2149 std::atomic<int> s_lowest_priority{INT_MAX};
2150 }
2151
2152 void VRegistry::clearCategories(void) {
2153 const base::threading::ScopedLock scopedLock(lock());
2154 m_categories.clear();
2155 m_cached_allowed_categories.clear();
2156 s_lowest_priority = INT_MAX;
2157 }
2158
2159 void VRegistry::setCategories(const char* categories, bool clear) {
2160 base::threading::ScopedLock scopedLock(lock());
2161 auto insert = [&](std::stringstream& ss, Level level) {
2162 m_categories.push_back(std::make_pair(ss.str(), level));
2163 m_cached_allowed_categories.clear();
2164 int pri = priority(level);
2165 if (pri > s_lowest_priority)
2166 s_lowest_priority = pri;
2167 };
2168
2169 if (clear) {
2170 s_lowest_priority = 0;
2171 m_categories.clear();
2172 m_cached_allowed_categories.clear();
2173 m_categoriesString.clear();
2174 }
2175 if (!categories)
2176 return;
2177 if (!m_categoriesString.empty())
2178 m_categoriesString += ",";
2179 m_categoriesString += categories;
2180
2181 size_t n_fields = m_categories.size() + 1;
2182 for (const char *ptr = categories; *ptr; ++ptr)
2183 if (*ptr == ',')
2184 ++n_fields;
2185 m_categories.reserve(n_fields);
2186
2187 bool isCat = true;
2188 bool isLevel = false;
2189 std::stringstream ss;
2190 Level level = Level::Unknown;
2191 for (; *categories; ++categories) {
2192 switch (*categories) {
2193 case ':':
2194 isLevel = true;
2195 isCat = false;
2196 break;
2197 case ',':
2198 isLevel = false;
2199 isCat = true;
2200 if (!ss.str().empty() && level != Level::Unknown) {
2201 insert(ss, level);
2202 ss.str(std::string(""));
2203 level = Level::Unknown;
2204 }
2205 break;
2206 default:
2207 if (isCat) {
2208 ss << *categories;
2209 } else if (isLevel) {
2210 level = LevelHelper::convertFromStringPrefix(categories);
2211 if (level != Level::Unknown)
2212 categories += strlen(LevelHelper::convertToString(level)) - 1;
2213 }
2214 break;
2215 }
2216 }
2217 if (!ss.str().empty() && level != Level::Unknown) {
2218 insert(ss, level);
2219 }
2220 }
2221
2222 std::string VRegistry::getCategories() {
2223 base::threading::ScopedLock scopedLock(lock());
2224 return m_categoriesString;
2225 }
2226
2227 bool VRegistry::allowed(Level level, const std::string &category) {
2228 return priority_allowed(priority(level), category);
2229 }
2230 bool VRegistry::priority_allowed(const int pri, const std::string &category) {
2231 base::threading::ScopedLock scopedLock(lock());
2232 const std::map<std::string, int>::const_iterator it = m_cached_allowed_categories.find(category);
2233 if (it != m_cached_allowed_categories.end())
2234 return pri <= it->second;
2235 if (m_categories.empty()) {
2236 return false;
2237 } else {
2238 std::vector<std::pair<std::string, Level>>::const_reverse_iterator it = m_categories.rbegin();
2239 for (; it != m_categories.rend(); ++it) {
2240 if (base::utils::Str::wildCardMatch(category.c_str(), it->first.c_str())) {
2241 const int p = priority(it->second);
2242 m_cached_allowed_categories.insert(std::make_pair(category, p));
2243 return pri <= p;
2244 }
2245 }
2246 m_cached_allowed_categories.insert(std::make_pair(category, -1));
2247 return false;
2248 }
2249 }
2250
2251 bool VRegistry::allowed(base::type::VerboseLevel vlevel, const char* file) {
2252 base::threading::ScopedLock scopedLock(lock());
2253 if (m_modules.empty() || file == nullptr) {
2254 return vlevel <= m_level;
2255 } else {
2256 char baseFilename[base::consts::kSourceFilenameMaxLength] = "";
2257 base::utils::File::buildBaseFilename(file, baseFilename);
2258 std::unordered_map<std::string, base::type::VerboseLevel>::iterator it = m_modules.begin();
2259 for (; it != m_modules.end(); ++it) {
2260 if (base::utils::Str::wildCardMatch(baseFilename, it->first.c_str())) {
2261 return vlevel <= it->second;
2262 }
2263 }
2264 if (base::utils::hasFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified, *m_pFlags)) {
2265 return true;
2266 }
2267 return false;
2268 }
2269 }
2270
2271 void VRegistry::setFromArgs(const base::utils::CommandLineArgs* commandLineArgs) {
2272 if (commandLineArgs->hasParam("-v") || commandLineArgs->hasParam("--verbose") ||
2273 commandLineArgs->hasParam("-V") || commandLineArgs->hasParam("--VERBOSE")) {
2274 setLevel(base::consts::kMaxVerboseLevel);
2275 } else if (commandLineArgs->hasParamWithValue("--v")) {
2276 setLevel(static_cast<base::type::VerboseLevel>(atoi(commandLineArgs->getParamValue("--v"))));
2277 } else if (commandLineArgs->hasParamWithValue("--V")) {
2278 setLevel(static_cast<base::type::VerboseLevel>(atoi(commandLineArgs->getParamValue("--V"))));
2279 } else if ((commandLineArgs->hasParamWithValue("-vmodule")) && vModulesEnabled()) {
2280 setModules(commandLineArgs->getParamValue("-vmodule"));
2281 } else if (commandLineArgs->hasParamWithValue("-VMODULE") && vModulesEnabled()) {
2282 setModules(commandLineArgs->getParamValue("-VMODULE"));
2283 }
2284 }
2285
2286 #if !defined(ELPP_DEFAULT_LOGGING_FLAGS)
2287 # define ELPP_DEFAULT_LOGGING_FLAGS 0x0
2288 #endif // !defined(ELPP_DEFAULT_LOGGING_FLAGS)
2289 // Storage
2290 el::base::type::StoragePointer &el::base::Storage::getELPP()
2291 {
2292 if (!el::base::elStorage)
2293 el::base::elStorage = new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder()));
2294 return el::base::elStorage;
2295 }
2296 static struct EnsureELPP { EnsureELPP() { el::base::Storage::getELPP(); } } ensureELPP;
2297 #if ELPP_ASYNC_LOGGING
2298 Storage::Storage(const LogBuilderPtr& defaultLogBuilder, base::IWorker* asyncDispatchWorker) :
2299 #else
2300 Storage::Storage(const LogBuilderPtr& defaultLogBuilder) :
2301 #endif // ELPP_ASYNC_LOGGING
2302 m_registeredHitCounters(new base::RegisteredHitCounters()),
2303 m_registeredLoggers(new base::RegisteredLoggers(defaultLogBuilder)),
2304 m_flags(ELPP_DEFAULT_LOGGING_FLAGS),
2305 m_vRegistry(new base::VRegistry(0, &m_flags)),
2306
2307 #if ELPP_ASYNC_LOGGING
2308 m_asyncLogQueue(new base::AsyncLogQueue()),
2309 m_asyncDispatchWorker(asyncDispatchWorker),
2310 #endif // ELPP_ASYNC_LOGGING
2311
2312 m_preRollOutCallback(base::defaultPreRollOutCallback) {
2313 // Register default logger
2314 m_registeredLoggers->get(std::string(base::consts::kDefaultLoggerId));
2315 // We register default logger anyway (worse case it's not going to register) just in case
2316 m_registeredLoggers->get("default");
2317
2318 #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
2319 // Register performance logger and reconfigure format
2320 Logger* performanceLogger = m_registeredLoggers->get(std::string(base::consts::kPerformanceLoggerId));
2321 m_registeredLoggers->get("performance");
2322 performanceLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%datetime %level %msg"));
2323 performanceLogger->reconfigure();
2324 #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
2325
2326 #if defined(ELPP_SYSLOG)
2327 // Register syslog logger and reconfigure format
2328 Logger* sysLogLogger = m_registeredLoggers->get(std::string(base::consts::kSysLogLoggerId));
2329 sysLogLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%level: %msg"));
2330 sysLogLogger->reconfigure();
2331 #endif // defined(ELPP_SYSLOG)
2332 addFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified);
2333 addFlag(LoggingFlag::CreateLoggerAutomatically);
2334 #if ELPP_ASYNC_LOGGING
2335 installLogDispatchCallback<base::AsyncLogDispatchCallback>(std::string("AsyncLogDispatchCallback"));
2336 #else
2337 installLogDispatchCallback<base::DefaultLogDispatchCallback>(std::string("DefaultLogDispatchCallback"));
2338 #endif // ELPP_ASYNC_LOGGING
2339 #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
2340 installPerformanceTrackingCallback<base::DefaultPerformanceTrackingCallback>
2341 (std::string("DefaultPerformanceTrackingCallback"));
2342 #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
2343 ELPP_INTERNAL_INFO(1, "Easylogging++ has been initialized");
2344 #if ELPP_ASYNC_LOGGING
2345 m_asyncDispatchWorker->start();
2346 #endif // ELPP_ASYNC_LOGGING
2347 }
2348
2349 Storage::~Storage(void) {
2350 ELPP_INTERNAL_INFO(4, "Destroying storage");
2351 #if ELPP_ASYNC_LOGGING
2352 ELPP_INTERNAL_INFO(5, "Replacing log dispatch callback to synchronous");
2353 uninstallLogDispatchCallback<base::AsyncLogDispatchCallback>(std::string("AsyncLogDispatchCallback"));
2354 installLogDispatchCallback<base::DefaultLogDispatchCallback>(std::string("DefaultLogDispatchCallback"));
2355 ELPP_INTERNAL_INFO(5, "Destroying asyncDispatchWorker");
2356 base::utils::safeDelete(m_asyncDispatchWorker);
2357 ELPP_INTERNAL_INFO(5, "Destroying asyncLogQueue");
2358 base::utils::safeDelete(m_asyncLogQueue);
2359 #endif // ELPP_ASYNC_LOGGING
2360 ELPP_INTERNAL_INFO(5, "Destroying registeredHitCounters");
2361 base::utils::safeDelete(m_registeredHitCounters);
2362 ELPP_INTERNAL_INFO(5, "Destroying registeredLoggers");
2363 base::utils::safeDelete(m_registeredLoggers);
2364 ELPP_INTERNAL_INFO(5, "Destroying vRegistry");
2365 base::utils::safeDelete(m_vRegistry);
2366 }
2367
2368 bool Storage::hasCustomFormatSpecifier(const char* formatSpecifier) {
2369 base::threading::ScopedLock scopedLock(customFormatSpecifiersLock());
2370 return std::find(m_customFormatSpecifiers.begin(), m_customFormatSpecifiers.end(),
2371 formatSpecifier) != m_customFormatSpecifiers.end();
2372 }
2373
2374 void Storage::installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) {
2375 if (hasCustomFormatSpecifier(customFormatSpecifier.formatSpecifier())) {
2376 return;
2377 }
2378 base::threading::ScopedLock scopedLock(customFormatSpecifiersLock());
2379 m_customFormatSpecifiers.push_back(customFormatSpecifier);
2380 }
2381
2382 bool Storage::uninstallCustomFormatSpecifier(const char* formatSpecifier) {
2383 base::threading::ScopedLock scopedLock(customFormatSpecifiersLock());
2384 std::vector<CustomFormatSpecifier>::iterator it = std::find(m_customFormatSpecifiers.begin(),
2385 m_customFormatSpecifiers.end(), formatSpecifier);
2386 if (it != m_customFormatSpecifiers.end() && strcmp(formatSpecifier, it->formatSpecifier()) == 0) {
2387 m_customFormatSpecifiers.erase(it);
2388 return true;
2389 }
2390 return false;
2391 }
2392
2393 void Storage::setApplicationArguments(int argc, char** argv) {
2394 m_commandLineArgs.setArgs(argc, argv);
2395 m_vRegistry->setFromArgs(commandLineArgs());
2396 // default log file
2397 #if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)
2398 if (m_commandLineArgs.hasParamWithValue(base::consts::kDefaultLogFileParam)) {
2399 Configurations c;
2400 c.setGlobally(ConfigurationType::Filename,
2401 std::string(m_commandLineArgs.getParamValue(base::consts::kDefaultLogFileParam)));
2402 registeredLoggers()->setDefaultConfigurations(c);
2403 for (base::RegisteredLoggers::iterator it = registeredLoggers()->begin();
2404 it != registeredLoggers()->end(); ++it) {
2405 it->second->configure(c);
2406 }
2407 }
2408 #endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)
2409 #if defined(ELPP_LOGGING_FLAGS_FROM_ARG)
2410 if (m_commandLineArgs.hasParamWithValue(base::consts::kLoggingFlagsParam)) {
2411 int userInput = atoi(m_commandLineArgs.getParamValue(base::consts::kLoggingFlagsParam));
2412 if (ELPP_DEFAULT_LOGGING_FLAGS == 0x0) {
2413 m_flags = userInput;
2414 } else {
2415 base::utils::addFlag<base::type::EnumType>(userInput, &m_flags);
2416 }
2417 }
2418 #endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG)
2419 }
2420
2421 } // namespace base
2422
2423 // LogDispatchCallback
2424 void LogDispatchCallback::handle(const LogDispatchData* data) {
2425 #if defined(ELPP_THREAD_SAFE)
2426 base::threading::ScopedLock scopedLock(m_fileLocksMapLock);
2427 std::string filename = data->logMessage()->logger()->typedConfigurations()->filename(data->logMessage()->level());
2428 auto lock = m_fileLocks.find(filename);
2429 if (lock == m_fileLocks.end()) {
2430 m_fileLocks.emplace(std::make_pair(filename, std::unique_ptr<base::threading::Mutex>(new base::threading::Mutex)));
2431 }
2432 #endif
2433 }
2434
2435 base::threading::Mutex& LogDispatchCallback::fileHandle(const LogDispatchData* data) {
2436 auto it = m_fileLocks.find(data->logMessage()->logger()->typedConfigurations()->filename(data->logMessage()->level()));
2437 return *(it->second.get());
2438 }
2439
2440 namespace base {
2441 // DefaultLogDispatchCallback
2442
2443 const char* convertToChar(Level level) {
2444 // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet.
2445 if (level == Level::Global) return "G";
2446 if (level == Level::Debug) return "D";
2447 if (level == Level::Info) return "I";
2448 if (level == Level::Warning) return "W";
2449 if (level == Level::Error) return "E";
2450 if (level == Level::Fatal) return "F";
2451 if (level == Level::Verbose) return "V";
2452 if (level == Level::Trace) return "T";
2453 return "?";
2454 }
2455
2456 void DefaultLogDispatchCallback::handle(const LogDispatchData* data) {
2457 #if defined(ELPP_THREAD_SAFE)
2458 #if 0
2459 LogDispatchCallback::handle(data);
2460 base::threading::ScopedLock scopedLock(fileHandle(data));
2461 #endif
2462 #endif
2463 m_data = data;
2464 base::TypedConfigurations* tc = m_data->logMessage()->logger()->typedConfigurations();
2465 const base::LogFormat* logFormat = &tc->logFormat(m_data->logMessage()->level());
2466
2467 const auto &logmsg = m_data->logMessage();
2468 const auto msg = logmsg->message();
2469 if (strchr(msg.c_str(), '\n'))
2470 {
2471 std::vector<std::string> v;
2472 const char *s = msg.c_str();
2473 while (true)
2474 {
2475 const char *ptr = strchr(s, '\n');
2476 if (!ptr)
2477 {
2478 if (*s)
2479 v.push_back(s);
2480 break;
2481 }
2482 v.push_back(std::string(s, ptr - s));
2483 s = ptr + 1;
2484 }
2485 for (const std::string &s: v)
2486 {
2487 LogMessage msgline(logmsg->level(), logmsg->color(), logmsg->file(), logmsg->line(), logmsg->func(), logmsg->verboseLevel(), logmsg->logger(), &s);
2488 dispatch(base::utils::DateTime::getDateTime(logFormat->dateTimeFormat().c_str(), &tc->subsecondPrecision(m_data->logMessage()->level())) + "\t" + convertToChar(m_data->logMessage()->level()) + " ",
2489 s + "\n",
2490 m_data->logMessage()->logger()->logBuilder()->build(&msgline,
2491 m_data->dispatchAction() == base::DispatchAction::NormalLog || m_data->dispatchAction() == base::DispatchAction::FileOnlyLog));
2492 }
2493 }
2494 else
2495 {
2496 dispatch(base::utils::DateTime::getDateTime(logFormat->dateTimeFormat().c_str(), &tc->subsecondPrecision(m_data->logMessage()->level()))
2497 + "\t" + convertToChar(m_data->logMessage()->level()) + " ", m_data->logMessage()->message() + "\n",
2498 m_data->logMessage()->logger()->logBuilder()->build(m_data->logMessage(),
2499 m_data->dispatchAction() == base::DispatchAction::NormalLog || m_data->dispatchAction() == base::DispatchAction::FileOnlyLog));
2500 }
2501 }
2502
2503
2504 template<typename Transform>
2505 static inline void utf8canonical(std::string &s, Transform t = [](wint_t c)->wint_t { return c; })
2506 {
2507 size_t avail = s.size();
2508 const char *ptr = s.data();
2509 wint_t cp = 0;
2510 int rbytes = 1, bytes = -1;
2511 char wbuf[8], *wptr;
2512 size_t w_offset = 0;
2513 while (avail--)
2514 {
2515 if ((*ptr & 0x80) == 0)
2516 {
2517 cp = *ptr++;
2518 rbytes = 1;
2519 }
2520 else if ((*ptr & 0xe0) == 0xc0)
2521 {
2522 if (avail < 1)
2523 throw std::runtime_error("Invalid UTF-8");
2524 cp = (*ptr++ & 0x1f) << 6;
2525 cp |= *ptr++ & 0x3f;
2526 --avail;
2527 rbytes = 2;
2528 }
2529 else if ((*ptr & 0xf0) == 0xe0)
2530 {
2531 if (avail < 2)
2532 throw std::runtime_error("Invalid UTF-8");
2533 cp = (*ptr++ & 0xf) << 12;
2534 cp |= (*ptr++ & 0x3f) << 6;
2535 cp |= *ptr++ & 0x3f;
2536 avail -= 2;
2537 rbytes = 3;
2538 }
2539 else if ((*ptr & 0xf8) == 0xf0)
2540 {
2541 if (avail < 3)
2542 throw std::runtime_error("Invalid UTF-8");
2543 cp = (*ptr++ & 0x7) << 18;
2544 cp |= (*ptr++ & 0x3f) << 12;
2545 cp |= (*ptr++ & 0x3f) << 6;
2546 cp |= *ptr++ & 0x3f;
2547 avail -= 3;
2548 rbytes = 4;
2549 }
2550 else
2551 throw std::runtime_error("Invalid UTF-8");
2552
2553 cp = t(cp);
2554 if (cp <= 0x7f)
2555 bytes = 1;
2556 else if (cp <= 0x7ff)
2557 bytes = 2;
2558 else if (cp <= 0xffff)
2559 bytes = 3;
2560 else if (cp <= 0x10ffff)
2561 bytes = 4;
2562 else
2563 throw std::runtime_error("Invalid code point UTF-8 transformation");
2564
2565 if (bytes > rbytes)
2566 throw std::runtime_error("In place sanitization requires replacements to not take more space than the original code points");
2567
2568 wptr = wbuf;
2569 switch (bytes)
2570 {
2571 case 1: *wptr++ = cp; break;
2572 case 2: *wptr++ = 0xc0 | (cp >> 6); *wptr++ = 0x80 | (cp & 0x3f); break;
2573 case 3: *wptr++ = 0xe0 | (cp >> 12); *wptr++ = 0x80 | ((cp >> 6) & 0x3f); *wptr++ = 0x80 | (cp & 0x3f); break;
2574 case 4: *wptr++ = 0xf0 | (cp >> 18); *wptr++ = 0x80 | ((cp >> 12) & 0x3f); *wptr++ = 0x80 | ((cp >> 6) & 0x3f); *wptr++ = 0x80 | (cp & 0x3f); break;
2575 default: throw std::runtime_error("Invalid UTF-8");
2576 }
2577 *wptr = 0;
2578 memcpy(&s[w_offset], wbuf, bytes);
2579 w_offset += bytes;
2580 cp = 0;
2581 bytes = 1;
2582 }
2583 s.resize(w_offset);
2584 }
2585
2586 void sanitize(std::string &s)
2587 {
2588 utf8canonical(s, [](wint_t c)->wint_t {
2589 if (c == 9 || c == 10 || c == 13)
2590 return c;
2591 if (c < 0x20)
2592 return '?';
2593 if (c == 0x7f)
2594 return '?';
2595 if (c >= 0x80 && c <= 0x9f)
2596 return '?';
2597 return c;
2598 });
2599 }
2600
2601 void DefaultLogDispatchCallback::dispatch(base::type::string_t&& rawLinePrefix, base::type::string_t&& rawLinePayload, base::type::string_t&& logLine) {
2602 if (m_data->dispatchAction() == base::DispatchAction::NormalLog || m_data->dispatchAction() == base::DispatchAction::FileOnlyLog) {
2603 if (m_data->logMessage()->logger()->m_typedConfigurations->toFile(m_data->logMessage()->level())) {
2604 base::type::fstream_t* fs = m_data->logMessage()->logger()->m_typedConfigurations->fileStream(
2605 m_data->logMessage()->level());
2606 if (fs != nullptr) {
2607 fs->write(logLine.c_str(), logLine.size());
2608 if (fs->fail()) {
2609 ELPP_INTERNAL_ERROR("Unable to write log to file ["
2610 << m_data->logMessage()->logger()->m_typedConfigurations->filename(m_data->logMessage()->level()) << "].\n"
2611 << "Few possible reasons (could be something else):\n" << " * Permission denied\n"
2612 << " * Disk full\n" << " * Disk is not writable", true);
2613 } else {
2614 if (ELPP->hasFlag(LoggingFlag::ImmediateFlush)
2615 || (m_data->logMessage()->logger()->isFlushNeeded(m_data->logMessage()->level()))) {
2616 m_data->logMessage()->logger()->flush(m_data->logMessage()->level(), fs);
2617 }
2618 }
2619 } else {
2620 ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(m_data->logMessage()->level()) << "] "
2621 << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: "
2622 << m_data->logMessage()->logger()->id() << "]", false);
2623 }
2624 }
2625 if (m_data->dispatchAction() != base::DispatchAction::FileOnlyLog) {
2626 if (m_data->logMessage()->logger()->m_typedConfigurations->toStandardOutput(m_data->logMessage()->level())) {
2627 const el::Level level = m_data->logMessage()->level();
2628 const el::Color color = m_data->logMessage()->color();
2629 m_data->logMessage()->logger()->logBuilder()->setColor(el::base::utils::colorFromLevel(level), false);
2630 ELPP_COUT << rawLinePrefix;
2631 m_data->logMessage()->logger()->logBuilder()->setColor(color == el::Color::Default ? el::base::utils::colorFromLevel(level): color, color != el::Color::Default);
2632 try { sanitize(rawLinePayload); }
2633 catch (const std::exception &e) { rawLinePayload = "<Invalid UTF-8 in log>"; }
2634 ELPP_COUT << rawLinePayload;
2635 m_data->logMessage()->logger()->logBuilder()->setColor(el::Color::Default, false);
2636 ELPP_COUT << std::flush;
2637 }
2638 }
2639 }
2640 #if defined(ELPP_SYSLOG)
2641 else if (m_data->dispatchAction() == base::DispatchAction::SysLog) {
2642 // Determine syslog priority
2643 int sysLogPriority = 0;
2644 if (m_data->logMessage()->level() == Level::Fatal)
2645 sysLogPriority = LOG_EMERG;
2646 else if (m_data->logMessage()->level() == Level::Error)
2647 sysLogPriority = LOG_ERR;
2648 else if (m_data->logMessage()->level() == Level::Warning)
2649 sysLogPriority = LOG_WARNING;
2650 else if (m_data->logMessage()->level() == Level::Info)
2651 sysLogPriority = LOG_INFO;
2652 else if (m_data->logMessage()->level() == Level::Debug)
2653 sysLogPriority = LOG_DEBUG;
2654 else
2655 sysLogPriority = LOG_NOTICE;
2656 # if defined(ELPP_UNICODE)
2657 char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str());
2658 syslog(sysLogPriority, "%s", line);
2659 free(line);
2660 # else
2661 syslog(sysLogPriority, "%s", logLine.c_str());
2662 # endif
2663 }
2664 #endif // defined(ELPP_SYSLOG)
2665 }
2666
2667 #if ELPP_ASYNC_LOGGING
2668
2669 // AsyncLogDispatchCallback
2670
2671 void AsyncLogDispatchCallback::handle(const LogDispatchData* data) {
2672 base::type::string_t logLine = data->logMessage()->logger()->logBuilder()->build(data->logMessage(),
2673 data->dispatchAction() == base::DispatchAction::NormalLog || data->dispatchAction() == base::DispatchAction::FileOnlyLog);
2674 if ((data->dispatchAction() == base::DispatchAction::NormalLog || data->dispatchAction() == base::DispatchAction::FileOnlyLog)
2675 && data->logMessage()->logger()->typedConfigurations()->toStandardOutput(data->logMessage()->level())) {
2676 if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput))
2677 data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&logLine, data->logMessage()->level(), data->logMessage()->color());
2678 ELPP_COUT << ELPP_COUT_LINE(logLine);
2679 }
2680 // Save resources and only queue if we want to write to file otherwise just ignore handler
2681 if (data->logMessage()->logger()->typedConfigurations()->toFile(data->logMessage()->level())) {
2682 ELPP->asyncLogQueue()->push(AsyncLogItem(*(data->logMessage()), *data, logLine));
2683 }
2684 }
2685
2686 // AsyncDispatchWorker
2687 AsyncDispatchWorker::AsyncDispatchWorker() {
2688 setContinueRunning(false);
2689 }
2690
2691 AsyncDispatchWorker::~AsyncDispatchWorker() {
2692 setContinueRunning(false);
2693 ELPP_INTERNAL_INFO(6, "Stopping dispatch worker - Cleaning log queue");
2694 clean();
2695 ELPP_INTERNAL_INFO(6, "Log queue cleaned");
2696 }
2697
2698 bool AsyncDispatchWorker::clean(void) {
2699 std::mutex m;
2700 std::unique_lock<std::mutex> lk(m);
2701 cv.wait(lk, [] { return !ELPP->asyncLogQueue()->empty(); });
2702 emptyQueue();
2703 lk.unlock();
2704 cv.notify_one();
2705 return ELPP->asyncLogQueue()->empty();
2706 }
2707
2708 void AsyncDispatchWorker::emptyQueue(void) {
2709 while (!ELPP->asyncLogQueue()->empty()) {
2710 AsyncLogItem data = ELPP->asyncLogQueue()->next();
2711 handle(&data);
2712 base::threading::msleep(100);
2713 }
2714 }
2715
2716 void AsyncDispatchWorker::start(void) {
2717 base::threading::msleep(5000); // 5s (why?)
2718 setContinueRunning(true);
2719 std::thread t1(&AsyncDispatchWorker::run, this);
2720 t1.join();
2721 }
2722
2723 void AsyncDispatchWorker::handle(AsyncLogItem* logItem) {
2724 LogDispatchData* data = logItem->data();
2725 LogMessage* logMessage = logItem->logMessage();
2726 Logger* logger = logMessage->logger();
2727 base::TypedConfigurations* conf = logger->typedConfigurations();
2728 base::type::string_t logLine = logItem->logLine();
2729 if (data->dispatchAction() == base::DispatchAction::NormalLog || data->dispatchAction() == base::DispatchAction::FileOnlyLog) {
2730 if (conf->toFile(logMessage->level())) {
2731 base::type::fstream_t* fs = conf->fileStream(logMessage->level());
2732 if (fs != nullptr) {
2733 fs->write(logLine.c_str(), logLine.size());
2734 if (fs->fail()) {
2735 ELPP_INTERNAL_ERROR("Unable to write log to file ["
2736 << conf->filename(logMessage->level()) << "].\n"
2737 << "Few possible reasons (could be something else):\n" << " * Permission denied\n"
2738 << " * Disk full\n" << " * Disk is not writable", true);
2739 } else {
2740 if (ELPP->hasFlag(LoggingFlag::ImmediateFlush) || (logger->isFlushNeeded(logMessage->level()))) {
2741 logger->flush(logMessage->level(), fs);
2742 }
2743 }
2744 } else {
2745 ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(logMessage->level()) << "] "
2746 << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: " << logger->id() << "]", false);
2747 }
2748 }
2749 }
2750 # if defined(ELPP_SYSLOG)
2751 else if (data->dispatchAction() == base::DispatchAction::SysLog) {
2752 // Determine syslog priority
2753 int sysLogPriority = 0;
2754 if (logMessage->level() == Level::Fatal)
2755 sysLogPriority = LOG_EMERG;
2756 else if (logMessage->level() == Level::Error)
2757 sysLogPriority = LOG_ERR;
2758 else if (logMessage->level() == Level::Warning)
2759 sysLogPriority = LOG_WARNING;
2760 else if (logMessage->level() == Level::Info)
2761 sysLogPriority = LOG_INFO;
2762 else if (logMessage->level() == Level::Debug)
2763 sysLogPriority = LOG_DEBUG;
2764 else
2765 sysLogPriority = LOG_NOTICE;
2766 # if defined(ELPP_UNICODE)
2767 char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str());
2768 syslog(sysLogPriority, "%s", line);
2769 free(line);
2770 # else
2771 syslog(sysLogPriority, "%s", logLine.c_str());
2772 # endif
2773 }
2774 # endif // defined(ELPP_SYSLOG)
2775 }
2776
2777 void AsyncDispatchWorker::run(void) {
2778 while (continueRunning()) {
2779 emptyQueue();
2780 base::threading::msleep(10); // 10ms
2781 }
2782 }
2783 #endif // ELPP_ASYNC_LOGGING
2784
2785 // DefaultLogBuilder
2786
2787 base::type::string_t DefaultLogBuilder::build(const LogMessage* logMessage, bool appendNewLine) const {
2788 base::TypedConfigurations* tc = logMessage->logger()->typedConfigurations();
2789 const base::LogFormat* logFormat = &tc->logFormat(logMessage->level());
2790 base::type::string_t logLine = logFormat->format();
2791 char buff[base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength] = "";
2792 const char* bufLim = buff + sizeof(buff);
2793 if (logFormat->hasFlag(base::FormatFlags::AppName)) {
2794 // App name
2795 base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kAppNameFormatSpecifier,
2796 logMessage->logger()->parentApplicationName());
2797 }
2798 if (logFormat->hasFlag(base::FormatFlags::ThreadId)) {
2799 // Thread ID
2800 base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kThreadIdFormatSpecifier,
2801 ELPP->getThreadName(base::threading::getCurrentThreadId()));
2802 }
2803 if (logFormat->hasFlag(base::FormatFlags::DateTime)) {
2804 // DateTime
2805 base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kDateTimeFormatSpecifier,
2806 base::utils::DateTime::getDateTime(logFormat->dateTimeFormat().c_str(),
2807 &tc->subsecondPrecision(logMessage->level())));
2808 }
2809 if (logFormat->hasFlag(base::FormatFlags::Function)) {
2810 // Function
2811 base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFunctionFormatSpecifier, logMessage->func());
2812 }
2813 if (logFormat->hasFlag(base::FormatFlags::File)) {
2814 // File
2815 base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength);
2816 base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff, ELPP->vRegistry()->getFilenameCommonPrefix());
2817 base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileFormatSpecifier, std::string(buff));
2818 }
2819 if (logFormat->hasFlag(base::FormatFlags::FileBase)) {
2820 // FileBase
2821 base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength);
2822 base::utils::File::buildBaseFilename(logMessage->file(), buff);
2823 base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileBaseFormatSpecifier, std::string(buff));
2824 }
2825 if (logFormat->hasFlag(base::FormatFlags::Line)) {
2826 // Line
2827 char* buf = base::utils::Str::clearBuff(buff, base::consts::kSourceLineMaxLength);
2828 buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), base::consts::kSourceLineMaxLength, buf, bufLim, false);
2829 base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLineFormatSpecifier, std::string(buff));
2830 }
2831 if (logFormat->hasFlag(base::FormatFlags::Location)) {
2832 // Location
2833 char* buf = base::utils::Str::clearBuff(buff,
2834 base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength);
2835 base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff, ELPP->vRegistry()->getFilenameCommonPrefix());
2836 buf = base::utils::Str::addToBuff(buff, buf, bufLim);
2837 buf = base::utils::Str::addToBuff(":", buf, bufLim);
2838 buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), base::consts::kSourceLineMaxLength, buf, bufLim,
2839 false);
2840 base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLocationFormatSpecifier, std::string(buff));
2841 }
2842 if (logMessage->level() == Level::Verbose && logFormat->hasFlag(base::FormatFlags::VerboseLevel)) {
2843 // Verbose level
2844 char* buf = base::utils::Str::clearBuff(buff, 1);
2845 buf = base::utils::Str::convertAndAddToBuff(logMessage->verboseLevel(), 1, buf, bufLim, false);
2846 base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kVerboseLevelFormatSpecifier, std::string(buff));
2847 }
2848 if (logFormat->hasFlag(base::FormatFlags::LogMessage)) {
2849 // Log message
2850 base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kMessageFormatSpecifier, logMessage->message());
2851 }
2852 #if !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS)
2853 el::base::threading::ScopedLock lock_(ELPP->customFormatSpecifiersLock());
2854 ELPP_UNUSED(lock_);
2855 for (std::vector<CustomFormatSpecifier>::const_iterator it = ELPP->customFormatSpecifiers()->begin();
2856 it != ELPP->customFormatSpecifiers()->end(); ++it) {
2857 std::string fs(it->formatSpecifier());
2858 base::type::string_t wcsFormatSpecifier(fs.begin(), fs.end());
2859 base::utils::Str::replaceFirstWithEscape(logLine, wcsFormatSpecifier, it->resolver()(logMessage));
2860 }
2861 #endif // !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS)
2862 if (appendNewLine) logLine += ELPP_LITERAL("\n");
2863 return logLine;
2864 }
2865
2866 // LogDispatcher
2867
2868 void LogDispatcher::dispatch(void) {
2869 if (m_proceed && m_dispatchAction == base::DispatchAction::None) {
2870 m_proceed = false;
2871 }
2872 if (!m_proceed) {
2873 return;
2874 }
2875 #ifndef ELPP_NO_GLOBAL_LOCK
2876 // see https://github.com/muflihun/easyloggingpp/issues/580
2877 // global lock is turned off by default unless
2878 // ELPP_NO_GLOBAL_LOCK is defined
2879 base::threading::ScopedLock scopedLock(ELPP->lock());
2880 #endif
2881 base::TypedConfigurations* tc = m_logMessage->logger()->m_typedConfigurations;
2882 if (ELPP->hasFlag(LoggingFlag::StrictLogFileSizeCheck)) {
2883 tc->validateFileRolling(m_logMessage->level(), ELPP->preRollOutCallback());
2884 }
2885 LogDispatchCallback* callback = nullptr;
2886 LogDispatchData data;
2887 for (const std::pair<std::string, base::type::LogDispatchCallbackPtr>& h
2888 : ELPP->m_logDispatchCallbacks) {
2889 callback = h.second.get();
2890 if (callback != nullptr && callback->enabled()) {
2891 data.setLogMessage(m_logMessage);
2892 data.setDispatchAction(m_dispatchAction);
2893 callback->handle(&data);
2894 }
2895 }
2896 }
2897
2898 // MessageBuilder
2899
2900 void MessageBuilder::initialize(Logger* logger) {
2901 m_logger = logger;
2902 m_containerLogSeperator = ELPP->hasFlag(LoggingFlag::NewLineForContainer) ?
2903 ELPP_LITERAL("\n ") : ELPP_LITERAL(", ");
2904 }
2905
2906 MessageBuilder& MessageBuilder::operator<<(const wchar_t* msg) {
2907 if (msg == nullptr) {
2908 m_logger->stream() << base::consts::kNullPointer;
2909 return *this;
2910 }
2911 # if defined(ELPP_UNICODE)
2912 m_logger->stream() << msg;
2913 # else
2914 char* buff_ = base::utils::Str::wcharPtrToCharPtr(msg);
2915 m_logger->stream() << buff_;
2916 free(buff_);
2917 # endif
2918 if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) {
2919 m_logger->stream() << " ";
2920 }
2921 return *this;
2922 }
2923
2924 // Writer
2925
2926 Writer& Writer::construct(Logger* logger, bool needLock) {
2927 m_logger = logger;
2928 initializeLogger(logger->id(), false, needLock);
2929 m_messageBuilder.initialize(m_logger);
2930 return *this;
2931 }
2932
2933 Writer& Writer::construct(int count, const char* loggerIds, ...) {
2934 if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) {
2935 va_list loggersList;
2936 va_start(loggersList, loggerIds);
2937 const char* id = loggerIds;
2938 m_loggerIds.reserve(count);
2939 for (int i = 0; i < count; ++i) {
2940 m_loggerIds.push_back(std::string(id));
2941 id = va_arg(loggersList, const char*);
2942 }
2943 va_end(loggersList);
2944 initializeLogger(m_loggerIds.at(0));
2945 } else {
2946 initializeLogger(std::string(loggerIds));
2947 }
2948 m_messageBuilder.initialize(m_logger);
2949 return *this;
2950 }
2951
2952 Writer& Writer::construct(const char *loggerId) {
2953 initializeLogger(ELPP->registeredLoggers()->get(loggerId, ELPP->hasFlag(LoggingFlag::CreateLoggerAutomatically)));
2954 m_messageBuilder.initialize(m_logger);
2955 return *this;
2956 }
2957
2958 void Writer::initializeLogger(const std::string& loggerId, bool lookup, bool needLock) {
2959 if (lookup) {
2960 m_logger = ELPP->registeredLoggers()->get(loggerId, ELPP->hasFlag(LoggingFlag::CreateLoggerAutomatically));
2961 }
2962 if (m_logger == nullptr) {
2963 {
2964 if (!ELPP->registeredLoggers()->has(std::string(base::consts::kDefaultLoggerId))) {
2965 // Somehow default logger has been unregistered. Not good! Register again
2966 ELPP->registeredLoggers()->get(std::string(base::consts::kDefaultLoggerId));
2967 }
2968 }
2969 Writer(Level::Debug, Color::Default, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId)
2970 << "Logger [" << loggerId << "] is not registered yet!";
2971 m_proceed = false;
2972 } else {
2973 if (needLock) {
2974 m_logger->acquireLock(); // This should not be unlocked by checking m_proceed because
2975 // m_proceed can be changed by lines below
2976 }
2977 if (ELPP->hasFlag(LoggingFlag::HierarchicalLogging)) {
2978 m_proceed = m_level == Level::Verbose ? m_logger->enabled(m_level) :
2979 ELPP->vRegistry()->allowed(m_level, loggerId);
2980 } else {
2981 m_proceed = m_logger->enabled(m_level);
2982 }
2983 }
2984 }
2985
2986 void Writer::initializeLogger(Logger *logger, bool needLock) {
2987 m_logger = logger;
2988 if (m_logger == nullptr) {
2989 m_proceed = false;
2990 } else {
2991 if (needLock) {
2992 m_logger->acquireLock(); // This should not be unlocked by checking m_proceed because
2993 // m_proceed can be changed by lines below
2994 }
2995 m_proceed = true;
2996 }
2997 }
2998
2999 void Writer::processDispatch() {
3000 static __thread bool in_dispatch = false;
3001 if (in_dispatch)
3002 {
3003 if (m_proceed && m_logger != NULL)
3004 {
3005 m_logger->stream().str(ELPP_LITERAL(""));
3006 m_logger->releaseLock();
3007 }
3008 return;
3009 }
3010 in_dispatch = true;
3011 #if ELPP_LOGGING_ENABLED
3012 if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) {
3013 bool firstDispatched = false;
3014 base::type::string_t logMessage;
3015 std::size_t i = 0;
3016 do {
3017 if (m_proceed) {
3018 if (firstDispatched) {
3019 m_logger->stream() << logMessage;
3020 } else {
3021 firstDispatched = true;
3022 if (m_loggerIds.size() > 1) {
3023 logMessage = m_logger->stream().str();
3024 }
3025 }
3026 triggerDispatch();
3027 } else if (m_logger != nullptr) {
3028 m_logger->stream().str(ELPP_LITERAL(""));
3029 m_logger->releaseLock();
3030 }
3031 if (i + 1 < m_loggerIds.size()) {
3032 initializeLogger(m_loggerIds.at(i + 1));
3033 }
3034 } while (++i < m_loggerIds.size());
3035 } else {
3036 if (m_proceed) {
3037 triggerDispatch();
3038 } else if (m_logger != nullptr) {
3039 m_logger->stream().str(ELPP_LITERAL(""));
3040 m_logger->releaseLock();
3041 }
3042 }
3043 #else
3044 if (m_logger != nullptr) {
3045 m_logger->stream().str(ELPP_LITERAL(""));
3046 m_logger->releaseLock();
3047 }
3048 #endif // ELPP_LOGGING_ENABLED
3049 in_dispatch = false;
3050 }
3051
3052 void Writer::triggerDispatch(void) {
3053 if (m_proceed) {
3054 if (m_msg == nullptr) {
3055 LogMessage msg(m_level, m_color, m_file, m_line, m_func, m_verboseLevel,
3056 m_logger);
3057 base::LogDispatcher(m_proceed, &msg, m_dispatchAction).dispatch();
3058 } else {
3059 base::LogDispatcher(m_proceed, m_msg, m_dispatchAction).dispatch();
3060 }
3061 }
3062 if (m_logger != nullptr) {
3063 m_logger->stream().str(ELPP_LITERAL(""));
3064 m_logger->releaseLock();
3065 }
3066 if (m_proceed && m_level == Level::Fatal
3067 && !ELPP->hasFlag(LoggingFlag::DisableApplicationAbortOnFatalLog)) {
3068 const std::string str = "Aborting application. Reason: Fatal log at [" + std::string(m_file) + ":" + std::to_string(m_line) + "]";
3069 base::Writer(Level::Warning, Color::Default, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId)
3070 << str;
3071 std::stringstream reasonStream;
3072 reasonStream << "Fatal log at [" << m_file << ":" << m_line << "]"
3073 << " If you wish to disable 'abort on fatal log' please use "
3074 << "el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog)";
3075 base::utils::abort(1, reasonStream.str());
3076 }
3077 m_proceed = false;
3078 }
3079
3080 // PErrorWriter
3081
3082 PErrorWriter::~PErrorWriter(void) {
3083 if (m_proceed) {
3084 #if ELPP_COMPILER_MSVC
3085 char buff[256];
3086 strerror_s(buff, 256, errno);
3087 m_logger->stream() << ": " << buff << " [" << errno << "]";
3088 #else
3089 m_logger->stream() << ": " << strerror(errno) << " [" << errno << "]";
3090 #endif
3091 }
3092 }
3093
3094 // PerformanceTracker
3095
3096 #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
3097
3098 PerformanceTracker::PerformanceTracker(const std::string& blockName,
3099 base::TimestampUnit timestampUnit,
3100 const std::string& loggerId,
3101 bool scopedLog, Level level) :
3102 m_blockName(blockName), m_timestampUnit(timestampUnit), m_loggerId(loggerId), m_scopedLog(scopedLog),
3103 m_level(level), m_hasChecked(false), m_lastCheckpointId(std::string()), m_enabled(false) {
3104 #if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
3105 // We store it locally so that if user happen to change configuration by the end of scope
3106 // or before calling checkpoint, we still depend on state of configuraton at time of construction
3107 el::Logger* loggerPtr = ELPP->registeredLoggers()->get(loggerId, false);
3108 m_enabled = loggerPtr != nullptr && loggerPtr->m_typedConfigurations->performanceTracking(m_level);
3109 if (m_enabled) {
3110 base::utils::DateTime::gettimeofday(&m_startTime);
3111 }
3112 #endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
3113 }
3114
3115 PerformanceTracker::~PerformanceTracker(void) {
3116 #if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
3117 if (m_enabled) {
3118 base::threading::ScopedLock scopedLock(lock());
3119 if (m_scopedLog) {
3120 base::utils::DateTime::gettimeofday(&m_endTime);
3121 base::type::string_t formattedTime = getFormattedTimeTaken();
3122 PerformanceTrackingData data(PerformanceTrackingData::DataType::Complete);
3123 data.init(this);
3124 data.m_formattedTimeTaken = formattedTime;
3125 PerformanceTrackingCallback* callback = nullptr;
3126 for (const std::pair<std::string, base::type::PerformanceTrackingCallbackPtr>& h
3127 : ELPP->m_performanceTrackingCallbacks) {
3128 callback = h.second.get();
3129 if (callback != nullptr && callback->enabled()) {
3130 callback->handle(&data);
3131 }
3132 }
3133 }
3134 }
3135 #endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING)
3136 }
3137
3138 void PerformanceTracker::checkpoint(const std::string& id, const char* file, base::type::LineNumber line,
3139 const char* func) {
3140 #if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
3141 if (m_enabled) {
3142 base::threading::ScopedLock scopedLock(lock());
3143 base::utils::DateTime::gettimeofday(&m_endTime);
3144 base::type::string_t formattedTime = m_hasChecked ? getFormattedTimeTaken(m_lastCheckpointTime) : ELPP_LITERAL("");
3145 PerformanceTrackingData data(PerformanceTrackingData::DataType::Checkpoint);
3146 data.init(this);
3147 data.m_checkpointId = id;
3148 data.m_file = file;
3149 data.m_line = line;
3150 data.m_func = func;
3151 data.m_formattedTimeTaken = formattedTime;
3152 PerformanceTrackingCallback* callback = nullptr;
3153 for (const std::pair<std::string, base::type::PerformanceTrackingCallbackPtr>& h
3154 : ELPP->m_performanceTrackingCallbacks) {
3155 callback = h.second.get();
3156 if (callback != nullptr && callback->enabled()) {
3157 callback->handle(&data);
3158 }
3159 }
3160 base::utils::DateTime::gettimeofday(&m_lastCheckpointTime);
3161 m_hasChecked = true;
3162 m_lastCheckpointId = id;
3163 }
3164 #endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
3165 ELPP_UNUSED(id);
3166 ELPP_UNUSED(file);
3167 ELPP_UNUSED(line);
3168 ELPP_UNUSED(func);
3169 }
3170
3171 const base::type::string_t PerformanceTracker::getFormattedTimeTaken(struct timeval startTime) const {
3172 if (ELPP->hasFlag(LoggingFlag::FixedTimeFormat)) {
3173 base::type::stringstream_t ss;
3174 ss << base::utils::DateTime::getTimeDifference(m_endTime,
3175 startTime, m_timestampUnit) << " " << base::consts::kTimeFormats[static_cast<base::type::EnumType>
3176 (m_timestampUnit)].unit;
3177 return ss.str();
3178 }
3179 return base::utils::DateTime::formatTime(base::utils::DateTime::getTimeDifference(m_endTime,
3180 startTime, m_timestampUnit), m_timestampUnit);
3181 }
3182
3183 #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
3184
3185 namespace debug {
3186 #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
3187
3188 // StackTrace
3189
3190 StackTrace::StackTraceEntry::StackTraceEntry(std::size_t index, const std::string& loc, const std::string& demang,
3191 const std::string& hex,
3192 const std::string& addr) :
3193 m_index(index),
3194 m_location(loc),
3195 m_demangled(demang),
3196 m_hex(hex),
3197 m_addr(addr) {
3198 }
3199
3200 std::ostream& operator<<(std::ostream& ss, const StackTrace::StackTraceEntry& si) {
3201 ss << "[" << si.m_index << "] " << si.m_location << (si.m_hex.empty() ? "" : "+") << si.m_hex << " " << si.m_addr <<
3202 (si.m_demangled.empty() ? "" : ":") << si.m_demangled;
3203 return ss;
3204 }
3205
3206 std::ostream& operator<<(std::ostream& os, const StackTrace& st) {
3207 std::vector<StackTrace::StackTraceEntry>::const_iterator it = st.m_stack.begin();
3208 while (it != st.m_stack.end()) {
3209 os << " " << *it++ << "\n";
3210 }
3211 return os;
3212 }
3213
3214 void StackTrace::generateNew(void) {
3215 #if ELPP_STACKTRACE
3216 m_stack.clear();
3217 void* stack[kMaxStack];
3218 unsigned int size = backtrace(stack, kMaxStack);
3219 char** strings = backtrace_symbols(stack, size);
3220 if (size > kStackStart) { // Skip StackTrace c'tor and generateNew
3221 for (std::size_t i = kStackStart; i < size; ++i) {
3222 std::string mangName;
3223 std::string location;
3224 std::string hex;
3225 std::string addr;
3226
3227 // entry: 2 crash.cpp.bin 0x0000000101552be5 _ZN2el4base5debug10StackTraceC1Ev + 21
3228 const std::string line(strings[i]);
3229 auto p = line.find("_");
3230 if (p != std::string::npos) {
3231 mangName = line.substr(p);
3232 mangName = mangName.substr(0, mangName.find(" +"));
3233 }
3234 p = line.find("0x");
3235 if (p != std::string::npos) {
3236 addr = line.substr(p);
3237 addr = addr.substr(0, addr.find("_"));
3238 }
3239 // Perform demangling if parsed properly
3240 if (!mangName.empty()) {
3241 int status = 0;
3242 char* demangName = abi::__cxa_demangle(mangName.data(), 0, 0, &status);
3243 // if demangling is successful, output the demangled function name
3244 if (status == 0) {
3245 // Success (see http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html)
3246 StackTraceEntry entry(i - 1, location, demangName, hex, addr);
3247 m_stack.push_back(entry);
3248 } else {
3249 // Not successful - we will use mangled name
3250 StackTraceEntry entry(i - 1, location, mangName, hex, addr);
3251 m_stack.push_back(entry);
3252 }
3253 free(demangName);
3254 } else {
3255 StackTraceEntry entry(i - 1, line);
3256 m_stack.push_back(entry);
3257 }
3258 }
3259 }
3260 free(strings);
3261 #else
3262 ELPP_INTERNAL_INFO(1, "Stacktrace generation not supported for selected compiler");
3263 #endif // ELPP_STACKTRACE
3264 }
3265
3266 // Static helper functions
3267
3268 static std::string crashReason(int sig) {
3269 std::stringstream ss;
3270 bool foundReason = false;
3271 for (int i = 0; i < base::consts::kCrashSignalsCount; ++i) {
3272 if (base::consts::kCrashSignals[i].numb == sig) {
3273 ss << "Application has crashed due to [" << base::consts::kCrashSignals[i].name << "] signal";
3274 if (ELPP->hasFlag(el::LoggingFlag::LogDetailedCrashReason)) {
3275 ss << std::endl <<
3276 " " << base::consts::kCrashSignals[i].brief << std::endl <<
3277 " " << base::consts::kCrashSignals[i].detail;
3278 }
3279 foundReason = true;
3280 }
3281 }
3282 if (!foundReason) {
3283 ss << "Application has crashed due to unknown signal [" << sig << "]";
3284 }
3285 return ss.str();
3286 }
3287 /// @brief Logs reason of crash from sig
3288 static void logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) {
3289 if (sig == SIGINT && ELPP->hasFlag(el::LoggingFlag::IgnoreSigInt)) {
3290 return;
3291 }
3292 std::stringstream ss;
3293 ss << "CRASH HANDLED; ";
3294 ss << crashReason(sig);
3295 #if ELPP_STACKTRACE
3296 if (stackTraceIfAvailable) {
3297 ss << std::endl << " ======= Backtrace: =========" << std::endl << base::debug::StackTrace();
3298 }
3299 #else
3300 ELPP_UNUSED(stackTraceIfAvailable);
3301 #endif // ELPP_STACKTRACE
3302 ELPP_WRITE_LOG(el::base::Writer, level, base::DispatchAction::NormalLog, logger) << ss.str();
3303 }
3304
3305 static inline void crashAbort(int sig) {
3306 base::utils::abort(sig, std::string());
3307 }
3308
3309 /// @brief Default application crash handler
3310 ///
3311 /// @detail This function writes log using 'default' logger, prints stack trace for GCC based compilers and aborts program.
3312 static inline void defaultCrashHandler(int sig) {
3313 base::debug::logCrashReason(sig, true, Level::Fatal, base::consts::kDefaultLoggerId);
3314 base::debug::crashAbort(sig);
3315 }
3316
3317 // CrashHandler
3318
3319 CrashHandler::CrashHandler(bool useDefault) {
3320 if (useDefault) {
3321 setHandler(defaultCrashHandler);
3322 }
3323 }
3324
3325 void CrashHandler::setHandler(const Handler& cHandler) {
3326 m_handler = cHandler;
3327 #if defined(ELPP_HANDLE_SIGABRT)
3328 int i = 0; // SIGABRT is at base::consts::kCrashSignals[0]
3329 #else
3330 int i = 1;
3331 #endif // defined(ELPP_HANDLE_SIGABRT)
3332 for (; i < base::consts::kCrashSignalsCount; ++i) {
3333 m_handler = signal(base::consts::kCrashSignals[i].numb, cHandler);
3334 }
3335 }
3336
3337 #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
3338 } // namespace debug
3339 } // namespace base
3340
3341 // el
3342
3343 // Helpers
3344
3345 #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
3346
3347 void Helpers::crashAbort(int sig, const char* sourceFile, unsigned int long line) {
3348 std::stringstream ss;
3349 ss << base::debug::crashReason(sig).c_str();
3350 ss << " - [Called el::Helpers::crashAbort(" << sig << ")]";
3351 if (sourceFile != nullptr && strlen(sourceFile) > 0) {
3352 ss << " - Source: " << sourceFile;
3353 if (line > 0)
3354 ss << ":" << line;
3355 else
3356 ss << " (line number not specified)";
3357 }
3358 base::utils::abort(sig, ss.str());
3359 }
3360
3361 void Helpers::logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) {
3362 el::base::debug::logCrashReason(sig, stackTraceIfAvailable, level, logger);
3363 }
3364
3365 #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
3366
3367 // Loggers
3368
3369 bool Loggers::allowed(Level level, const char* cat)
3370 {
3371 const int pri = base::priority(level);
3372 if (pri > base::s_lowest_priority)
3373 return false;
3374 return ELPP->vRegistry()->priority_allowed(pri, std::string{cat});
3375 }
3376
3377 Logger* Loggers::getLogger(const std::string& identity, bool registerIfNotAvailable) {
3378 return ELPP->registeredLoggers()->get(identity, registerIfNotAvailable);
3379 }
3380
3381 void Loggers::setDefaultLogBuilder(el::LogBuilderPtr& logBuilderPtr) {
3382 ELPP->registeredLoggers()->setDefaultLogBuilder(logBuilderPtr);
3383 }
3384
3385 bool Loggers::unregisterLogger(const std::string& identity) {
3386 return ELPP->registeredLoggers()->remove(identity);
3387 }
3388
3389 bool Loggers::hasLogger(const std::string& identity) {
3390 return ELPP->registeredLoggers()->has(identity);
3391 }
3392
3393 Logger* Loggers::reconfigureLogger(Logger* logger, const Configurations& configurations) {
3394 if (!logger) return nullptr;
3395 logger->configure(configurations);
3396 return logger;
3397 }
3398
3399 Logger* Loggers::reconfigureLogger(const std::string& identity, const Configurations& configurations) {
3400 return Loggers::reconfigureLogger(Loggers::getLogger(identity), configurations);
3401 }
3402
3403 Logger* Loggers::reconfigureLogger(const std::string& identity, ConfigurationType configurationType,
3404 const std::string& value) {
3405 Logger* logger = Loggers::getLogger(identity);
3406 if (logger == nullptr) {
3407 return nullptr;
3408 }
3409 logger->configurations()->set(Level::Global, configurationType, value);
3410 logger->reconfigure();
3411 return logger;
3412 }
3413
3414 void Loggers::reconfigureAllLoggers(const Configurations& configurations) {
3415 for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin();
3416 it != ELPP->registeredLoggers()->end(); ++it) {
3417 Loggers::reconfigureLogger(it->second, configurations);
3418 }
3419 }
3420
3421 void Loggers::reconfigureAllLoggers(Level level, ConfigurationType configurationType,
3422 const std::string& value) {
3423 for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin();
3424 it != ELPP->registeredLoggers()->end(); ++it) {
3425 Logger* logger = it->second;
3426 logger->configurations()->set(level, configurationType, value);
3427 logger->reconfigure();
3428 }
3429 }
3430
3431 void Loggers::setDefaultConfigurations(const Configurations& configurations, bool reconfigureExistingLoggers) {
3432 ELPP->registeredLoggers()->setDefaultConfigurations(configurations);
3433 if (reconfigureExistingLoggers) {
3434 Loggers::reconfigureAllLoggers(configurations);
3435 }
3436 }
3437
3438 const Configurations* Loggers::defaultConfigurations(void) {
3439 return ELPP->registeredLoggers()->defaultConfigurations();
3440 }
3441
3442 const base::LogStreamsReferenceMap* Loggers::logStreamsReference(void) {
3443 return ELPP->registeredLoggers()->logStreamsReference();
3444 }
3445
3446 base::TypedConfigurations Loggers::defaultTypedConfigurations(void) {
3447 return base::TypedConfigurations(
3448 ELPP->registeredLoggers()->defaultConfigurations(),
3449 ELPP->registeredLoggers()->logStreamsReference());
3450 }
3451
3452 std::vector<std::string>* Loggers::populateAllLoggerIds(std::vector<std::string>* targetList) {
3453 targetList->clear();
3454 for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->list().begin();
3455 it != ELPP->registeredLoggers()->list().end(); ++it) {
3456 targetList->push_back(it->first);
3457 }
3458 return targetList;
3459 }
3460
3461 void Loggers::configureFromGlobal(const char* globalConfigurationFilePath) {
3462 std::ifstream gcfStream(globalConfigurationFilePath, std::ifstream::in);
3463 ELPP_ASSERT(gcfStream.is_open(), "Unable to open global configuration file [" << globalConfigurationFilePath
3464 << "] for parsing.");
3465 std::string line = std::string();
3466 std::stringstream ss;
3467 Logger* logger = nullptr;
3468 auto configure = [&](void) {
3469 ELPP_INTERNAL_INFO(8, "Configuring logger: '" << logger->id() << "' with configurations \n" << ss.str()
3470 << "\n--------------");
3471 Configurations c;
3472 c.parseFromText(ss.str());
3473 logger->configure(c);
3474 };
3475 while (gcfStream.good()) {
3476 std::getline(gcfStream, line);
3477 ELPP_INTERNAL_INFO(1, "Parsing line: " << line);
3478 base::utils::Str::trim(line);
3479 if (Configurations::Parser::isComment(line)) continue;
3480 Configurations::Parser::ignoreComments(&line);
3481 base::utils::Str::trim(line);
3482 if (line.size() > 2 && base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLoggerId))) {
3483 if (!ss.str().empty() && logger != nullptr) {
3484 configure();
3485 }
3486 ss.str(std::string(""));
3487 line = line.substr(2);
3488 base::utils::Str::trim(line);
3489 if (line.size() > 1) {
3490 ELPP_INTERNAL_INFO(1, "Getting logger: '" << line << "'");
3491 logger = getLogger(line);
3492 }
3493 } else {
3494 ss << line << "\n";
3495 }
3496 }
3497 if (!ss.str().empty() && logger != nullptr) {
3498 configure();
3499 }
3500 }
3501
3502 bool Loggers::configureFromArg(const char* argKey) {
3503 #if defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS)
3504 ELPP_UNUSED(argKey);
3505 #else
3506 if (!Helpers::commandLineArgs()->hasParamWithValue(argKey)) {
3507 return false;
3508 }
3509 configureFromGlobal(Helpers::commandLineArgs()->getParamValue(argKey));
3510 #endif // defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS)
3511 return true;
3512 }
3513
3514 void Loggers::flushAll(void) {
3515 ELPP->registeredLoggers()->flushAll();
3516 }
3517
3518 void Loggers::setVerboseLevel(base::type::VerboseLevel level) {
3519 ELPP->vRegistry()->setLevel(level);
3520 }
3521
3522 base::type::VerboseLevel Loggers::verboseLevel(void) {
3523 return ELPP->vRegistry()->level();
3524 }
3525
3526 void Loggers::setVModules(const char* modules) {
3527 if (ELPP->vRegistry()->vModulesEnabled()) {
3528 ELPP->vRegistry()->setModules(modules);
3529 }
3530 }
3531
3532 void Loggers::clearVModules(void) {
3533 ELPP->vRegistry()->clearModules();
3534 }
3535
3536 void Loggers::setCategories(const char* categories, bool clear) {
3537 ELPP->vRegistry()->setCategories(categories, clear);
3538 }
3539
3540 std::string Loggers::getCategories() {
3541 return ELPP->vRegistry()->getCategories();
3542 }
3543
3544 void Loggers::clearCategories(void) {
3545 ELPP->vRegistry()->clearCategories();
3546 }
3547
3548 void Loggers::setFilenameCommonPrefix(const std::string &prefix) {
3549 ELPP->vRegistry()->setFilenameCommonPrefix(prefix);
3550 }
3551
3552 const std::string &Loggers::getFilenameCommonPrefix() {
3553 return ELPP->vRegistry()->getFilenameCommonPrefix();
3554 }
3555
3556 // VersionInfo
3557
3558 const std::string VersionInfo::version(void) {
3559 return std::string("9.96.7");
3560 }
3561 /// @brief Release date of current version
3562 const std::string VersionInfo::releaseDate(void) {
3563 return std::string("24-11-2018 0728hrs");
3564 }
3565
3566 } // namespace el