easylogging++.cc 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996
  1. //
  2. // Bismillah ar-Rahmaan ar-Raheem
  3. //
  4. // Easylogging++ v9.95.3
  5. // Cross-platform logging library for C++ applications
  6. //
  7. // Copyright (c) 2017 muflihun.com
  8. //
  9. // This library is released under the MIT Licence.
  10. // http://labs.muflihun.com/easyloggingpp/licence.php
  11. //
  12. // https://github.com/muflihun/easyloggingpp
  13. // https://muflihun.github.io/easyloggingpp
  14. // http://muflihun.com
  15. //
  16. #include "easylogging++.h"
  17. #if defined(AUTO_INITIALIZE_EASYLOGGINGPP)
  18. INITIALIZE_EASYLOGGINGPP
  19. #endif
  20. namespace el {
  21. // el::base::utils
  22. namespace base {
  23. namespace utils {
  24. /// @brief Aborts application due with user-defined status
  25. static void abort(int status, const std::string& reason) {
  26. // Both status and reason params are there for debugging with tools like gdb etc
  27. ELPP_UNUSED(status);
  28. ELPP_UNUSED(reason);
  29. #if defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG)
  30. // Ignore msvc critical error dialog - break instead (on debug mode)
  31. _asm int 3
  32. #else
  33. ::abort();
  34. #endif // defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG)
  35. }
  36. } // namespace utils
  37. } // namespace base
  38. // el
  39. // LevelHelper
  40. const char* LevelHelper::convertToString(Level level) {
  41. // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet.
  42. if (level == Level::Global) return "GLOBAL";
  43. if (level == Level::Debug) return "DEBUG";
  44. if (level == Level::Info) return "INFO";
  45. if (level == Level::Warning) return "WARNING";
  46. if (level == Level::Error) return "ERROR";
  47. if (level == Level::Fatal) return "FATAL";
  48. if (level == Level::Verbose) return "VERBOSE";
  49. if (level == Level::Trace) return "TRACE";
  50. return "UNKNOWN";
  51. }
  52. struct StringToLevelItem {
  53. const char* levelString;
  54. Level level;
  55. };
  56. static struct StringToLevelItem stringToLevelMap[] = {
  57. { "global", Level::Global },
  58. { "debug", Level::Debug },
  59. { "info", Level::Info },
  60. { "warning", Level::Warning },
  61. { "error", Level::Error },
  62. { "fatal", Level::Fatal },
  63. { "verbose", Level::Verbose },
  64. { "trace", Level::Trace }
  65. };
  66. Level LevelHelper::convertFromString(const char* levelStr) {
  67. for (auto& item : stringToLevelMap) {
  68. if (base::utils::Str::cStringCaseEq(levelStr, item.levelString)) {
  69. return item.level;
  70. }
  71. }
  72. return Level::Unknown;
  73. }
  74. void LevelHelper::forEachLevel(base::type::EnumType* startIndex, const std::function<bool(void)>& fn) {
  75. base::type::EnumType lIndexMax = LevelHelper::kMaxValid;
  76. do {
  77. if (fn()) {
  78. break;
  79. }
  80. *startIndex = static_cast<base::type::EnumType>(*startIndex << 1);
  81. } while (*startIndex <= lIndexMax);
  82. }
  83. // ConfigurationTypeHelper
  84. const char* ConfigurationTypeHelper::convertToString(ConfigurationType configurationType) {
  85. // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet.
  86. if (configurationType == ConfigurationType::Enabled) return "ENABLED";
  87. if (configurationType == ConfigurationType::Filename) return "FILENAME";
  88. if (configurationType == ConfigurationType::Format) return "FORMAT";
  89. if (configurationType == ConfigurationType::ToFile) return "TO_FILE";
  90. if (configurationType == ConfigurationType::ToStandardOutput) return "TO_STANDARD_OUTPUT";
  91. if (configurationType == ConfigurationType::SubsecondPrecision) return "SUBSECOND_PRECISION";
  92. if (configurationType == ConfigurationType::PerformanceTracking) return "PERFORMANCE_TRACKING";
  93. if (configurationType == ConfigurationType::MaxLogFileSize) return "MAX_LOG_FILE_SIZE";
  94. if (configurationType == ConfigurationType::LogFlushThreshold) return "LOG_FLUSH_THRESHOLD";
  95. return "UNKNOWN";
  96. }
  97. struct ConfigurationStringToTypeItem {
  98. const char* configString;
  99. ConfigurationType configType;
  100. };
  101. static struct ConfigurationStringToTypeItem configStringToTypeMap[] = {
  102. { "enabled", ConfigurationType::Enabled },
  103. { "to_file", ConfigurationType::ToFile },
  104. { "to_standard_output", ConfigurationType::ToStandardOutput },
  105. { "format", ConfigurationType::Format },
  106. { "filename", ConfigurationType::Filename },
  107. { "subsecond_precision", ConfigurationType::SubsecondPrecision },
  108. { "milliseconds_width", ConfigurationType::MillisecondsWidth },
  109. { "performance_tracking", ConfigurationType::PerformanceTracking },
  110. { "max_log_file_size", ConfigurationType::MaxLogFileSize },
  111. { "log_flush_threshold", ConfigurationType::LogFlushThreshold },
  112. };
  113. ConfigurationType ConfigurationTypeHelper::convertFromString(const char* configStr) {
  114. for (auto& item : configStringToTypeMap) {
  115. if (base::utils::Str::cStringCaseEq(configStr, item.configString)) {
  116. return item.configType;
  117. }
  118. }
  119. return ConfigurationType::Unknown;
  120. }
  121. void ConfigurationTypeHelper::forEachConfigType(base::type::EnumType* startIndex, const std::function<bool(void)>& fn) {
  122. base::type::EnumType cIndexMax = ConfigurationTypeHelper::kMaxValid;
  123. do {
  124. if (fn()) {
  125. break;
  126. }
  127. *startIndex = static_cast<base::type::EnumType>(*startIndex << 1);
  128. } while (*startIndex <= cIndexMax);
  129. }
  130. // Configuration
  131. Configuration::Configuration(const Configuration& c) :
  132. m_level(c.m_level),
  133. m_configurationType(c.m_configurationType),
  134. m_value(c.m_value) {
  135. }
  136. Configuration& Configuration::operator=(const Configuration& c) {
  137. if (&c != this) {
  138. m_level = c.m_level;
  139. m_configurationType = c.m_configurationType;
  140. m_value = c.m_value;
  141. }
  142. return *this;
  143. }
  144. /// @brief Full constructor used to sets value of configuration
  145. Configuration::Configuration(Level level, ConfigurationType configurationType, const std::string& value) :
  146. m_level(level),
  147. m_configurationType(configurationType),
  148. m_value(value) {
  149. }
  150. void Configuration::log(el::base::type::ostream_t& os) const {
  151. os << LevelHelper::convertToString(m_level)
  152. << ELPP_LITERAL(" ") << ConfigurationTypeHelper::convertToString(m_configurationType)
  153. << ELPP_LITERAL(" = ") << m_value.c_str();
  154. }
  155. /// @brief Used to find configuration from configuration (pointers) repository. Avoid using it.
  156. Configuration::Predicate::Predicate(Level level, ConfigurationType configurationType) :
  157. m_level(level),
  158. m_configurationType(configurationType) {
  159. }
  160. bool Configuration::Predicate::operator()(const Configuration* conf) const {
  161. return ((conf != nullptr) && (conf->level() == m_level) && (conf->configurationType() == m_configurationType));
  162. }
  163. // Configurations
  164. Configurations::Configurations(void) :
  165. m_configurationFile(std::string()),
  166. m_isFromFile(false) {
  167. }
  168. Configurations::Configurations(const std::string& configurationFile, bool useDefaultsForRemaining,
  169. Configurations* base) :
  170. m_configurationFile(configurationFile),
  171. m_isFromFile(false) {
  172. parseFromFile(configurationFile, base);
  173. if (useDefaultsForRemaining) {
  174. setRemainingToDefault();
  175. }
  176. }
  177. bool Configurations::parseFromFile(const std::string& configurationFile, Configurations* base) {
  178. // We initial assertion with true because if we have assertion diabled, we want to pass this
  179. // check and if assertion is enabled we will have values re-assigned any way.
  180. bool assertionPassed = true;
  181. ELPP_ASSERT((assertionPassed = base::utils::File::pathExists(configurationFile.c_str(), true)) == true,
  182. "Configuration file [" << configurationFile << "] does not exist!");
  183. if (!assertionPassed) {
  184. return false;
  185. }
  186. bool success = Parser::parseFromFile(configurationFile, this, base);
  187. m_isFromFile = success;
  188. return success;
  189. }
  190. bool Configurations::parseFromText(const std::string& configurationsString, Configurations* base) {
  191. bool success = Parser::parseFromText(configurationsString, this, base);
  192. if (success) {
  193. m_isFromFile = false;
  194. }
  195. return success;
  196. }
  197. void Configurations::setFromBase(Configurations* base) {
  198. if (base == nullptr || base == this) {
  199. return;
  200. }
  201. base::threading::ScopedLock scopedLock(base->lock());
  202. for (Configuration*& conf : base->list()) {
  203. set(conf);
  204. }
  205. }
  206. bool Configurations::hasConfiguration(ConfigurationType configurationType) {
  207. base::type::EnumType lIndex = LevelHelper::kMinValid;
  208. bool result = false;
  209. LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
  210. if (hasConfiguration(LevelHelper::castFromInt(lIndex), configurationType)) {
  211. result = true;
  212. }
  213. return result;
  214. });
  215. return result;
  216. }
  217. bool Configurations::hasConfiguration(Level level, ConfigurationType configurationType) {
  218. base::threading::ScopedLock scopedLock(lock());
  219. #if ELPP_COMPILER_INTEL
  220. // We cant specify template types here, Intel C++ throws compilation error
  221. // "error: type name is not allowed"
  222. return RegistryWithPred::get(level, configurationType) != nullptr;
  223. #else
  224. return RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType) != nullptr;
  225. #endif // ELPP_COMPILER_INTEL
  226. }
  227. void Configurations::set(Level level, ConfigurationType configurationType, const std::string& value) {
  228. base::threading::ScopedLock scopedLock(lock());
  229. unsafeSet(level, configurationType, value); // This is not unsafe anymore as we have locked mutex
  230. if (level == Level::Global) {
  231. unsafeSetGlobally(configurationType, value, false); // Again this is not unsafe either
  232. }
  233. }
  234. void Configurations::set(Configuration* conf) {
  235. if (conf == nullptr) {
  236. return;
  237. }
  238. set(conf->level(), conf->configurationType(), conf->value());
  239. }
  240. void Configurations::setToDefault(void) {
  241. setGlobally(ConfigurationType::Enabled, std::string("true"), true);
  242. #if !defined(ELPP_NO_DEFAULT_LOG_FILE)
  243. setGlobally(ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile), true);
  244. #else
  245. ELPP_UNUSED(base::consts::kDefaultLogFile);
  246. #endif // !defined(ELPP_NO_DEFAULT_LOG_FILE)
  247. #if defined(ELPP_NO_LOG_TO_FILE)
  248. setGlobally(ConfigurationType::ToFile, std::string("false"), true);
  249. #else
  250. setGlobally(ConfigurationType::ToFile, std::string("true"), true);
  251. #endif // defined(ELPP_NO_LOG_TO_FILE)
  252. setGlobally(ConfigurationType::ToStandardOutput, std::string("true"), true);
  253. setGlobally(ConfigurationType::SubsecondPrecision, std::string("3"), true);
  254. setGlobally(ConfigurationType::PerformanceTracking, std::string("true"), true);
  255. setGlobally(ConfigurationType::MaxLogFileSize, std::string("0"), true);
  256. setGlobally(ConfigurationType::LogFlushThreshold, std::string("0"), true);
  257. setGlobally(ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"), true);
  258. set(Level::Debug, ConfigurationType::Format,
  259. std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg"));
  260. // INFO and WARNING are set to default by Level::Global
  261. set(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
  262. set(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
  263. set(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg"));
  264. set(Level::Trace, ConfigurationType::Format, std::string("%datetime %level [%logger] [%func] [%loc] %msg"));
  265. }
  266. void Configurations::setRemainingToDefault(void) {
  267. base::threading::ScopedLock scopedLock(lock());
  268. #if defined(ELPP_NO_LOG_TO_FILE)
  269. unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("false"));
  270. #else
  271. unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("true"));
  272. #endif // defined(ELPP_NO_LOG_TO_FILE)
  273. #if !defined(ELPP_NO_DEFAULT_LOG_FILE)
  274. unsafeSetIfNotExist(Level::Global, ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile));
  275. #endif // !defined(ELPP_NO_DEFAULT_LOG_FILE)
  276. unsafeSetIfNotExist(Level::Global, ConfigurationType::ToStandardOutput, std::string("true"));
  277. unsafeSetIfNotExist(Level::Global, ConfigurationType::SubsecondPrecision, std::string("3"));
  278. unsafeSetIfNotExist(Level::Global, ConfigurationType::PerformanceTracking, std::string("true"));
  279. unsafeSetIfNotExist(Level::Global, ConfigurationType::MaxLogFileSize, std::string("0"));
  280. unsafeSetIfNotExist(Level::Global, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
  281. unsafeSetIfNotExist(Level::Debug, ConfigurationType::Format,
  282. std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg"));
  283. // INFO and WARNING are set to default by Level::Global
  284. unsafeSetIfNotExist(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
  285. unsafeSetIfNotExist(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
  286. unsafeSetIfNotExist(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg"));
  287. unsafeSetIfNotExist(Level::Trace, ConfigurationType::Format,
  288. std::string("%datetime %level [%logger] [%func] [%loc] %msg"));
  289. }
  290. bool Configurations::Parser::parseFromFile(const std::string& configurationFile, Configurations* sender,
  291. Configurations* base) {
  292. sender->setFromBase(base);
  293. std::ifstream fileStream_(configurationFile.c_str(), std::ifstream::in);
  294. ELPP_ASSERT(fileStream_.is_open(), "Unable to open configuration file [" << configurationFile << "] for parsing.");
  295. bool parsedSuccessfully = false;
  296. std::string line = std::string();
  297. Level currLevel = Level::Unknown;
  298. std::string currConfigStr = std::string();
  299. std::string currLevelStr = std::string();
  300. while (fileStream_.good()) {
  301. std::getline(fileStream_, line);
  302. parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender);
  303. ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line);
  304. }
  305. return parsedSuccessfully;
  306. }
  307. bool Configurations::Parser::parseFromText(const std::string& configurationsString, Configurations* sender,
  308. Configurations* base) {
  309. sender->setFromBase(base);
  310. bool parsedSuccessfully = false;
  311. std::stringstream ss(configurationsString);
  312. std::string line = std::string();
  313. Level currLevel = Level::Unknown;
  314. std::string currConfigStr = std::string();
  315. std::string currLevelStr = std::string();
  316. while (std::getline(ss, line)) {
  317. parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender);
  318. ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line);
  319. }
  320. return parsedSuccessfully;
  321. }
  322. void Configurations::Parser::ignoreComments(std::string* line) {
  323. std::size_t foundAt = 0;
  324. std::size_t quotesStart = line->find("\"");
  325. std::size_t quotesEnd = std::string::npos;
  326. if (quotesStart != std::string::npos) {
  327. quotesEnd = line->find("\"", quotesStart + 1);
  328. while (quotesEnd != std::string::npos && line->at(quotesEnd - 1) == '\\') {
  329. // Do not erase slash yet - we will erase it in parseLine(..) while loop
  330. quotesEnd = line->find("\"", quotesEnd + 2);
  331. }
  332. }
  333. if ((foundAt = line->find(base::consts::kConfigurationComment)) != std::string::npos) {
  334. if (foundAt < quotesEnd) {
  335. foundAt = line->find(base::consts::kConfigurationComment, quotesEnd + 1);
  336. }
  337. *line = line->substr(0, foundAt);
  338. }
  339. }
  340. bool Configurations::Parser::isLevel(const std::string& line) {
  341. return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLevel));
  342. }
  343. bool Configurations::Parser::isComment(const std::string& line) {
  344. return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationComment));
  345. }
  346. bool Configurations::Parser::isConfig(const std::string& line) {
  347. std::size_t assignment = line.find('=');
  348. return line != "" &&
  349. ((line[0] >= 'A' && line[0] <= 'Z') || (line[0] >= 'a' && line[0] <= 'z')) &&
  350. (assignment != std::string::npos) &&
  351. (line.size() > assignment);
  352. }
  353. bool Configurations::Parser::parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr,
  354. Level* currLevel,
  355. Configurations* conf) {
  356. ConfigurationType currConfig = ConfigurationType::Unknown;
  357. std::string currValue = std::string();
  358. *line = base::utils::Str::trim(*line);
  359. if (isComment(*line)) return true;
  360. ignoreComments(line);
  361. *line = base::utils::Str::trim(*line);
  362. if (line->empty()) {
  363. // Comment ignored
  364. return true;
  365. }
  366. if (isLevel(*line)) {
  367. if (line->size() <= 2) {
  368. return true;
  369. }
  370. *currLevelStr = line->substr(1, line->size() - 2);
  371. *currLevelStr = base::utils::Str::toUpper(*currLevelStr);
  372. *currLevelStr = base::utils::Str::trim(*currLevelStr);
  373. *currLevel = LevelHelper::convertFromString(currLevelStr->c_str());
  374. return true;
  375. }
  376. if (isConfig(*line)) {
  377. std::size_t assignment = line->find('=');
  378. *currConfigStr = line->substr(0, assignment);
  379. *currConfigStr = base::utils::Str::toUpper(*currConfigStr);
  380. *currConfigStr = base::utils::Str::trim(*currConfigStr);
  381. currConfig = ConfigurationTypeHelper::convertFromString(currConfigStr->c_str());
  382. currValue = line->substr(assignment + 1);
  383. currValue = base::utils::Str::trim(currValue);
  384. std::size_t quotesStart = currValue.find("\"", 0);
  385. std::size_t quotesEnd = std::string::npos;
  386. if (quotesStart != std::string::npos) {
  387. quotesEnd = currValue.find("\"", quotesStart + 1);
  388. while (quotesEnd != std::string::npos && currValue.at(quotesEnd - 1) == '\\') {
  389. currValue = currValue.erase(quotesEnd - 1, 1);
  390. quotesEnd = currValue.find("\"", quotesEnd + 2);
  391. }
  392. }
  393. if (quotesStart != std::string::npos && quotesEnd != std::string::npos) {
  394. // Quote provided - check and strip if valid
  395. ELPP_ASSERT((quotesStart < quotesEnd), "Configuration error - No ending quote found in ["
  396. << currConfigStr << "]");
  397. ELPP_ASSERT((quotesStart + 1 != quotesEnd), "Empty configuration value for [" << currConfigStr << "]");
  398. if ((quotesStart != quotesEnd) && (quotesStart + 1 != quotesEnd)) {
  399. // Explicit check in case if assertion is disabled
  400. currValue = currValue.substr(quotesStart + 1, quotesEnd - 1);
  401. }
  402. }
  403. }
  404. ELPP_ASSERT(*currLevel != Level::Unknown, "Unrecognized severity level [" << *currLevelStr << "]");
  405. ELPP_ASSERT(currConfig != ConfigurationType::Unknown, "Unrecognized configuration [" << *currConfigStr << "]");
  406. if (*currLevel == Level::Unknown || currConfig == ConfigurationType::Unknown) {
  407. return false; // unrecognizable level or config
  408. }
  409. conf->set(*currLevel, currConfig, currValue);
  410. return true;
  411. }
  412. void Configurations::unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value) {
  413. Configuration* conf = RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType);
  414. if (conf == nullptr) {
  415. unsafeSet(level, configurationType, value);
  416. }
  417. }
  418. void Configurations::unsafeSet(Level level, ConfigurationType configurationType, const std::string& value) {
  419. Configuration* conf = RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType);
  420. if (conf == nullptr) {
  421. registerNew(new Configuration(level, configurationType, value));
  422. } else {
  423. conf->setValue(value);
  424. }
  425. if (level == Level::Global) {
  426. unsafeSetGlobally(configurationType, value, false);
  427. }
  428. }
  429. void Configurations::setGlobally(ConfigurationType configurationType, const std::string& value,
  430. bool includeGlobalLevel) {
  431. if (includeGlobalLevel) {
  432. set(Level::Global, configurationType, value);
  433. }
  434. base::type::EnumType lIndex = LevelHelper::kMinValid;
  435. LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
  436. set(LevelHelper::castFromInt(lIndex), configurationType, value);
  437. return false; // Do not break lambda function yet as we need to set all levels regardless
  438. });
  439. }
  440. void Configurations::unsafeSetGlobally(ConfigurationType configurationType, const std::string& value,
  441. bool includeGlobalLevel) {
  442. if (includeGlobalLevel) {
  443. unsafeSet(Level::Global, configurationType, value);
  444. }
  445. base::type::EnumType lIndex = LevelHelper::kMinValid;
  446. LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
  447. unsafeSet(LevelHelper::castFromInt(lIndex), configurationType, value);
  448. return false; // Do not break lambda function yet as we need to set all levels regardless
  449. });
  450. }
  451. // LogBuilder
  452. void LogBuilder::convertToColoredOutput(base::type::string_t* logLine, Level level) {
  453. if (!m_termSupportsColor) return;
  454. const base::type::char_t* resetColor = ELPP_LITERAL("\x1b[0m");
  455. if (level == Level::Error || level == Level::Fatal)
  456. *logLine = ELPP_LITERAL("\x1b[31m") + *logLine + resetColor;
  457. else if (level == Level::Warning)
  458. *logLine = ELPP_LITERAL("\x1b[33m") + *logLine + resetColor;
  459. else if (level == Level::Debug)
  460. *logLine = ELPP_LITERAL("\x1b[32m") + *logLine + resetColor;
  461. else if (level == Level::Info)
  462. *logLine = ELPP_LITERAL("\x1b[36m") + *logLine + resetColor;
  463. else if (level == Level::Trace)
  464. *logLine = ELPP_LITERAL("\x1b[35m") + *logLine + resetColor;
  465. }
  466. // Logger
  467. Logger::Logger(const std::string& id, base::LogStreamsReferenceMap* logStreamsReference) :
  468. m_id(id),
  469. m_typedConfigurations(nullptr),
  470. m_parentApplicationName(std::string()),
  471. m_isConfigured(false),
  472. m_logStreamsReference(logStreamsReference) {
  473. initUnflushedCount();
  474. }
  475. Logger::Logger(const std::string& id, const Configurations& configurations,
  476. base::LogStreamsReferenceMap* logStreamsReference) :
  477. m_id(id),
  478. m_typedConfigurations(nullptr),
  479. m_parentApplicationName(std::string()),
  480. m_isConfigured(false),
  481. m_logStreamsReference(logStreamsReference) {
  482. initUnflushedCount();
  483. configure(configurations);
  484. }
  485. Logger::Logger(const Logger& logger) {
  486. base::utils::safeDelete(m_typedConfigurations);
  487. m_id = logger.m_id;
  488. m_typedConfigurations = logger.m_typedConfigurations;
  489. m_parentApplicationName = logger.m_parentApplicationName;
  490. m_isConfigured = logger.m_isConfigured;
  491. m_configurations = logger.m_configurations;
  492. m_unflushedCount = logger.m_unflushedCount;
  493. m_logStreamsReference = logger.m_logStreamsReference;
  494. }
  495. Logger& Logger::operator=(const Logger& logger) {
  496. if (&logger != this) {
  497. base::utils::safeDelete(m_typedConfigurations);
  498. m_id = logger.m_id;
  499. m_typedConfigurations = logger.m_typedConfigurations;
  500. m_parentApplicationName = logger.m_parentApplicationName;
  501. m_isConfigured = logger.m_isConfigured;
  502. m_configurations = logger.m_configurations;
  503. m_unflushedCount = logger.m_unflushedCount;
  504. m_logStreamsReference = logger.m_logStreamsReference;
  505. }
  506. return *this;
  507. }
  508. void Logger::configure(const Configurations& configurations) {
  509. m_isConfigured = false; // we set it to false in case if we fail
  510. initUnflushedCount();
  511. if (m_typedConfigurations != nullptr) {
  512. Configurations* c = const_cast<Configurations*>(m_typedConfigurations->configurations());
  513. if (c->hasConfiguration(Level::Global, ConfigurationType::Filename)) {
  514. // This check is definitely needed for cases like ELPP_NO_DEFAULT_LOG_FILE
  515. flush();
  516. }
  517. }
  518. base::threading::ScopedLock scopedLock(lock());
  519. if (m_configurations != configurations) {
  520. m_configurations.setFromBase(const_cast<Configurations*>(&configurations));
  521. }
  522. base::utils::safeDelete(m_typedConfigurations);
  523. m_typedConfigurations = new base::TypedConfigurations(&m_configurations, m_logStreamsReference);
  524. resolveLoggerFormatSpec();
  525. m_isConfigured = true;
  526. }
  527. void Logger::reconfigure(void) {
  528. ELPP_INTERNAL_INFO(1, "Reconfiguring logger [" << m_id << "]");
  529. configure(m_configurations);
  530. }
  531. bool Logger::isValidId(const std::string& id) {
  532. for (std::string::const_iterator it = id.begin(); it != id.end(); ++it) {
  533. if (!base::utils::Str::contains(base::consts::kValidLoggerIdSymbols, *it)) {
  534. return false;
  535. }
  536. }
  537. return true;
  538. }
  539. void Logger::flush(void) {
  540. ELPP_INTERNAL_INFO(3, "Flushing logger [" << m_id << "] all levels");
  541. base::threading::ScopedLock scopedLock(lock());
  542. base::type::EnumType lIndex = LevelHelper::kMinValid;
  543. LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
  544. flush(LevelHelper::castFromInt(lIndex), nullptr);
  545. return false;
  546. });
  547. }
  548. void Logger::flush(Level level, base::type::fstream_t* fs) {
  549. if (fs == nullptr && m_typedConfigurations->toFile(level)) {
  550. fs = m_typedConfigurations->fileStream(level);
  551. }
  552. if (fs != nullptr) {
  553. fs->flush();
  554. std::map<Level, unsigned int>::iterator iter = m_unflushedCount.find(level);
  555. if (iter != m_unflushedCount.end()) {
  556. iter->second = 0;
  557. }
  558. }
  559. }
  560. void Logger::initUnflushedCount(void) {
  561. m_unflushedCount.clear();
  562. base::type::EnumType lIndex = LevelHelper::kMinValid;
  563. LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
  564. m_unflushedCount.insert(std::make_pair(LevelHelper::castFromInt(lIndex), 0));
  565. return false;
  566. });
  567. }
  568. void Logger::resolveLoggerFormatSpec(void) const {
  569. base::type::EnumType lIndex = LevelHelper::kMinValid;
  570. LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
  571. base::LogFormat* logFormat =
  572. const_cast<base::LogFormat*>(&m_typedConfigurations->logFormat(LevelHelper::castFromInt(lIndex)));
  573. base::utils::Str::replaceFirstWithEscape(logFormat->m_format, base::consts::kLoggerIdFormatSpecifier, m_id);
  574. return false;
  575. });
  576. }
  577. // el::base
  578. namespace base {
  579. // el::base::utils
  580. namespace utils {
  581. // File
  582. base::type::fstream_t* File::newFileStream(const std::string& filename) {
  583. base::type::fstream_t *fs = new base::type::fstream_t(filename.c_str(),
  584. base::type::fstream_t::out
  585. #if !defined(ELPP_FRESH_LOG_FILE)
  586. | base::type::fstream_t::app
  587. #endif
  588. );
  589. #if defined(ELPP_UNICODE)
  590. std::locale elppUnicodeLocale("");
  591. # if ELPP_OS_WINDOWS
  592. std::locale elppUnicodeLocaleWindows(elppUnicodeLocale, new std::codecvt_utf8_utf16<wchar_t>);
  593. elppUnicodeLocale = elppUnicodeLocaleWindows;
  594. # endif // ELPP_OS_WINDOWS
  595. fs->imbue(elppUnicodeLocale);
  596. #endif // defined(ELPP_UNICODE)
  597. if (fs->is_open()) {
  598. fs->flush();
  599. } else {
  600. base::utils::safeDelete(fs);
  601. ELPP_INTERNAL_ERROR("Bad file [" << filename << "]", true);
  602. }
  603. return fs;
  604. }
  605. std::size_t File::getSizeOfFile(base::type::fstream_t* fs) {
  606. if (fs == nullptr) {
  607. return 0;
  608. }
  609. std::streampos currPos = fs->tellg();
  610. fs->seekg(0, fs->end);
  611. std::size_t size = static_cast<std::size_t>(fs->tellg());
  612. fs->seekg(currPos);
  613. return size;
  614. }
  615. bool File::pathExists(const char* path, bool considerFile) {
  616. if (path == nullptr) {
  617. return false;
  618. }
  619. #if ELPP_OS_UNIX
  620. ELPP_UNUSED(considerFile);
  621. struct stat st;
  622. return (stat(path, &st) == 0);
  623. #elif ELPP_OS_WINDOWS
  624. DWORD fileType = GetFileAttributesA(path);
  625. if (fileType == INVALID_FILE_ATTRIBUTES) {
  626. return false;
  627. }
  628. return considerFile ? true : ((fileType & FILE_ATTRIBUTE_DIRECTORY) == 0 ? false : true);
  629. #endif // ELPP_OS_UNIX
  630. }
  631. bool File::createPath(const std::string& path) {
  632. if (path.empty()) {
  633. return false;
  634. }
  635. if (base::utils::File::pathExists(path.c_str())) {
  636. return true;
  637. }
  638. int status = -1;
  639. char* currPath = const_cast<char*>(path.c_str());
  640. std::string builtPath = std::string();
  641. #if ELPP_OS_UNIX
  642. if (path[0] == '/') {
  643. builtPath = "/";
  644. }
  645. currPath = STRTOK(currPath, base::consts::kFilePathSeperator, 0);
  646. #elif ELPP_OS_WINDOWS
  647. // Use secure functions API
  648. char* nextTok_ = nullptr;
  649. currPath = STRTOK(currPath, base::consts::kFilePathSeperator, &nextTok_);
  650. ELPP_UNUSED(nextTok_);
  651. #endif // ELPP_OS_UNIX
  652. while (currPath != nullptr) {
  653. builtPath.append(currPath);
  654. builtPath.append(base::consts::kFilePathSeperator);
  655. #if ELPP_OS_UNIX
  656. status = mkdir(builtPath.c_str(), ELPP_LOG_PERMS);
  657. currPath = STRTOK(nullptr, base::consts::kFilePathSeperator, 0);
  658. #elif ELPP_OS_WINDOWS
  659. status = _mkdir(builtPath.c_str());
  660. currPath = STRTOK(nullptr, base::consts::kFilePathSeperator, &nextTok_);
  661. #endif // ELPP_OS_UNIX
  662. }
  663. if (status == -1) {
  664. ELPP_INTERNAL_ERROR("Error while creating path [" << path << "]", true);
  665. return false;
  666. }
  667. return true;
  668. }
  669. std::string File::extractPathFromFilename(const std::string& fullPath, const char* separator) {
  670. if ((fullPath == "") || (fullPath.find(separator) == std::string::npos)) {
  671. return fullPath;
  672. }
  673. std::size_t lastSlashAt = fullPath.find_last_of(separator);
  674. if (lastSlashAt == 0) {
  675. return std::string(separator);
  676. }
  677. return fullPath.substr(0, lastSlashAt + 1);
  678. }
  679. void File::buildStrippedFilename(const char* filename, char buff[], std::size_t limit) {
  680. std::size_t sizeOfFilename = strlen(filename);
  681. if (sizeOfFilename >= limit) {
  682. filename += (sizeOfFilename - limit);
  683. if (filename[0] != '.' && filename[1] != '.') { // prepend if not already
  684. filename += 3; // 3 = '..'
  685. STRCAT(buff, "..", limit);
  686. }
  687. }
  688. STRCAT(buff, filename, limit);
  689. }
  690. void File::buildBaseFilename(const std::string& fullPath, char buff[], std::size_t limit, const char* separator) {
  691. const char *filename = fullPath.c_str();
  692. std::size_t lastSlashAt = fullPath.find_last_of(separator);
  693. filename += lastSlashAt ? lastSlashAt+1 : 0;
  694. std::size_t sizeOfFilename = strlen(filename);
  695. if (sizeOfFilename >= limit) {
  696. filename += (sizeOfFilename - limit);
  697. if (filename[0] != '.' && filename[1] != '.') { // prepend if not already
  698. filename += 3; // 3 = '..'
  699. STRCAT(buff, "..", limit);
  700. }
  701. }
  702. STRCAT(buff, filename, limit);
  703. }
  704. // Str
  705. bool Str::wildCardMatch(const char* str, const char* pattern) {
  706. while (*pattern) {
  707. switch (*pattern) {
  708. case '?':
  709. if (!*str)
  710. return false;
  711. ++str;
  712. ++pattern;
  713. break;
  714. case '*':
  715. if (wildCardMatch(str, pattern + 1))
  716. return true;
  717. if (*str && wildCardMatch(str + 1, pattern))
  718. return true;
  719. return false;
  720. default:
  721. if (*str++ != *pattern++)
  722. return false;
  723. break;
  724. }
  725. }
  726. return !*str && !*pattern;
  727. }
  728. std::string& Str::ltrim(std::string& str) {
  729. str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](char c) {
  730. return !std::isspace(c);
  731. } ));
  732. return str;
  733. }
  734. std::string& Str::rtrim(std::string& str) {
  735. str.erase(std::find_if(str.rbegin(), str.rend(), [](char c) {
  736. return !std::isspace(c);
  737. }).base(), str.end());
  738. return str;
  739. }
  740. std::string& Str::trim(std::string& str) {
  741. return ltrim(rtrim(str));
  742. }
  743. bool Str::startsWith(const std::string& str, const std::string& start) {
  744. return (str.length() >= start.length()) && (str.compare(0, start.length(), start) == 0);
  745. }
  746. bool Str::endsWith(const std::string& str, const std::string& end) {
  747. return (str.length() >= end.length()) && (str.compare(str.length() - end.length(), end.length(), end) == 0);
  748. }
  749. std::string& Str::replaceAll(std::string& str, char replaceWhat, char replaceWith) {
  750. std::replace(str.begin(), str.end(), replaceWhat, replaceWith);
  751. return str;
  752. }
  753. std::string& Str::replaceAll(std::string& str, const std::string& replaceWhat,
  754. const std::string& replaceWith) {
  755. if (replaceWhat == replaceWith)
  756. return str;
  757. std::size_t foundAt = std::string::npos;
  758. while ((foundAt = str.find(replaceWhat, foundAt + 1)) != std::string::npos) {
  759. str.replace(foundAt, replaceWhat.length(), replaceWith);
  760. }
  761. return str;
  762. }
  763. void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
  764. const base::type::string_t& replaceWith) {
  765. std::size_t foundAt = base::type::string_t::npos;
  766. while ((foundAt = str.find(replaceWhat, foundAt + 1)) != base::type::string_t::npos) {
  767. if (foundAt > 0 && str[foundAt - 1] == base::consts::kFormatSpecifierChar) {
  768. str.erase(foundAt > 0 ? foundAt - 1 : 0, 1);
  769. ++foundAt;
  770. } else {
  771. str.replace(foundAt, replaceWhat.length(), replaceWith);
  772. return;
  773. }
  774. }
  775. }
  776. #if defined(ELPP_UNICODE)
  777. void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
  778. const std::string& replaceWith) {
  779. replaceFirstWithEscape(str, replaceWhat, base::type::string_t(replaceWith.begin(), replaceWith.end()));
  780. }
  781. #endif // defined(ELPP_UNICODE)
  782. std::string& Str::toUpper(std::string& str) {
  783. std::transform(str.begin(), str.end(), str.begin(),
  784. [](char c) {
  785. return static_cast<char>(::toupper(c));
  786. });
  787. return str;
  788. }
  789. bool Str::cStringEq(const char* s1, const char* s2) {
  790. if (s1 == nullptr && s2 == nullptr) return true;
  791. if (s1 == nullptr || s2 == nullptr) return false;
  792. return strcmp(s1, s2) == 0;
  793. }
  794. bool Str::cStringCaseEq(const char* s1, const char* s2) {
  795. if (s1 == nullptr && s2 == nullptr) return true;
  796. if (s1 == nullptr || s2 == nullptr) return false;
  797. // With thanks to cygwin for this code
  798. int d = 0;
  799. while (true) {
  800. const int c1 = toupper(*s1++);
  801. const int c2 = toupper(*s2++);
  802. if (((d = c1 - c2) != 0) || (c2 == '\0')) {
  803. break;
  804. }
  805. }
  806. return d == 0;
  807. }
  808. bool Str::contains(const char* str, char c) {
  809. for (; *str; ++str) {
  810. if (*str == c)
  811. return true;
  812. }
  813. return false;
  814. }
  815. char* Str::convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded) {
  816. char localBuff[10] = "";
  817. char* p = localBuff + sizeof(localBuff) - 2;
  818. if (n > 0) {
  819. for (; n > 0 && p > localBuff && len > 0; n /= 10, --len)
  820. *--p = static_cast<char>(n % 10 + '0');
  821. } else {
  822. *--p = '0';
  823. --len;
  824. }
  825. if (zeroPadded)
  826. while (p > localBuff && len-- > 0) *--p = static_cast<char>('0');
  827. return addToBuff(p, buf, bufLim);
  828. }
  829. char* Str::addToBuff(const char* str, char* buf, const char* bufLim) {
  830. while ((buf < bufLim) && ((*buf = *str++) != '\0'))
  831. ++buf;
  832. return buf;
  833. }
  834. char* Str::clearBuff(char buff[], std::size_t lim) {
  835. STRCPY(buff, "", lim);
  836. ELPP_UNUSED(lim); // For *nix we dont have anything using lim in above STRCPY macro
  837. return buff;
  838. }
  839. /// @brief Converst wchar* to char*
  840. /// NOTE: Need to free return value after use!
  841. char* Str::wcharPtrToCharPtr(const wchar_t* line) {
  842. std::size_t len_ = wcslen(line) + 1;
  843. char* buff_ = static_cast<char*>(malloc(len_ + 1));
  844. # if ELPP_OS_UNIX || (ELPP_OS_WINDOWS && !ELPP_CRT_DBG_WARNINGS)
  845. std::wcstombs(buff_, line, len_);
  846. # elif ELPP_OS_WINDOWS
  847. std::size_t convCount_ = 0;
  848. mbstate_t mbState_;
  849. ::memset(static_cast<void*>(&mbState_), 0, sizeof(mbState_));
  850. wcsrtombs_s(&convCount_, buff_, len_, &line, len_, &mbState_);
  851. # endif // ELPP_OS_UNIX || (ELPP_OS_WINDOWS && !ELPP_CRT_DBG_WARNINGS)
  852. return buff_;
  853. }
  854. // OS
  855. #if ELPP_OS_WINDOWS
  856. /// @brief Gets environment variables for Windows based OS.
  857. /// We are not using <code>getenv(const char*)</code> because of CRT deprecation
  858. /// @param varname Variable name to get environment variable value for
  859. /// @return If variable exist the value of it otherwise nullptr
  860. const char* OS::getWindowsEnvironmentVariable(const char* varname) {
  861. const DWORD bufferLen = 50;
  862. static char buffer[bufferLen];
  863. if (GetEnvironmentVariableA(varname, buffer, bufferLen)) {
  864. return buffer;
  865. }
  866. return nullptr;
  867. }
  868. #endif // ELPP_OS_WINDOWS
  869. #if ELPP_OS_ANDROID
  870. std::string OS::getProperty(const char* prop) {
  871. char propVal[PROP_VALUE_MAX + 1];
  872. int ret = __system_property_get(prop, propVal);
  873. return ret == 0 ? std::string() : std::string(propVal);
  874. }
  875. std::string OS::getDeviceName(void) {
  876. std::stringstream ss;
  877. std::string manufacturer = getProperty("ro.product.manufacturer");
  878. std::string model = getProperty("ro.product.model");
  879. if (manufacturer.empty() || model.empty()) {
  880. return std::string();
  881. }
  882. ss << manufacturer << "-" << model;
  883. return ss.str();
  884. }
  885. #endif // ELPP_OS_ANDROID
  886. const std::string OS::getBashOutput(const char* command) {
  887. #if (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN)
  888. if (command == nullptr) {
  889. return std::string();
  890. }
  891. FILE* proc = nullptr;
  892. if ((proc = popen(command, "r")) == nullptr) {
  893. ELPP_INTERNAL_ERROR("\nUnable to run command [" << command << "]", true);
  894. return std::string();
  895. }
  896. char hBuff[4096];
  897. if (fgets(hBuff, sizeof(hBuff), proc) != nullptr) {
  898. pclose(proc);
  899. if (hBuff[strlen(hBuff) - 1] == '\n') {
  900. hBuff[strlen(hBuff) - 1] = '\0';
  901. }
  902. return std::string(hBuff);
  903. } else {
  904. pclose(proc);
  905. }
  906. return std::string();
  907. #else
  908. ELPP_UNUSED(command);
  909. return std::string();
  910. #endif // (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN)
  911. }
  912. std::string OS::getEnvironmentVariable(const char* variableName, const char* defaultVal,
  913. const char* alternativeBashCommand) {
  914. #if ELPP_OS_UNIX
  915. const char* val = getenv(variableName);
  916. #elif ELPP_OS_WINDOWS
  917. const char* val = getWindowsEnvironmentVariable(variableName);
  918. #endif // ELPP_OS_UNIX
  919. if ((val == nullptr) || ((strcmp(val, "") == 0))) {
  920. #if ELPP_OS_UNIX && defined(ELPP_FORCE_ENV_VAR_FROM_BASH)
  921. // Try harder on unix-based systems
  922. std::string valBash = base::utils::OS::getBashOutput(alternativeBashCommand);
  923. if (valBash.empty()) {
  924. return std::string(defaultVal);
  925. } else {
  926. return valBash;
  927. }
  928. #elif ELPP_OS_WINDOWS || ELPP_OS_UNIX
  929. ELPP_UNUSED(alternativeBashCommand);
  930. return std::string(defaultVal);
  931. #endif // ELPP_OS_UNIX && defined(ELPP_FORCE_ENV_VAR_FROM_BASH)
  932. }
  933. return std::string(val);
  934. }
  935. std::string OS::currentUser(void) {
  936. #if ELPP_OS_UNIX && !ELPP_OS_ANDROID
  937. return getEnvironmentVariable("USER", base::consts::kUnknownUser, "whoami");
  938. #elif ELPP_OS_WINDOWS
  939. return getEnvironmentVariable("USERNAME", base::consts::kUnknownUser);
  940. #elif ELPP_OS_ANDROID
  941. ELPP_UNUSED(base::consts::kUnknownUser);
  942. return std::string("android");
  943. #else
  944. return std::string();
  945. #endif // ELPP_OS_UNIX && !ELPP_OS_ANDROID
  946. }
  947. std::string OS::currentHost(void) {
  948. #if ELPP_OS_UNIX && !ELPP_OS_ANDROID
  949. return getEnvironmentVariable("HOSTNAME", base::consts::kUnknownHost, "hostname");
  950. #elif ELPP_OS_WINDOWS
  951. return getEnvironmentVariable("COMPUTERNAME", base::consts::kUnknownHost);
  952. #elif ELPP_OS_ANDROID
  953. ELPP_UNUSED(base::consts::kUnknownHost);
  954. return getDeviceName();
  955. #else
  956. return std::string();
  957. #endif // ELPP_OS_UNIX && !ELPP_OS_ANDROID
  958. }
  959. bool OS::termSupportsColor(void) {
  960. std::string term = getEnvironmentVariable("TERM", "");
  961. return term == "xterm" || term == "xterm-color" || term == "xterm-256color"
  962. || term == "screen" || term == "linux" || term == "cygwin"
  963. || term == "screen-256color";
  964. }
  965. // DateTime
  966. void DateTime::gettimeofday(struct timeval* tv) {
  967. #if ELPP_OS_WINDOWS
  968. if (tv != nullptr) {
  969. # if ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS)
  970. const unsigned __int64 delta_ = 11644473600000000Ui64;
  971. # else
  972. const unsigned __int64 delta_ = 11644473600000000ULL;
  973. # endif // ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS)
  974. const double secOffSet = 0.000001;
  975. const unsigned long usecOffSet = 1000000;
  976. FILETIME fileTime;
  977. GetSystemTimeAsFileTime(&fileTime);
  978. unsigned __int64 present = 0;
  979. present |= fileTime.dwHighDateTime;
  980. present = present << 32;
  981. present |= fileTime.dwLowDateTime;
  982. present /= 10; // mic-sec
  983. // Subtract the difference
  984. present -= delta_;
  985. tv->tv_sec = static_cast<long>(present * secOffSet);
  986. tv->tv_usec = static_cast<long>(present % usecOffSet);
  987. }
  988. #else
  989. ::gettimeofday(tv, nullptr);
  990. #endif // ELPP_OS_WINDOWS
  991. }
  992. std::string DateTime::getDateTime(const char* format, const base::SubsecondPrecision* ssPrec) {
  993. struct timeval currTime;
  994. gettimeofday(&currTime);
  995. return timevalToString(currTime, format, ssPrec);
  996. }
  997. std::string DateTime::timevalToString(struct timeval tval, const char* format,
  998. const el::base::SubsecondPrecision* ssPrec) {
  999. struct ::tm timeInfo;
  1000. buildTimeInfo(&tval, &timeInfo);
  1001. const int kBuffSize = 30;
  1002. char buff_[kBuffSize] = "";
  1003. parseFormat(buff_, kBuffSize, format, &timeInfo, static_cast<std::size_t>(tval.tv_usec / ssPrec->m_offset),
  1004. ssPrec);
  1005. return std::string(buff_);
  1006. }
  1007. base::type::string_t DateTime::formatTime(unsigned long long time, base::TimestampUnit timestampUnit) {
  1008. base::type::EnumType start = static_cast<base::type::EnumType>(timestampUnit);
  1009. const base::type::char_t* unit = base::consts::kTimeFormats[start].unit;
  1010. for (base::type::EnumType i = start; i < base::consts::kTimeFormatsCount - 1; ++i) {
  1011. if (time <= base::consts::kTimeFormats[i].value) {
  1012. break;
  1013. }
  1014. if (base::consts::kTimeFormats[i].value == 1000.0f && time / 1000.0f < 1.9f) {
  1015. break;
  1016. }
  1017. time /= static_cast<decltype(time)>(base::consts::kTimeFormats[i].value);
  1018. unit = base::consts::kTimeFormats[i + 1].unit;
  1019. }
  1020. base::type::stringstream_t ss;
  1021. ss << time << " " << unit;
  1022. return ss.str();
  1023. }
  1024. unsigned long long DateTime::getTimeDifference(const struct timeval& endTime, const struct timeval& startTime,
  1025. base::TimestampUnit timestampUnit) {
  1026. if (timestampUnit == base::TimestampUnit::Microsecond) {
  1027. return static_cast<unsigned long long>(static_cast<unsigned long long>(1000000 * endTime.tv_sec + endTime.tv_usec) -
  1028. static_cast<unsigned long long>(1000000 * startTime.tv_sec + startTime.tv_usec));
  1029. }
  1030. // milliseconds
  1031. auto conv = [](const struct timeval& tim) {
  1032. return static_cast<unsigned long long>((tim.tv_sec * 1000) + (tim.tv_usec / 1000));
  1033. };
  1034. return static_cast<unsigned long long>(conv(endTime) - conv(startTime));
  1035. }
  1036. struct ::tm* DateTime::buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo) {
  1037. #if ELPP_OS_UNIX
  1038. time_t rawTime = currTime->tv_sec;
  1039. ::elpptime_r(&rawTime, timeInfo);
  1040. return timeInfo;
  1041. #else
  1042. # if ELPP_COMPILER_MSVC
  1043. ELPP_UNUSED(currTime);
  1044. time_t t;
  1045. # if defined(_USE_32BIT_TIME_T)
  1046. _time32(&t);
  1047. # else
  1048. _time64(&t);
  1049. # endif
  1050. elpptime_s(timeInfo, &t);
  1051. return timeInfo;
  1052. # else
  1053. // For any other compilers that don't have CRT warnings issue e.g, MinGW or TDM GCC- we use different method
  1054. time_t rawTime = currTime->tv_sec;
  1055. struct tm* tmInf = elpptime(&rawTime);
  1056. *timeInfo = *tmInf;
  1057. return timeInfo;
  1058. # endif // ELPP_COMPILER_MSVC
  1059. #endif // ELPP_OS_UNIX
  1060. }
  1061. char* DateTime::parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo,
  1062. std::size_t msec, const base::SubsecondPrecision* ssPrec) {
  1063. const char* bufLim = buf + bufSz;
  1064. for (; *format; ++format) {
  1065. if (*format == base::consts::kFormatSpecifierChar) {
  1066. switch (*++format) {
  1067. case base::consts::kFormatSpecifierChar: // Escape
  1068. break;
  1069. case '\0': // End
  1070. --format;
  1071. break;
  1072. case 'd': // Day
  1073. buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mday, 2, buf, bufLim);
  1074. continue;
  1075. case 'a': // Day of week (short)
  1076. buf = base::utils::Str::addToBuff(base::consts::kDaysAbbrev[tInfo->tm_wday], buf, bufLim);
  1077. continue;
  1078. case 'A': // Day of week (long)
  1079. buf = base::utils::Str::addToBuff(base::consts::kDays[tInfo->tm_wday], buf, bufLim);
  1080. continue;
  1081. case 'M': // month
  1082. buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mon + 1, 2, buf, bufLim);
  1083. continue;
  1084. case 'b': // month (short)
  1085. buf = base::utils::Str::addToBuff(base::consts::kMonthsAbbrev[tInfo->tm_mon], buf, bufLim);
  1086. continue;
  1087. case 'B': // month (long)
  1088. buf = base::utils::Str::addToBuff(base::consts::kMonths[tInfo->tm_mon], buf, bufLim);
  1089. continue;
  1090. case 'y': // year (two digits)
  1091. buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 2, buf, bufLim);
  1092. continue;
  1093. case 'Y': // year (four digits)
  1094. buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 4, buf, bufLim);
  1095. continue;
  1096. case 'h': // hour (12-hour)
  1097. buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour % 12, 2, buf, bufLim);
  1098. continue;
  1099. case 'H': // hour (24-hour)
  1100. buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour, 2, buf, bufLim);
  1101. continue;
  1102. case 'm': // minute
  1103. buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_min, 2, buf, bufLim);
  1104. continue;
  1105. case 's': // second
  1106. buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_sec, 2, buf, bufLim);
  1107. continue;
  1108. case 'z': // subsecond part
  1109. case 'g':
  1110. buf = base::utils::Str::convertAndAddToBuff(msec, ssPrec->m_width, buf, bufLim);
  1111. continue;
  1112. case 'F': // AM/PM
  1113. buf = base::utils::Str::addToBuff((tInfo->tm_hour >= 12) ? base::consts::kPm : base::consts::kAm, buf, bufLim);
  1114. continue;
  1115. default:
  1116. continue;
  1117. }
  1118. }
  1119. if (buf == bufLim) break;
  1120. *buf++ = *format;
  1121. }
  1122. return buf;
  1123. }
  1124. // CommandLineArgs
  1125. void CommandLineArgs::setArgs(int argc, char** argv) {
  1126. m_params.clear();
  1127. m_paramsWithValue.clear();
  1128. if (argc == 0 || argv == nullptr) {
  1129. return;
  1130. }
  1131. m_argc = argc;
  1132. m_argv = argv;
  1133. for (int i = 1; i < m_argc; ++i) {
  1134. const char* v = (strstr(m_argv[i], "="));
  1135. if (v != nullptr && strlen(v) > 0) {
  1136. std::string key = std::string(m_argv[i]);
  1137. key = key.substr(0, key.find_first_of('='));
  1138. if (hasParamWithValue(key.c_str())) {
  1139. ELPP_INTERNAL_INFO(1, "Skipping [" << key << "] arg since it already has value ["
  1140. << getParamValue(key.c_str()) << "]");
  1141. } else {
  1142. m_paramsWithValue.insert(std::make_pair(key, std::string(v + 1)));
  1143. }
  1144. }
  1145. if (v == nullptr) {
  1146. if (hasParam(m_argv[i])) {
  1147. ELPP_INTERNAL_INFO(1, "Skipping [" << m_argv[i] << "] arg since it already exists");
  1148. } else {
  1149. m_params.push_back(std::string(m_argv[i]));
  1150. }
  1151. }
  1152. }
  1153. }
  1154. bool CommandLineArgs::hasParamWithValue(const char* paramKey) const {
  1155. return m_paramsWithValue.find(std::string(paramKey)) != m_paramsWithValue.end();
  1156. }
  1157. const char* CommandLineArgs::getParamValue(const char* paramKey) const {
  1158. std::map<std::string, std::string>::const_iterator iter = m_paramsWithValue.find(std::string(paramKey));
  1159. return iter != m_paramsWithValue.end() ? iter->second.c_str() : "";
  1160. }
  1161. bool CommandLineArgs::hasParam(const char* paramKey) const {
  1162. return std::find(m_params.begin(), m_params.end(), std::string(paramKey)) != m_params.end();
  1163. }
  1164. bool CommandLineArgs::empty(void) const {
  1165. return m_params.empty() && m_paramsWithValue.empty();
  1166. }
  1167. std::size_t CommandLineArgs::size(void) const {
  1168. return m_params.size() + m_paramsWithValue.size();
  1169. }
  1170. base::type::ostream_t& operator<<(base::type::ostream_t& os, const CommandLineArgs& c) {
  1171. for (int i = 1; i < c.m_argc; ++i) {
  1172. os << ELPP_LITERAL("[") << c.m_argv[i] << ELPP_LITERAL("]");
  1173. if (i < c.m_argc - 1) {
  1174. os << ELPP_LITERAL(" ");
  1175. }
  1176. }
  1177. return os;
  1178. }
  1179. } // namespace utils
  1180. // el::base::threading
  1181. namespace threading {
  1182. #if ELPP_THREADING_ENABLED
  1183. # if ELPP_USE_STD_THREADING
  1184. # if ELPP_ASYNC_LOGGING
  1185. static void msleep(int ms) {
  1186. // Only when async logging enabled - this is because async is strict on compiler
  1187. # if defined(ELPP_NO_SLEEP_FOR)
  1188. usleep(ms * 1000);
  1189. # else
  1190. std::this_thread::sleep_for(std::chrono::milliseconds(ms));
  1191. # endif // defined(ELPP_NO_SLEEP_FOR)
  1192. }
  1193. # endif // ELPP_ASYNC_LOGGING
  1194. # endif // !ELPP_USE_STD_THREADING
  1195. #endif // ELPP_THREADING_ENABLED
  1196. } // namespace threading
  1197. // el::base
  1198. // SubsecondPrecision
  1199. void SubsecondPrecision::init(int width) {
  1200. if (width < 1 || width > 6) {
  1201. width = base::consts::kDefaultSubsecondPrecision;
  1202. }
  1203. m_width = width;
  1204. switch (m_width) {
  1205. case 3:
  1206. m_offset = 1000;
  1207. break;
  1208. case 4:
  1209. m_offset = 100;
  1210. break;
  1211. case 5:
  1212. m_offset = 10;
  1213. break;
  1214. case 6:
  1215. m_offset = 1;
  1216. break;
  1217. default:
  1218. m_offset = 1000;
  1219. break;
  1220. }
  1221. }
  1222. // LogFormat
  1223. LogFormat::LogFormat(void) :
  1224. m_level(Level::Unknown),
  1225. m_userFormat(base::type::string_t()),
  1226. m_format(base::type::string_t()),
  1227. m_dateTimeFormat(std::string()),
  1228. m_flags(0x0),
  1229. m_currentUser(base::utils::OS::currentUser()),
  1230. m_currentHost(base::utils::OS::currentHost()) {
  1231. }
  1232. LogFormat::LogFormat(Level level, const base::type::string_t& format)
  1233. : m_level(level), m_userFormat(format), m_currentUser(base::utils::OS::currentUser()),
  1234. m_currentHost(base::utils::OS::currentHost()) {
  1235. parseFromFormat(m_userFormat);
  1236. }
  1237. LogFormat::LogFormat(const LogFormat& logFormat):
  1238. m_level(logFormat.m_level),
  1239. m_userFormat(logFormat.m_userFormat),
  1240. m_format(logFormat.m_format),
  1241. m_dateTimeFormat(logFormat.m_dateTimeFormat),
  1242. m_flags(logFormat.m_flags),
  1243. m_currentUser(logFormat.m_currentUser),
  1244. m_currentHost(logFormat.m_currentHost) {
  1245. }
  1246. LogFormat::LogFormat(LogFormat&& logFormat) {
  1247. m_level = std::move(logFormat.m_level);
  1248. m_userFormat = std::move(logFormat.m_userFormat);
  1249. m_format = std::move(logFormat.m_format);
  1250. m_dateTimeFormat = std::move(logFormat.m_dateTimeFormat);
  1251. m_flags = std::move(logFormat.m_flags);
  1252. m_currentUser = std::move(logFormat.m_currentUser);
  1253. m_currentHost = std::move(logFormat.m_currentHost);
  1254. }
  1255. LogFormat& LogFormat::operator=(const LogFormat& logFormat) {
  1256. if (&logFormat != this) {
  1257. m_level = logFormat.m_level;
  1258. m_userFormat = logFormat.m_userFormat;
  1259. m_dateTimeFormat = logFormat.m_dateTimeFormat;
  1260. m_flags = logFormat.m_flags;
  1261. m_currentUser = logFormat.m_currentUser;
  1262. m_currentHost = logFormat.m_currentHost;
  1263. }
  1264. return *this;
  1265. }
  1266. bool LogFormat::operator==(const LogFormat& other) {
  1267. return m_level == other.m_level && m_userFormat == other.m_userFormat && m_format == other.m_format &&
  1268. m_dateTimeFormat == other.m_dateTimeFormat && m_flags == other.m_flags;
  1269. }
  1270. /// @brief Updates format to be used while logging.
  1271. /// @param userFormat User provided format
  1272. void LogFormat::parseFromFormat(const base::type::string_t& userFormat) {
  1273. // We make copy because we will be changing the format
  1274. // i.e, removing user provided date format from original format
  1275. // and then storing it.
  1276. base::type::string_t formatCopy = userFormat;
  1277. m_flags = 0x0;
  1278. auto conditionalAddFlag = [&](const base::type::char_t* specifier, base::FormatFlags flag) {
  1279. std::size_t foundAt = base::type::string_t::npos;
  1280. while ((foundAt = formatCopy.find(specifier, foundAt + 1)) != base::type::string_t::npos) {
  1281. if (foundAt > 0 && formatCopy[foundAt - 1] == base::consts::kFormatSpecifierChar) {
  1282. if (hasFlag(flag)) {
  1283. // If we already have flag we remove the escape chars so that '%%' is turned to '%'
  1284. // even after specifier resolution - this is because we only replaceFirst specifier
  1285. formatCopy.erase(foundAt > 0 ? foundAt - 1 : 0, 1);
  1286. ++foundAt;
  1287. }
  1288. } else {
  1289. if (!hasFlag(flag)) addFlag(flag);
  1290. }
  1291. }
  1292. };
  1293. conditionalAddFlag(base::consts::kAppNameFormatSpecifier, base::FormatFlags::AppName);
  1294. conditionalAddFlag(base::consts::kSeverityLevelFormatSpecifier, base::FormatFlags::Level);
  1295. conditionalAddFlag(base::consts::kSeverityLevelShortFormatSpecifier, base::FormatFlags::LevelShort);
  1296. conditionalAddFlag(base::consts::kLoggerIdFormatSpecifier, base::FormatFlags::LoggerId);
  1297. conditionalAddFlag(base::consts::kThreadIdFormatSpecifier, base::FormatFlags::ThreadId);
  1298. conditionalAddFlag(base::consts::kLogFileFormatSpecifier, base::FormatFlags::File);
  1299. conditionalAddFlag(base::consts::kLogFileBaseFormatSpecifier, base::FormatFlags::FileBase);
  1300. conditionalAddFlag(base::consts::kLogLineFormatSpecifier, base::FormatFlags::Line);
  1301. conditionalAddFlag(base::consts::kLogLocationFormatSpecifier, base::FormatFlags::Location);
  1302. conditionalAddFlag(base::consts::kLogFunctionFormatSpecifier, base::FormatFlags::Function);
  1303. conditionalAddFlag(base::consts::kCurrentUserFormatSpecifier, base::FormatFlags::User);
  1304. conditionalAddFlag(base::consts::kCurrentHostFormatSpecifier, base::FormatFlags::Host);
  1305. conditionalAddFlag(base::consts::kMessageFormatSpecifier, base::FormatFlags::LogMessage);
  1306. conditionalAddFlag(base::consts::kVerboseLevelFormatSpecifier, base::FormatFlags::VerboseLevel);
  1307. // For date/time we need to extract user's date format first
  1308. std::size_t dateIndex = std::string::npos;
  1309. if ((dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier)) != std::string::npos) {
  1310. while (dateIndex > 0 && formatCopy[dateIndex - 1] == base::consts::kFormatSpecifierChar) {
  1311. dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier, dateIndex + 1);
  1312. }
  1313. if (dateIndex != std::string::npos) {
  1314. addFlag(base::FormatFlags::DateTime);
  1315. updateDateFormat(dateIndex, formatCopy);
  1316. }
  1317. }
  1318. m_format = formatCopy;
  1319. updateFormatSpec();
  1320. }
  1321. void LogFormat::updateDateFormat(std::size_t index, base::type::string_t& currFormat) {
  1322. if (hasFlag(base::FormatFlags::DateTime)) {
  1323. index += ELPP_STRLEN(base::consts::kDateTimeFormatSpecifier);
  1324. }
  1325. const base::type::char_t* ptr = currFormat.c_str() + index;
  1326. if ((currFormat.size() > index) && (ptr[0] == '{')) {
  1327. // User has provided format for date/time
  1328. ++ptr;
  1329. int count = 1; // Start by 1 in order to remove starting brace
  1330. std::stringstream ss;
  1331. for (; *ptr; ++ptr, ++count) {
  1332. if (*ptr == '}') {
  1333. ++count; // In order to remove ending brace
  1334. break;
  1335. }
  1336. ss << static_cast<char>(*ptr);
  1337. }
  1338. currFormat.erase(index, count);
  1339. m_dateTimeFormat = ss.str();
  1340. } else {
  1341. // No format provided, use default
  1342. if (hasFlag(base::FormatFlags::DateTime)) {
  1343. m_dateTimeFormat = std::string(base::consts::kDefaultDateTimeFormat);
  1344. }
  1345. }
  1346. }
  1347. void LogFormat::updateFormatSpec(void) {
  1348. // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet.
  1349. if (m_level == Level::Debug) {
  1350. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
  1351. base::consts::kDebugLevelLogValue);
  1352. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
  1353. base::consts::kDebugLevelShortLogValue);
  1354. } else if (m_level == Level::Info) {
  1355. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
  1356. base::consts::kInfoLevelLogValue);
  1357. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
  1358. base::consts::kInfoLevelShortLogValue);
  1359. } else if (m_level == Level::Warning) {
  1360. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
  1361. base::consts::kWarningLevelLogValue);
  1362. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
  1363. base::consts::kWarningLevelShortLogValue);
  1364. } else if (m_level == Level::Error) {
  1365. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
  1366. base::consts::kErrorLevelLogValue);
  1367. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
  1368. base::consts::kErrorLevelShortLogValue);
  1369. } else if (m_level == Level::Fatal) {
  1370. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
  1371. base::consts::kFatalLevelLogValue);
  1372. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
  1373. base::consts::kFatalLevelShortLogValue);
  1374. } else if (m_level == Level::Verbose) {
  1375. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
  1376. base::consts::kVerboseLevelLogValue);
  1377. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
  1378. base::consts::kVerboseLevelShortLogValue);
  1379. } else if (m_level == Level::Trace) {
  1380. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
  1381. base::consts::kTraceLevelLogValue);
  1382. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
  1383. base::consts::kTraceLevelShortLogValue);
  1384. }
  1385. if (hasFlag(base::FormatFlags::User)) {
  1386. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentUserFormatSpecifier,
  1387. m_currentUser);
  1388. }
  1389. if (hasFlag(base::FormatFlags::Host)) {
  1390. base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentHostFormatSpecifier,
  1391. m_currentHost);
  1392. }
  1393. // Ignore Level::Global and Level::Unknown
  1394. }
  1395. // TypedConfigurations
  1396. TypedConfigurations::TypedConfigurations(Configurations* configurations,
  1397. base::LogStreamsReferenceMap* logStreamsReference) {
  1398. m_configurations = configurations;
  1399. m_logStreamsReference = logStreamsReference;
  1400. build(m_configurations);
  1401. }
  1402. TypedConfigurations::TypedConfigurations(const TypedConfigurations& other) {
  1403. this->m_configurations = other.m_configurations;
  1404. this->m_logStreamsReference = other.m_logStreamsReference;
  1405. build(m_configurations);
  1406. }
  1407. bool TypedConfigurations::enabled(Level level) {
  1408. return getConfigByVal<bool>(level, &m_enabledMap, "enabled");
  1409. }
  1410. bool TypedConfigurations::toFile(Level level) {
  1411. return getConfigByVal<bool>(level, &m_toFileMap, "toFile");
  1412. }
  1413. const std::string& TypedConfigurations::filename(Level level) {
  1414. return getConfigByRef<std::string>(level, &m_filenameMap, "filename");
  1415. }
  1416. bool TypedConfigurations::toStandardOutput(Level level) {
  1417. return getConfigByVal<bool>(level, &m_toStandardOutputMap, "toStandardOutput");
  1418. }
  1419. const base::LogFormat& TypedConfigurations::logFormat(Level level) {
  1420. return getConfigByRef<base::LogFormat>(level, &m_logFormatMap, "logFormat");
  1421. }
  1422. const base::SubsecondPrecision& TypedConfigurations::subsecondPrecision(Level level) {
  1423. return getConfigByRef<base::SubsecondPrecision>(level, &m_subsecondPrecisionMap, "subsecondPrecision");
  1424. }
  1425. const base::MillisecondsWidth& TypedConfigurations::millisecondsWidth(Level level) {
  1426. return getConfigByRef<base::MillisecondsWidth>(level, &m_subsecondPrecisionMap, "millisecondsWidth");
  1427. }
  1428. bool TypedConfigurations::performanceTracking(Level level) {
  1429. return getConfigByVal<bool>(level, &m_performanceTrackingMap, "performanceTracking");
  1430. }
  1431. base::type::fstream_t* TypedConfigurations::fileStream(Level level) {
  1432. return getConfigByRef<base::FileStreamPtr>(level, &m_fileStreamMap, "fileStream").get();
  1433. }
  1434. std::size_t TypedConfigurations::maxLogFileSize(Level level) {
  1435. return getConfigByVal<std::size_t>(level, &m_maxLogFileSizeMap, "maxLogFileSize");
  1436. }
  1437. std::size_t TypedConfigurations::logFlushThreshold(Level level) {
  1438. return getConfigByVal<std::size_t>(level, &m_logFlushThresholdMap, "logFlushThreshold");
  1439. }
  1440. void TypedConfigurations::build(Configurations* configurations) {
  1441. base::threading::ScopedLock scopedLock(lock());
  1442. auto getBool = [] (std::string boolStr) -> bool { // Pass by value for trimming
  1443. base::utils::Str::trim(boolStr);
  1444. return (boolStr == "TRUE" || boolStr == "true" || boolStr == "1");
  1445. };
  1446. std::vector<Configuration*> withFileSizeLimit;
  1447. for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) {
  1448. Configuration* conf = *it;
  1449. // We cannot use switch on strong enums because Intel C++ dont support them yet
  1450. if (conf->configurationType() == ConfigurationType::Enabled) {
  1451. setValue(conf->level(), getBool(conf->value()), &m_enabledMap);
  1452. } else if (conf->configurationType() == ConfigurationType::ToFile) {
  1453. setValue(conf->level(), getBool(conf->value()), &m_toFileMap);
  1454. } else if (conf->configurationType() == ConfigurationType::ToStandardOutput) {
  1455. setValue(conf->level(), getBool(conf->value()), &m_toStandardOutputMap);
  1456. } else if (conf->configurationType() == ConfigurationType::Filename) {
  1457. // We do not yet configure filename but we will configure in another
  1458. // loop. This is because if file cannot be created, we will force ToFile
  1459. // to be false. Because configuring logger is not necessarily performance
  1460. // sensative operation, we can live with another loop; (by the way this loop
  1461. // is not very heavy either)
  1462. } else if (conf->configurationType() == ConfigurationType::Format) {
  1463. setValue(conf->level(), base::LogFormat(conf->level(),
  1464. base::type::string_t(conf->value().begin(), conf->value().end())), &m_logFormatMap);
  1465. } else if (conf->configurationType() == ConfigurationType::SubsecondPrecision) {
  1466. setValue(Level::Global,
  1467. base::SubsecondPrecision(static_cast<int>(getULong(conf->value()))), &m_subsecondPrecisionMap);
  1468. } else if (conf->configurationType() == ConfigurationType::PerformanceTracking) {
  1469. setValue(Level::Global, getBool(conf->value()), &m_performanceTrackingMap);
  1470. } else if (conf->configurationType() == ConfigurationType::MaxLogFileSize) {
  1471. setValue(conf->level(), static_cast<std::size_t>(getULong(conf->value())), &m_maxLogFileSizeMap);
  1472. #if !defined(ELPP_NO_DEFAULT_LOG_FILE)
  1473. withFileSizeLimit.push_back(conf);
  1474. #endif // !defined(ELPP_NO_DEFAULT_LOG_FILE)
  1475. } else if (conf->configurationType() == ConfigurationType::LogFlushThreshold) {
  1476. setValue(conf->level(), static_cast<std::size_t>(getULong(conf->value())), &m_logFlushThresholdMap);
  1477. }
  1478. }
  1479. // As mentioned earlier, we will now set filename configuration in separate loop to deal with non-existent files
  1480. for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) {
  1481. Configuration* conf = *it;
  1482. if (conf->configurationType() == ConfigurationType::Filename) {
  1483. insertFile(conf->level(), conf->value());
  1484. }
  1485. }
  1486. for (std::vector<Configuration*>::iterator conf = withFileSizeLimit.begin();
  1487. conf != withFileSizeLimit.end(); ++conf) {
  1488. // This is not unsafe as mutex is locked in currect scope
  1489. unsafeValidateFileRolling((*conf)->level(), base::defaultPreRollOutCallback);
  1490. }
  1491. }
  1492. unsigned long TypedConfigurations::getULong(std::string confVal) {
  1493. bool valid = true;
  1494. base::utils::Str::trim(confVal);
  1495. valid = !confVal.empty() && std::find_if(confVal.begin(), confVal.end(),
  1496. [](char c) {
  1497. return !base::utils::Str::isDigit(c);
  1498. }) == confVal.end();
  1499. if (!valid) {
  1500. valid = false;
  1501. ELPP_ASSERT(valid, "Configuration value not a valid integer [" << confVal << "]");
  1502. return 0;
  1503. }
  1504. return atol(confVal.c_str());
  1505. }
  1506. std::string TypedConfigurations::resolveFilename(const std::string& filename) {
  1507. std::string resultingFilename = filename;
  1508. std::size_t dateIndex = std::string::npos;
  1509. std::string dateTimeFormatSpecifierStr = std::string(base::consts::kDateTimeFormatSpecifierForFilename);
  1510. if ((dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str())) != std::string::npos) {
  1511. while (dateIndex > 0 && resultingFilename[dateIndex - 1] == base::consts::kFormatSpecifierChar) {
  1512. dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str(), dateIndex + 1);
  1513. }
  1514. if (dateIndex != std::string::npos) {
  1515. const char* ptr = resultingFilename.c_str() + dateIndex;
  1516. // Goto end of specifier
  1517. ptr += dateTimeFormatSpecifierStr.size();
  1518. std::string fmt;
  1519. if ((resultingFilename.size() > dateIndex) && (ptr[0] == '{')) {
  1520. // User has provided format for date/time
  1521. ++ptr;
  1522. int count = 1; // Start by 1 in order to remove starting brace
  1523. std::stringstream ss;
  1524. for (; *ptr; ++ptr, ++count) {
  1525. if (*ptr == '}') {
  1526. ++count; // In order to remove ending brace
  1527. break;
  1528. }
  1529. ss << *ptr;
  1530. }
  1531. resultingFilename.erase(dateIndex + dateTimeFormatSpecifierStr.size(), count);
  1532. fmt = ss.str();
  1533. } else {
  1534. fmt = std::string(base::consts::kDefaultDateTimeFormatInFilename);
  1535. }
  1536. base::SubsecondPrecision ssPrec(3);
  1537. std::string now = base::utils::DateTime::getDateTime(fmt.c_str(), &ssPrec);
  1538. base::utils::Str::replaceAll(now, '/', '-'); // Replace path element since we are dealing with filename
  1539. base::utils::Str::replaceAll(resultingFilename, dateTimeFormatSpecifierStr, now);
  1540. }
  1541. }
  1542. return resultingFilename;
  1543. }
  1544. void TypedConfigurations::insertFile(Level level, const std::string& fullFilename) {
  1545. #if defined(ELPP_NO_LOG_TO_FILE)
  1546. setValue(level, false, &m_toFileMap);
  1547. ELPP_UNUSED(fullFilename);
  1548. m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(nullptr)));
  1549. return;
  1550. #endif
  1551. std::string resolvedFilename = resolveFilename(fullFilename);
  1552. if (resolvedFilename.empty()) {
  1553. std::cerr << "Could not load empty file for logging, please re-check your configurations for level ["
  1554. << LevelHelper::convertToString(level) << "]";
  1555. }
  1556. std::string filePath = base::utils::File::extractPathFromFilename(resolvedFilename, base::consts::kFilePathSeperator);
  1557. if (filePath.size() < resolvedFilename.size()) {
  1558. base::utils::File::createPath(filePath);
  1559. }
  1560. auto create = [&](Level level) {
  1561. base::LogStreamsReferenceMap::iterator filestreamIter = m_logStreamsReference->find(resolvedFilename);
  1562. base::type::fstream_t* fs = nullptr;
  1563. if (filestreamIter == m_logStreamsReference->end()) {
  1564. // We need a completely new stream, nothing to share with
  1565. fs = base::utils::File::newFileStream(resolvedFilename);
  1566. m_filenameMap.insert(std::make_pair(level, resolvedFilename));
  1567. m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(fs)));
  1568. m_logStreamsReference->insert(std::make_pair(resolvedFilename, base::FileStreamPtr(m_fileStreamMap.at(level))));
  1569. } else {
  1570. // Woops! we have an existing one, share it!
  1571. m_filenameMap.insert(std::make_pair(level, filestreamIter->first));
  1572. m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(filestreamIter->second)));
  1573. fs = filestreamIter->second.get();
  1574. }
  1575. if (fs == nullptr) {
  1576. // We display bad file error from newFileStream()
  1577. ELPP_INTERNAL_ERROR("Setting [TO_FILE] of ["
  1578. << LevelHelper::convertToString(level) << "] to FALSE", false);
  1579. setValue(level, false, &m_toFileMap);
  1580. }
  1581. };
  1582. // If we dont have file conf for any level, create it for Level::Global first
  1583. // otherwise create for specified level
  1584. create(m_filenameMap.empty() && m_fileStreamMap.empty() ? Level::Global : level);
  1585. }
  1586. bool TypedConfigurations::unsafeValidateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback) {
  1587. base::type::fstream_t* fs = unsafeGetConfigByRef(level, &m_fileStreamMap, "fileStream").get();
  1588. if (fs == nullptr) {
  1589. return true;
  1590. }
  1591. std::size_t maxLogFileSize = unsafeGetConfigByVal(level, &m_maxLogFileSizeMap, "maxLogFileSize");
  1592. std::size_t currFileSize = base::utils::File::getSizeOfFile(fs);
  1593. if (maxLogFileSize != 0 && currFileSize >= maxLogFileSize) {
  1594. std::string fname = unsafeGetConfigByRef(level, &m_filenameMap, "filename");
  1595. ELPP_INTERNAL_INFO(1, "Truncating log file [" << fname << "] as a result of configurations for level ["
  1596. << LevelHelper::convertToString(level) << "]");
  1597. fs->close();
  1598. preRollOutCallback(fname.c_str(), currFileSize);
  1599. fs->open(fname, std::fstream::out | std::fstream::trunc);
  1600. return true;
  1601. }
  1602. return false;
  1603. }
  1604. // RegisteredHitCounters
  1605. bool RegisteredHitCounters::validateEveryN(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
  1606. base::threading::ScopedLock scopedLock(lock());
  1607. base::HitCounter* counter = get(filename, lineNumber);
  1608. if (counter == nullptr) {
  1609. registerNew(counter = new base::HitCounter(filename, lineNumber));
  1610. }
  1611. counter->validateHitCounts(n);
  1612. bool result = (n >= 1 && counter->hitCounts() != 0 && counter->hitCounts() % n == 0);
  1613. return result;
  1614. }
  1615. /// @brief Validates counter for hits >= N, i.e, registers new if does not exist otherwise updates original one
  1616. /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned
  1617. bool RegisteredHitCounters::validateAfterN(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
  1618. base::threading::ScopedLock scopedLock(lock());
  1619. base::HitCounter* counter = get(filename, lineNumber);
  1620. if (counter == nullptr) {
  1621. registerNew(counter = new base::HitCounter(filename, lineNumber));
  1622. }
  1623. // Do not use validateHitCounts here since we do not want to reset counter here
  1624. // Note the >= instead of > because we are incrementing
  1625. // after this check
  1626. if (counter->hitCounts() >= n)
  1627. return true;
  1628. counter->increment();
  1629. return false;
  1630. }
  1631. /// @brief Validates counter for hits are <= n, i.e, registers new if does not exist otherwise updates original one
  1632. /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned
  1633. bool RegisteredHitCounters::validateNTimes(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
  1634. base::threading::ScopedLock scopedLock(lock());
  1635. base::HitCounter* counter = get(filename, lineNumber);
  1636. if (counter == nullptr) {
  1637. registerNew(counter = new base::HitCounter(filename, lineNumber));
  1638. }
  1639. counter->increment();
  1640. // Do not use validateHitCounts here since we do not want to reset counter here
  1641. if (counter->hitCounts() <= n)
  1642. return true;
  1643. return false;
  1644. }
  1645. // RegisteredLoggers
  1646. RegisteredLoggers::RegisteredLoggers(const LogBuilderPtr& defaultLogBuilder) :
  1647. m_defaultLogBuilder(defaultLogBuilder) {
  1648. m_defaultConfigurations.setToDefault();
  1649. }
  1650. Logger* RegisteredLoggers::get(const std::string& id, bool forceCreation) {
  1651. base::threading::ScopedLock scopedLock(lock());
  1652. Logger* logger_ = base::utils::Registry<Logger, std::string>::get(id);
  1653. if (logger_ == nullptr && forceCreation) {
  1654. bool validId = Logger::isValidId(id);
  1655. if (!validId) {
  1656. ELPP_ASSERT(validId, "Invalid logger ID [" << id << "]. Not registering this logger.");
  1657. return nullptr;
  1658. }
  1659. logger_ = new Logger(id, m_defaultConfigurations, &m_logStreamsReference);
  1660. logger_->m_logBuilder = m_defaultLogBuilder;
  1661. registerNew(id, logger_);
  1662. LoggerRegistrationCallback* callback = nullptr;
  1663. for (const std::pair<std::string, base::type::LoggerRegistrationCallbackPtr>& h
  1664. : m_loggerRegistrationCallbacks) {
  1665. callback = h.second.get();
  1666. if (callback != nullptr && callback->enabled()) {
  1667. callback->handle(logger_);
  1668. }
  1669. }
  1670. }
  1671. return logger_;
  1672. }
  1673. bool RegisteredLoggers::remove(const std::string& id) {
  1674. if (id == base::consts::kDefaultLoggerId) {
  1675. return false;
  1676. }
  1677. Logger* logger = base::utils::Registry<Logger, std::string>::get(id);
  1678. if (logger != nullptr) {
  1679. unregister(logger);
  1680. }
  1681. return true;
  1682. }
  1683. void RegisteredLoggers::unsafeFlushAll(void) {
  1684. ELPP_INTERNAL_INFO(1, "Flushing all log files");
  1685. for (base::LogStreamsReferenceMap::iterator it = m_logStreamsReference.begin();
  1686. it != m_logStreamsReference.end(); ++it) {
  1687. if (it->second.get() == nullptr) continue;
  1688. it->second->flush();
  1689. }
  1690. }
  1691. // VRegistry
  1692. VRegistry::VRegistry(base::type::VerboseLevel level, base::type::EnumType* pFlags) : m_level(level), m_pFlags(pFlags) {
  1693. }
  1694. /// @brief Sets verbose level. Accepted range is 0-9
  1695. void VRegistry::setLevel(base::type::VerboseLevel level) {
  1696. base::threading::ScopedLock scopedLock(lock());
  1697. if (level > 9)
  1698. m_level = base::consts::kMaxVerboseLevel;
  1699. else
  1700. m_level = level;
  1701. }
  1702. void VRegistry::setModules(const char* modules) {
  1703. base::threading::ScopedLock scopedLock(lock());
  1704. auto addSuffix = [](std::stringstream& ss, const char* sfx, const char* prev) {
  1705. if (prev != nullptr && base::utils::Str::endsWith(ss.str(), std::string(prev))) {
  1706. std::string chr(ss.str().substr(0, ss.str().size() - strlen(prev)));
  1707. ss.str(std::string(""));
  1708. ss << chr;
  1709. }
  1710. if (base::utils::Str::endsWith(ss.str(), std::string(sfx))) {
  1711. std::string chr(ss.str().substr(0, ss.str().size() - strlen(sfx)));
  1712. ss.str(std::string(""));
  1713. ss << chr;
  1714. }
  1715. ss << sfx;
  1716. };
  1717. auto insert = [&](std::stringstream& ss, base::type::VerboseLevel level) {
  1718. if (!base::utils::hasFlag(LoggingFlag::DisableVModulesExtensions, *m_pFlags)) {
  1719. addSuffix(ss, ".h", nullptr);
  1720. m_modules.insert(std::make_pair(ss.str(), level));
  1721. addSuffix(ss, ".c", ".h");
  1722. m_modules.insert(std::make_pair(ss.str(), level));
  1723. addSuffix(ss, ".cpp", ".c");
  1724. m_modules.insert(std::make_pair(ss.str(), level));
  1725. addSuffix(ss, ".cc", ".cpp");
  1726. m_modules.insert(std::make_pair(ss.str(), level));
  1727. addSuffix(ss, ".cxx", ".cc");
  1728. m_modules.insert(std::make_pair(ss.str(), level));
  1729. addSuffix(ss, ".-inl.h", ".cxx");
  1730. m_modules.insert(std::make_pair(ss.str(), level));
  1731. addSuffix(ss, ".hxx", ".-inl.h");
  1732. m_modules.insert(std::make_pair(ss.str(), level));
  1733. addSuffix(ss, ".hpp", ".hxx");
  1734. m_modules.insert(std::make_pair(ss.str(), level));
  1735. addSuffix(ss, ".hh", ".hpp");
  1736. }
  1737. m_modules.insert(std::make_pair(ss.str(), level));
  1738. };
  1739. bool isMod = true;
  1740. bool isLevel = false;
  1741. std::stringstream ss;
  1742. int level = -1;
  1743. for (; *modules; ++modules) {
  1744. switch (*modules) {
  1745. case '=':
  1746. isLevel = true;
  1747. isMod = false;
  1748. break;
  1749. case ',':
  1750. isLevel = false;
  1751. isMod = true;
  1752. if (!ss.str().empty() && level != -1) {
  1753. insert(ss, static_cast<base::type::VerboseLevel>(level));
  1754. ss.str(std::string(""));
  1755. level = -1;
  1756. }
  1757. break;
  1758. default:
  1759. if (isMod) {
  1760. ss << *modules;
  1761. } else if (isLevel) {
  1762. if (isdigit(*modules)) {
  1763. level = static_cast<base::type::VerboseLevel>(*modules) - 48;
  1764. }
  1765. }
  1766. break;
  1767. }
  1768. }
  1769. if (!ss.str().empty() && level != -1) {
  1770. insert(ss, static_cast<base::type::VerboseLevel>(level));
  1771. }
  1772. }
  1773. bool VRegistry::allowed(base::type::VerboseLevel vlevel, const char* file) {
  1774. base::threading::ScopedLock scopedLock(lock());
  1775. if (m_modules.empty() || file == nullptr) {
  1776. return vlevel <= m_level;
  1777. } else {
  1778. char baseFilename[base::consts::kSourceFilenameMaxLength] = "";
  1779. base::utils::File::buildBaseFilename(file, baseFilename);
  1780. std::map<std::string, base::type::VerboseLevel>::iterator it = m_modules.begin();
  1781. for (; it != m_modules.end(); ++it) {
  1782. if (base::utils::Str::wildCardMatch(baseFilename, it->first.c_str())) {
  1783. return vlevel <= it->second;
  1784. }
  1785. }
  1786. if (base::utils::hasFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified, *m_pFlags)) {
  1787. return true;
  1788. }
  1789. return false;
  1790. }
  1791. }
  1792. void VRegistry::setFromArgs(const base::utils::CommandLineArgs* commandLineArgs) {
  1793. if (commandLineArgs->hasParam("-v") || commandLineArgs->hasParam("--verbose") ||
  1794. commandLineArgs->hasParam("-V") || commandLineArgs->hasParam("--VERBOSE")) {
  1795. setLevel(base::consts::kMaxVerboseLevel);
  1796. } else if (commandLineArgs->hasParamWithValue("--v")) {
  1797. setLevel(static_cast<base::type::VerboseLevel>(atoi(commandLineArgs->getParamValue("--v"))));
  1798. } else if (commandLineArgs->hasParamWithValue("--V")) {
  1799. setLevel(static_cast<base::type::VerboseLevel>(atoi(commandLineArgs->getParamValue("--V"))));
  1800. } else if ((commandLineArgs->hasParamWithValue("-vmodule")) && vModulesEnabled()) {
  1801. setModules(commandLineArgs->getParamValue("-vmodule"));
  1802. } else if (commandLineArgs->hasParamWithValue("-VMODULE") && vModulesEnabled()) {
  1803. setModules(commandLineArgs->getParamValue("-VMODULE"));
  1804. }
  1805. }
  1806. #if !defined(ELPP_DEFAULT_LOGGING_FLAGS)
  1807. # define ELPP_DEFAULT_LOGGING_FLAGS 0x0
  1808. #endif // !defined(ELPP_DEFAULT_LOGGING_FLAGS)
  1809. // Storage
  1810. #if ELPP_ASYNC_LOGGING
  1811. Storage::Storage(const LogBuilderPtr& defaultLogBuilder, base::IWorker* asyncDispatchWorker) :
  1812. #else
  1813. Storage::Storage(const LogBuilderPtr& defaultLogBuilder) :
  1814. #endif // ELPP_ASYNC_LOGGING
  1815. m_registeredHitCounters(new base::RegisteredHitCounters()),
  1816. m_registeredLoggers(new base::RegisteredLoggers(defaultLogBuilder)),
  1817. m_flags(ELPP_DEFAULT_LOGGING_FLAGS),
  1818. m_vRegistry(new base::VRegistry(0, &m_flags)),
  1819. #if ELPP_ASYNC_LOGGING
  1820. m_asyncLogQueue(new base::AsyncLogQueue()),
  1821. m_asyncDispatchWorker(asyncDispatchWorker),
  1822. #endif // ELPP_ASYNC_LOGGING
  1823. m_preRollOutCallback(base::defaultPreRollOutCallback) {
  1824. // Register default logger
  1825. m_registeredLoggers->get(std::string(base::consts::kDefaultLoggerId));
  1826. // We register default logger anyway (worse case it's not going to register) just in case
  1827. m_registeredLoggers->get("default");
  1828. // Register performance logger and reconfigure format
  1829. Logger* performanceLogger = m_registeredLoggers->get(std::string(base::consts::kPerformanceLoggerId));
  1830. m_registeredLoggers->get("performance");
  1831. performanceLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%datetime %level %msg"));
  1832. performanceLogger->reconfigure();
  1833. #if defined(ELPP_SYSLOG)
  1834. // Register syslog logger and reconfigure format
  1835. Logger* sysLogLogger = m_registeredLoggers->get(std::string(base::consts::kSysLogLoggerId));
  1836. sysLogLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%level: %msg"));
  1837. sysLogLogger->reconfigure();
  1838. #endif // defined(ELPP_SYSLOG)
  1839. addFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified);
  1840. #if ELPP_ASYNC_LOGGING
  1841. installLogDispatchCallback<base::AsyncLogDispatchCallback>(std::string("AsyncLogDispatchCallback"));
  1842. #else
  1843. installLogDispatchCallback<base::DefaultLogDispatchCallback>(std::string("DefaultLogDispatchCallback"));
  1844. #endif // ELPP_ASYNC_LOGGING
  1845. #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
  1846. installPerformanceTrackingCallback<base::DefaultPerformanceTrackingCallback>
  1847. (std::string("DefaultPerformanceTrackingCallback"));
  1848. #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
  1849. ELPP_INTERNAL_INFO(1, "Easylogging++ has been initialized");
  1850. #if ELPP_ASYNC_LOGGING
  1851. m_asyncDispatchWorker->start();
  1852. #endif // ELPP_ASYNC_LOGGING
  1853. }
  1854. Storage::~Storage(void) {
  1855. ELPP_INTERNAL_INFO(4, "Destroying storage");
  1856. #if ELPP_ASYNC_LOGGING
  1857. ELPP_INTERNAL_INFO(5, "Replacing log dispatch callback to synchronous");
  1858. uninstallLogDispatchCallback<base::AsyncLogDispatchCallback>(std::string("AsyncLogDispatchCallback"));
  1859. installLogDispatchCallback<base::DefaultLogDispatchCallback>(std::string("DefaultLogDispatchCallback"));
  1860. ELPP_INTERNAL_INFO(5, "Destroying asyncDispatchWorker");
  1861. base::utils::safeDelete(m_asyncDispatchWorker);
  1862. ELPP_INTERNAL_INFO(5, "Destroying asyncLogQueue");
  1863. base::utils::safeDelete(m_asyncLogQueue);
  1864. #endif // ELPP_ASYNC_LOGGING
  1865. ELPP_INTERNAL_INFO(5, "Destroying registeredHitCounters");
  1866. base::utils::safeDelete(m_registeredHitCounters);
  1867. ELPP_INTERNAL_INFO(5, "Destroying registeredLoggers");
  1868. base::utils::safeDelete(m_registeredLoggers);
  1869. ELPP_INTERNAL_INFO(5, "Destroying vRegistry");
  1870. base::utils::safeDelete(m_vRegistry);
  1871. }
  1872. bool Storage::hasCustomFormatSpecifier(const char* formatSpecifier) {
  1873. base::threading::ScopedLock scopedLock(lock());
  1874. return std::find(m_customFormatSpecifiers.begin(), m_customFormatSpecifiers.end(),
  1875. formatSpecifier) != m_customFormatSpecifiers.end();
  1876. }
  1877. void Storage::installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) {
  1878. if (hasCustomFormatSpecifier(customFormatSpecifier.formatSpecifier())) {
  1879. return;
  1880. }
  1881. base::threading::ScopedLock scopedLock(lock());
  1882. m_customFormatSpecifiers.push_back(customFormatSpecifier);
  1883. }
  1884. bool Storage::uninstallCustomFormatSpecifier(const char* formatSpecifier) {
  1885. base::threading::ScopedLock scopedLock(lock());
  1886. std::vector<CustomFormatSpecifier>::iterator it = std::find(m_customFormatSpecifiers.begin(),
  1887. m_customFormatSpecifiers.end(), formatSpecifier);
  1888. if (it != m_customFormatSpecifiers.end() && strcmp(formatSpecifier, it->formatSpecifier()) == 0) {
  1889. m_customFormatSpecifiers.erase(it);
  1890. return true;
  1891. }
  1892. return false;
  1893. }
  1894. void Storage::setApplicationArguments(int argc, char** argv) {
  1895. m_commandLineArgs.setArgs(argc, argv);
  1896. m_vRegistry->setFromArgs(commandLineArgs());
  1897. // default log file
  1898. #if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)
  1899. if (m_commandLineArgs.hasParamWithValue(base::consts::kDefaultLogFileParam)) {
  1900. Configurations c;
  1901. c.setGlobally(ConfigurationType::Filename,
  1902. std::string(m_commandLineArgs.getParamValue(base::consts::kDefaultLogFileParam)));
  1903. registeredLoggers()->setDefaultConfigurations(c);
  1904. for (base::RegisteredLoggers::iterator it = registeredLoggers()->begin();
  1905. it != registeredLoggers()->end(); ++it) {
  1906. it->second->configure(c);
  1907. }
  1908. }
  1909. #endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)
  1910. #if defined(ELPP_LOGGING_FLAGS_FROM_ARG)
  1911. if (m_commandLineArgs.hasParamWithValue(base::consts::kLoggingFlagsParam)) {
  1912. int userInput = atoi(m_commandLineArgs.getParamValue(base::consts::kLoggingFlagsParam));
  1913. if (ELPP_DEFAULT_LOGGING_FLAGS == 0x0) {
  1914. m_flags = userInput;
  1915. } else {
  1916. base::utils::addFlag<base::type::EnumType>(userInput, &m_flags);
  1917. }
  1918. }
  1919. #endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG)
  1920. }
  1921. // DefaultLogDispatchCallback
  1922. void DefaultLogDispatchCallback::handle(const LogDispatchData* data) {
  1923. m_data = data;
  1924. dispatch(m_data->logMessage()->logger()->logBuilder()->build(m_data->logMessage(),
  1925. m_data->dispatchAction() == base::DispatchAction::NormalLog));
  1926. }
  1927. void DefaultLogDispatchCallback::dispatch(base::type::string_t&& logLine) {
  1928. if (m_data->dispatchAction() == base::DispatchAction::NormalLog) {
  1929. if (m_data->logMessage()->logger()->m_typedConfigurations->toFile(m_data->logMessage()->level())) {
  1930. base::type::fstream_t* fs = m_data->logMessage()->logger()->m_typedConfigurations->fileStream(
  1931. m_data->logMessage()->level());
  1932. if (fs != nullptr) {
  1933. fs->write(logLine.c_str(), logLine.size());
  1934. if (fs->fail()) {
  1935. ELPP_INTERNAL_ERROR("Unable to write log to file ["
  1936. << m_data->logMessage()->logger()->m_typedConfigurations->filename(m_data->logMessage()->level()) << "].\n"
  1937. << "Few possible reasons (could be something else):\n" << " * Permission denied\n"
  1938. << " * Disk full\n" << " * Disk is not writable", true);
  1939. } else {
  1940. if (ELPP->hasFlag(LoggingFlag::ImmediateFlush)
  1941. || (m_data->logMessage()->logger()->isFlushNeeded(m_data->logMessage()->level()))) {
  1942. m_data->logMessage()->logger()->flush(m_data->logMessage()->level(), fs);
  1943. }
  1944. }
  1945. } else {
  1946. ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(m_data->logMessage()->level()) << "] "
  1947. << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: "
  1948. << m_data->logMessage()->logger()->id() << "]", false);
  1949. }
  1950. }
  1951. if (m_data->logMessage()->logger()->m_typedConfigurations->toStandardOutput(m_data->logMessage()->level())) {
  1952. if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput))
  1953. m_data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&logLine, m_data->logMessage()->level());
  1954. ELPP_COUT << ELPP_COUT_LINE(logLine);
  1955. }
  1956. }
  1957. #if defined(ELPP_SYSLOG)
  1958. else if (m_data->dispatchAction() == base::DispatchAction::SysLog) {
  1959. // Determine syslog priority
  1960. int sysLogPriority = 0;
  1961. if (m_data->logMessage()->level() == Level::Fatal)
  1962. sysLogPriority = LOG_EMERG;
  1963. else if (m_data->logMessage()->level() == Level::Error)
  1964. sysLogPriority = LOG_ERR;
  1965. else if (m_data->logMessage()->level() == Level::Warning)
  1966. sysLogPriority = LOG_WARNING;
  1967. else if (m_data->logMessage()->level() == Level::Info)
  1968. sysLogPriority = LOG_INFO;
  1969. else if (m_data->logMessage()->level() == Level::Debug)
  1970. sysLogPriority = LOG_DEBUG;
  1971. else
  1972. sysLogPriority = LOG_NOTICE;
  1973. # if defined(ELPP_UNICODE)
  1974. char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str());
  1975. syslog(sysLogPriority, "%s", line);
  1976. free(line);
  1977. # else
  1978. syslog(sysLogPriority, "%s", logLine.c_str());
  1979. # endif
  1980. }
  1981. #endif // defined(ELPP_SYSLOG)
  1982. }
  1983. #if ELPP_ASYNC_LOGGING
  1984. // AsyncLogDispatchCallback
  1985. void AsyncLogDispatchCallback::handle(const LogDispatchData* data) {
  1986. base::type::string_t logLine = data->logMessage()->logger()->logBuilder()->build(data->logMessage(),
  1987. data->dispatchAction() == base::DispatchAction::NormalLog);
  1988. if (data->dispatchAction() == base::DispatchAction::NormalLog
  1989. && data->logMessage()->logger()->typedConfigurations()->toStandardOutput(data->logMessage()->level())) {
  1990. if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput))
  1991. data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&logLine, data->logMessage()->level());
  1992. ELPP_COUT << ELPP_COUT_LINE(logLine);
  1993. }
  1994. // Save resources and only queue if we want to write to file otherwise just ignore handler
  1995. if (data->logMessage()->logger()->typedConfigurations()->toFile(data->logMessage()->level())) {
  1996. ELPP->asyncLogQueue()->push(AsyncLogItem(*(data->logMessage()), *data, logLine));
  1997. }
  1998. }
  1999. // AsyncDispatchWorker
  2000. AsyncDispatchWorker::AsyncDispatchWorker() {
  2001. setContinueRunning(false);
  2002. }
  2003. AsyncDispatchWorker::~AsyncDispatchWorker() {
  2004. setContinueRunning(false);
  2005. ELPP_INTERNAL_INFO(6, "Stopping dispatch worker - Cleaning log queue");
  2006. clean();
  2007. ELPP_INTERNAL_INFO(6, "Log queue cleaned");
  2008. }
  2009. bool AsyncDispatchWorker::clean(void) {
  2010. std::mutex m;
  2011. std::unique_lock<std::mutex> lk(m);
  2012. cv.wait(lk, [] { return !ELPP->asyncLogQueue()->empty(); });
  2013. emptyQueue();
  2014. lk.unlock();
  2015. cv.notify_one();
  2016. return ELPP->asyncLogQueue()->empty();
  2017. }
  2018. void AsyncDispatchWorker::emptyQueue(void) {
  2019. while (!ELPP->asyncLogQueue()->empty()) {
  2020. AsyncLogItem data = ELPP->asyncLogQueue()->next();
  2021. handle(&data);
  2022. base::threading::msleep(100);
  2023. }
  2024. }
  2025. void AsyncDispatchWorker::start(void) {
  2026. base::threading::msleep(5000); // 5s (why?)
  2027. setContinueRunning(true);
  2028. std::thread t1(&AsyncDispatchWorker::run, this);
  2029. t1.join();
  2030. }
  2031. void AsyncDispatchWorker::handle(AsyncLogItem* logItem) {
  2032. LogDispatchData* data = logItem->data();
  2033. LogMessage* logMessage = logItem->logMessage();
  2034. Logger* logger = logMessage->logger();
  2035. base::TypedConfigurations* conf = logger->typedConfigurations();
  2036. base::type::string_t logLine = logItem->logLine();
  2037. if (data->dispatchAction() == base::DispatchAction::NormalLog) {
  2038. if (conf->toFile(logMessage->level())) {
  2039. base::type::fstream_t* fs = conf->fileStream(logMessage->level());
  2040. if (fs != nullptr) {
  2041. fs->write(logLine.c_str(), logLine.size());
  2042. if (fs->fail()) {
  2043. ELPP_INTERNAL_ERROR("Unable to write log to file ["
  2044. << conf->filename(logMessage->level()) << "].\n"
  2045. << "Few possible reasons (could be something else):\n" << " * Permission denied\n"
  2046. << " * Disk full\n" << " * Disk is not writable", true);
  2047. } else {
  2048. if (ELPP->hasFlag(LoggingFlag::ImmediateFlush) || (logger->isFlushNeeded(logMessage->level()))) {
  2049. logger->flush(logMessage->level(), fs);
  2050. }
  2051. }
  2052. } else {
  2053. ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(logMessage->level()) << "] "
  2054. << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: " << logger->id() << "]", false);
  2055. }
  2056. }
  2057. }
  2058. # if defined(ELPP_SYSLOG)
  2059. else if (data->dispatchAction() == base::DispatchAction::SysLog) {
  2060. // Determine syslog priority
  2061. int sysLogPriority = 0;
  2062. if (logMessage->level() == Level::Fatal)
  2063. sysLogPriority = LOG_EMERG;
  2064. else if (logMessage->level() == Level::Error)
  2065. sysLogPriority = LOG_ERR;
  2066. else if (logMessage->level() == Level::Warning)
  2067. sysLogPriority = LOG_WARNING;
  2068. else if (logMessage->level() == Level::Info)
  2069. sysLogPriority = LOG_INFO;
  2070. else if (logMessage->level() == Level::Debug)
  2071. sysLogPriority = LOG_DEBUG;
  2072. else
  2073. sysLogPriority = LOG_NOTICE;
  2074. # if defined(ELPP_UNICODE)
  2075. char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str());
  2076. syslog(sysLogPriority, "%s", line);
  2077. free(line);
  2078. # else
  2079. syslog(sysLogPriority, "%s", logLine.c_str());
  2080. # endif
  2081. }
  2082. # endif // defined(ELPP_SYSLOG)
  2083. }
  2084. void AsyncDispatchWorker::run(void) {
  2085. while (continueRunning()) {
  2086. emptyQueue();
  2087. base::threading::msleep(10); // 10ms
  2088. }
  2089. }
  2090. #endif // ELPP_ASYNC_LOGGING
  2091. // DefaultLogBuilder
  2092. base::type::string_t DefaultLogBuilder::build(const LogMessage* logMessage, bool appendNewLine) const {
  2093. base::TypedConfigurations* tc = logMessage->logger()->typedConfigurations();
  2094. const base::LogFormat* logFormat = &tc->logFormat(logMessage->level());
  2095. base::type::string_t logLine = logFormat->format();
  2096. char buff[base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength] = "";
  2097. const char* bufLim = buff + sizeof(buff);
  2098. if (logFormat->hasFlag(base::FormatFlags::AppName)) {
  2099. // App name
  2100. base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kAppNameFormatSpecifier,
  2101. logMessage->logger()->parentApplicationName());
  2102. }
  2103. if (logFormat->hasFlag(base::FormatFlags::ThreadId)) {
  2104. // Thread ID
  2105. base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kThreadIdFormatSpecifier,
  2106. ELPP->getThreadName(base::threading::getCurrentThreadId()));
  2107. }
  2108. if (logFormat->hasFlag(base::FormatFlags::DateTime)) {
  2109. // DateTime
  2110. base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kDateTimeFormatSpecifier,
  2111. base::utils::DateTime::getDateTime(logFormat->dateTimeFormat().c_str(),
  2112. &tc->subsecondPrecision(logMessage->level())));
  2113. }
  2114. if (logFormat->hasFlag(base::FormatFlags::Function)) {
  2115. // Function
  2116. base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFunctionFormatSpecifier, logMessage->func());
  2117. }
  2118. if (logFormat->hasFlag(base::FormatFlags::File)) {
  2119. // File
  2120. base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength);
  2121. base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff);
  2122. base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileFormatSpecifier, std::string(buff));
  2123. }
  2124. if (logFormat->hasFlag(base::FormatFlags::FileBase)) {
  2125. // FileBase
  2126. base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength);
  2127. base::utils::File::buildBaseFilename(logMessage->file(), buff);
  2128. base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileBaseFormatSpecifier, std::string(buff));
  2129. }
  2130. if (logFormat->hasFlag(base::FormatFlags::Line)) {
  2131. // Line
  2132. char* buf = base::utils::Str::clearBuff(buff, base::consts::kSourceLineMaxLength);
  2133. buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), base::consts::kSourceLineMaxLength, buf, bufLim, false);
  2134. base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLineFormatSpecifier, std::string(buff));
  2135. }
  2136. if (logFormat->hasFlag(base::FormatFlags::Location)) {
  2137. // Location
  2138. char* buf = base::utils::Str::clearBuff(buff,
  2139. base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength);
  2140. base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff);
  2141. buf = base::utils::Str::addToBuff(buff, buf, bufLim);
  2142. buf = base::utils::Str::addToBuff(":", buf, bufLim);
  2143. buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), base::consts::kSourceLineMaxLength, buf, bufLim,
  2144. false);
  2145. base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLocationFormatSpecifier, std::string(buff));
  2146. }
  2147. if (logMessage->level() == Level::Verbose && logFormat->hasFlag(base::FormatFlags::VerboseLevel)) {
  2148. // Verbose level
  2149. char* buf = base::utils::Str::clearBuff(buff, 1);
  2150. buf = base::utils::Str::convertAndAddToBuff(logMessage->verboseLevel(), 1, buf, bufLim, false);
  2151. base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kVerboseLevelFormatSpecifier, std::string(buff));
  2152. }
  2153. if (logFormat->hasFlag(base::FormatFlags::LogMessage)) {
  2154. // Log message
  2155. base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kMessageFormatSpecifier, logMessage->message());
  2156. }
  2157. #if !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS)
  2158. el::base::threading::ScopedLock lock_(ELPP->lock());
  2159. ELPP_UNUSED(lock_);
  2160. for (std::vector<CustomFormatSpecifier>::const_iterator it = ELPP->customFormatSpecifiers()->begin();
  2161. it != ELPP->customFormatSpecifiers()->end(); ++it) {
  2162. std::string fs(it->formatSpecifier());
  2163. base::type::string_t wcsFormatSpecifier(fs.begin(), fs.end());
  2164. base::utils::Str::replaceFirstWithEscape(logLine, wcsFormatSpecifier, it->resolver()(logMessage));
  2165. }
  2166. #endif // !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS)
  2167. if (appendNewLine) logLine += ELPP_LITERAL("\n");
  2168. return logLine;
  2169. }
  2170. // LogDispatcher
  2171. void LogDispatcher::dispatch(void) {
  2172. if (m_proceed && m_dispatchAction == base::DispatchAction::None) {
  2173. m_proceed = false;
  2174. }
  2175. if (!m_proceed) {
  2176. return;
  2177. }
  2178. base::TypedConfigurations* tc = m_logMessage.logger()->m_typedConfigurations;
  2179. if (ELPP->hasFlag(LoggingFlag::StrictLogFileSizeCheck)) {
  2180. tc->validateFileRolling(m_logMessage.level(), ELPP->preRollOutCallback());
  2181. }
  2182. LogDispatchCallback* callback = nullptr;
  2183. LogDispatchData data;
  2184. for (const std::pair<std::string, base::type::LogDispatchCallbackPtr>& h
  2185. : ELPP->m_logDispatchCallbacks) {
  2186. callback = h.second.get();
  2187. if (callback != nullptr && callback->enabled()) {
  2188. data.setLogMessage(&m_logMessage);
  2189. data.setDispatchAction(m_dispatchAction);
  2190. callback->handle(&data);
  2191. }
  2192. }
  2193. }
  2194. // MessageBuilder
  2195. void MessageBuilder::initialize(Logger* logger) {
  2196. m_logger = logger;
  2197. m_containerLogSeperator = ELPP->hasFlag(LoggingFlag::NewLineForContainer) ?
  2198. ELPP_LITERAL("\n ") : ELPP_LITERAL(", ");
  2199. }
  2200. MessageBuilder& MessageBuilder::operator<<(const wchar_t* msg) {
  2201. if (msg == nullptr) {
  2202. m_logger->stream() << base::consts::kNullPointer;
  2203. return *this;
  2204. }
  2205. # if defined(ELPP_UNICODE)
  2206. m_logger->stream() << msg;
  2207. # else
  2208. char* buff_ = base::utils::Str::wcharPtrToCharPtr(msg);
  2209. m_logger->stream() << buff_;
  2210. free(buff_);
  2211. # endif
  2212. if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) {
  2213. m_logger->stream() << " ";
  2214. }
  2215. return *this;
  2216. }
  2217. // Writer
  2218. Writer& Writer::construct(Logger* logger, bool needLock) {
  2219. m_logger = logger;
  2220. initializeLogger(logger->id(), false, needLock);
  2221. m_messageBuilder.initialize(m_logger);
  2222. return *this;
  2223. }
  2224. Writer& Writer::construct(int count, const char* loggerIds, ...) {
  2225. if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) {
  2226. va_list loggersList;
  2227. va_start(loggersList, loggerIds);
  2228. const char* id = loggerIds;
  2229. for (int i = 0; i < count; ++i) {
  2230. m_loggerIds.push_back(std::string(id));
  2231. id = va_arg(loggersList, const char*);
  2232. }
  2233. va_end(loggersList);
  2234. initializeLogger(m_loggerIds.at(0));
  2235. } else {
  2236. initializeLogger(std::string(loggerIds));
  2237. }
  2238. m_messageBuilder.initialize(m_logger);
  2239. return *this;
  2240. }
  2241. void Writer::initializeLogger(const std::string& loggerId, bool lookup, bool needLock) {
  2242. if (lookup) {
  2243. m_logger = ELPP->registeredLoggers()->get(loggerId, ELPP->hasFlag(LoggingFlag::CreateLoggerAutomatically));
  2244. }
  2245. if (m_logger == nullptr) {
  2246. {
  2247. base::threading::ScopedLock scopedLock(ELPP->lock());
  2248. if (!ELPP->registeredLoggers()->has(std::string(base::consts::kDefaultLoggerId))) {
  2249. // Somehow default logger has been unregistered. Not good! Register again
  2250. ELPP->registeredLoggers()->get(std::string(base::consts::kDefaultLoggerId));
  2251. }
  2252. }
  2253. Writer(Level::Debug, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId)
  2254. << "Logger [" << loggerId << "] is not registered yet!";
  2255. m_proceed = false;
  2256. } else {
  2257. if (needLock) {
  2258. m_logger->acquireLock(); // This should not be unlocked by checking m_proceed because
  2259. // m_proceed can be changed by lines below
  2260. }
  2261. if (ELPP->hasFlag(LoggingFlag::HierarchicalLogging)) {
  2262. m_proceed = m_level == Level::Verbose ? m_logger->enabled(m_level) :
  2263. LevelHelper::castToInt(m_level) >= LevelHelper::castToInt(ELPP->m_loggingLevel);
  2264. } else {
  2265. m_proceed = m_logger->enabled(m_level);
  2266. }
  2267. }
  2268. }
  2269. void Writer::processDispatch() {
  2270. #if ELPP_LOGGING_ENABLED
  2271. if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) {
  2272. bool firstDispatched = false;
  2273. base::type::string_t logMessage;
  2274. std::size_t i = 0;
  2275. do {
  2276. if (m_proceed) {
  2277. if (firstDispatched) {
  2278. m_logger->stream() << logMessage;
  2279. } else {
  2280. firstDispatched = true;
  2281. if (m_loggerIds.size() > 1) {
  2282. logMessage = m_logger->stream().str();
  2283. }
  2284. }
  2285. triggerDispatch();
  2286. } else if (m_logger != nullptr) {
  2287. m_logger->stream().str(ELPP_LITERAL(""));
  2288. m_logger->releaseLock();
  2289. }
  2290. if (i + 1 < m_loggerIds.size()) {
  2291. initializeLogger(m_loggerIds.at(i + 1));
  2292. }
  2293. } while (++i < m_loggerIds.size());
  2294. } else {
  2295. if (m_proceed) {
  2296. triggerDispatch();
  2297. } else if (m_logger != nullptr) {
  2298. m_logger->stream().str(ELPP_LITERAL(""));
  2299. m_logger->releaseLock();
  2300. }
  2301. }
  2302. #else
  2303. if (m_logger != nullptr) {
  2304. m_logger->stream().str(ELPP_LITERAL(""));
  2305. m_logger->releaseLock();
  2306. }
  2307. #endif // ELPP_LOGGING_ENABLED
  2308. }
  2309. void Writer::triggerDispatch(void) {
  2310. if (m_proceed) {
  2311. base::LogDispatcher(m_proceed, LogMessage(m_level, m_file, m_line, m_func, m_verboseLevel,
  2312. m_logger), m_dispatchAction).dispatch();
  2313. }
  2314. if (m_logger != nullptr) {
  2315. m_logger->stream().str(ELPP_LITERAL(""));
  2316. m_logger->releaseLock();
  2317. }
  2318. if (m_proceed && m_level == Level::Fatal
  2319. && !ELPP->hasFlag(LoggingFlag::DisableApplicationAbortOnFatalLog)) {
  2320. base::Writer(Level::Warning, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId)
  2321. << "Aborting application. Reason: Fatal log at [" << m_file << ":" << m_line << "]";
  2322. std::stringstream reasonStream;
  2323. reasonStream << "Fatal log at [" << m_file << ":" << m_line << "]"
  2324. << " If you wish to disable 'abort on fatal log' please use "
  2325. << "el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog)";
  2326. base::utils::abort(1, reasonStream.str());
  2327. }
  2328. m_proceed = false;
  2329. }
  2330. // PErrorWriter
  2331. PErrorWriter::~PErrorWriter(void) {
  2332. if (m_proceed) {
  2333. #if ELPP_COMPILER_MSVC
  2334. char buff[256];
  2335. strerror_s(buff, 256, errno);
  2336. m_logger->stream() << ": " << buff << " [" << errno << "]";
  2337. #else
  2338. m_logger->stream() << ": " << strerror(errno) << " [" << errno << "]";
  2339. #endif
  2340. }
  2341. }
  2342. // PerformanceTracker
  2343. #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
  2344. PerformanceTracker::PerformanceTracker(const std::string& blockName,
  2345. base::TimestampUnit timestampUnit,
  2346. const std::string& loggerId,
  2347. bool scopedLog, Level level) :
  2348. m_blockName(blockName), m_timestampUnit(timestampUnit), m_loggerId(loggerId), m_scopedLog(scopedLog),
  2349. m_level(level), m_hasChecked(false), m_lastCheckpointId(std::string()), m_enabled(false) {
  2350. #if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
  2351. // We store it locally so that if user happen to change configuration by the end of scope
  2352. // or before calling checkpoint, we still depend on state of configuraton at time of construction
  2353. el::Logger* loggerPtr = ELPP->registeredLoggers()->get(loggerId, false);
  2354. m_enabled = loggerPtr != nullptr && loggerPtr->m_typedConfigurations->performanceTracking(m_level);
  2355. if (m_enabled) {
  2356. base::utils::DateTime::gettimeofday(&m_startTime);
  2357. }
  2358. #endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
  2359. }
  2360. PerformanceTracker::~PerformanceTracker(void) {
  2361. #if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
  2362. if (m_enabled) {
  2363. base::threading::ScopedLock scopedLock(lock());
  2364. if (m_scopedLog) {
  2365. base::utils::DateTime::gettimeofday(&m_endTime);
  2366. base::type::string_t formattedTime = getFormattedTimeTaken();
  2367. PerformanceTrackingData data(PerformanceTrackingData::DataType::Complete);
  2368. data.init(this);
  2369. data.m_formattedTimeTaken = formattedTime;
  2370. PerformanceTrackingCallback* callback = nullptr;
  2371. for (const std::pair<std::string, base::type::PerformanceTrackingCallbackPtr>& h
  2372. : ELPP->m_performanceTrackingCallbacks) {
  2373. callback = h.second.get();
  2374. if (callback != nullptr && callback->enabled()) {
  2375. callback->handle(&data);
  2376. }
  2377. }
  2378. }
  2379. }
  2380. #endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING)
  2381. }
  2382. void PerformanceTracker::checkpoint(const std::string& id, const char* file, base::type::LineNumber line,
  2383. const char* func) {
  2384. #if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
  2385. if (m_enabled) {
  2386. base::threading::ScopedLock scopedLock(lock());
  2387. base::utils::DateTime::gettimeofday(&m_endTime);
  2388. base::type::string_t formattedTime = m_hasChecked ? getFormattedTimeTaken(m_lastCheckpointTime) : ELPP_LITERAL("");
  2389. PerformanceTrackingData data(PerformanceTrackingData::DataType::Checkpoint);
  2390. data.init(this);
  2391. data.m_checkpointId = id;
  2392. data.m_file = file;
  2393. data.m_line = line;
  2394. data.m_func = func;
  2395. data.m_formattedTimeTaken = formattedTime;
  2396. PerformanceTrackingCallback* callback = nullptr;
  2397. for (const std::pair<std::string, base::type::PerformanceTrackingCallbackPtr>& h
  2398. : ELPP->m_performanceTrackingCallbacks) {
  2399. callback = h.second.get();
  2400. if (callback != nullptr && callback->enabled()) {
  2401. callback->handle(&data);
  2402. }
  2403. }
  2404. base::utils::DateTime::gettimeofday(&m_lastCheckpointTime);
  2405. m_hasChecked = true;
  2406. m_lastCheckpointId = id;
  2407. }
  2408. #endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
  2409. ELPP_UNUSED(id);
  2410. ELPP_UNUSED(file);
  2411. ELPP_UNUSED(line);
  2412. ELPP_UNUSED(func);
  2413. }
  2414. const base::type::string_t PerformanceTracker::getFormattedTimeTaken(struct timeval startTime) const {
  2415. if (ELPP->hasFlag(LoggingFlag::FixedTimeFormat)) {
  2416. base::type::stringstream_t ss;
  2417. ss << base::utils::DateTime::getTimeDifference(m_endTime,
  2418. startTime, m_timestampUnit) << " " << base::consts::kTimeFormats[static_cast<base::type::EnumType>
  2419. (m_timestampUnit)].unit;
  2420. return ss.str();
  2421. }
  2422. return base::utils::DateTime::formatTime(base::utils::DateTime::getTimeDifference(m_endTime,
  2423. startTime, m_timestampUnit), m_timestampUnit);
  2424. }
  2425. #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
  2426. namespace debug {
  2427. #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
  2428. // StackTrace
  2429. StackTrace::StackTraceEntry::StackTraceEntry(std::size_t index, const char* loc, const char* demang, const char* hex,
  2430. const char* addr) {
  2431. m_index = index;
  2432. m_location = std::string(loc);
  2433. m_demangled = std::string(demang);
  2434. m_hex = std::string(hex);
  2435. m_addr = std::string(addr);
  2436. }
  2437. std::ostream& operator<<(std::ostream& ss, const StackTrace::StackTraceEntry& si) {
  2438. ss << "[" << si.m_index << "] " << si.m_location << (si.m_demangled.empty() ? "" : ":") << si.m_demangled
  2439. << (si.m_hex.empty() ? "" : "+") << si.m_hex << si.m_addr;
  2440. return ss;
  2441. }
  2442. std::ostream& operator<<(std::ostream& os, const StackTrace& st) {
  2443. std::vector<StackTrace::StackTraceEntry>::const_iterator it = st.m_stack.begin();
  2444. while (it != st.m_stack.end()) {
  2445. os << " " << *it++ << "\n";
  2446. }
  2447. return os;
  2448. }
  2449. void StackTrace::generateNew(void) {
  2450. #if ELPP_STACKTRACE
  2451. m_stack.clear();
  2452. void* stack[kMaxStack];
  2453. unsigned int size = backtrace(stack, kMaxStack);
  2454. char** strings = backtrace_symbols(stack, size);
  2455. if (size > kStackStart) { // Skip StackTrace c'tor and generateNew
  2456. for (std::size_t i = kStackStart; i < size; ++i) {
  2457. char* mangName = nullptr;
  2458. char* hex = nullptr;
  2459. char* addr = nullptr;
  2460. for (char* c = strings[i]; *c; ++c) {
  2461. switch (*c) {
  2462. case '(':
  2463. mangName = c;
  2464. break;
  2465. case '+':
  2466. hex = c;
  2467. break;
  2468. case ')':
  2469. addr = c;
  2470. break;
  2471. default:
  2472. break;
  2473. }
  2474. }
  2475. // Perform demangling if parsed properly
  2476. if (mangName != nullptr && hex != nullptr && addr != nullptr && mangName < hex) {
  2477. *mangName++ = '\0';
  2478. *hex++ = '\0';
  2479. *addr++ = '\0';
  2480. int status = 0;
  2481. char* demangName = abi::__cxa_demangle(mangName, 0, 0, &status);
  2482. // if demangling is successful, output the demangled function name
  2483. if (status == 0) {
  2484. // Success (see http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html)
  2485. StackTraceEntry entry(i - 1, strings[i], demangName, hex, addr);
  2486. m_stack.push_back(entry);
  2487. } else {
  2488. // Not successful - we will use mangled name
  2489. StackTraceEntry entry(i - 1, strings[i], mangName, hex, addr);
  2490. m_stack.push_back(entry);
  2491. }
  2492. free(demangName);
  2493. } else {
  2494. StackTraceEntry entry(i - 1, strings[i]);
  2495. m_stack.push_back(entry);
  2496. }
  2497. }
  2498. }
  2499. free(strings);
  2500. #else
  2501. ELPP_INTERNAL_INFO(1, "Stacktrace generation not supported for selected compiler");
  2502. #endif // ELPP_STACKTRACE
  2503. }
  2504. // Static helper functions
  2505. static std::string crashReason(int sig) {
  2506. std::stringstream ss;
  2507. bool foundReason = false;
  2508. for (int i = 0; i < base::consts::kCrashSignalsCount; ++i) {
  2509. if (base::consts::kCrashSignals[i].numb == sig) {
  2510. ss << "Application has crashed due to [" << base::consts::kCrashSignals[i].name << "] signal";
  2511. if (ELPP->hasFlag(el::LoggingFlag::LogDetailedCrashReason)) {
  2512. ss << std::endl <<
  2513. " " << base::consts::kCrashSignals[i].brief << std::endl <<
  2514. " " << base::consts::kCrashSignals[i].detail;
  2515. }
  2516. foundReason = true;
  2517. }
  2518. }
  2519. if (!foundReason) {
  2520. ss << "Application has crashed due to unknown signal [" << sig << "]";
  2521. }
  2522. return ss.str();
  2523. }
  2524. /// @brief Logs reason of crash from sig
  2525. static void logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) {
  2526. std::stringstream ss;
  2527. ss << "CRASH HANDLED; ";
  2528. ss << crashReason(sig);
  2529. #if ELPP_STACKTRACE
  2530. if (stackTraceIfAvailable) {
  2531. ss << std::endl << " ======= Backtrace: =========" << std::endl << base::debug::StackTrace();
  2532. }
  2533. #else
  2534. ELPP_UNUSED(stackTraceIfAvailable);
  2535. #endif // ELPP_STACKTRACE
  2536. ELPP_WRITE_LOG(el::base::Writer, level, base::DispatchAction::NormalLog, logger) << ss.str();
  2537. }
  2538. static inline void crashAbort(int sig) {
  2539. base::utils::abort(sig, std::string());
  2540. }
  2541. /// @brief Default application crash handler
  2542. ///
  2543. /// @detail This function writes log using 'default' logger, prints stack trace for GCC based compilers and aborts program.
  2544. static inline void defaultCrashHandler(int sig) {
  2545. base::debug::logCrashReason(sig, true, Level::Fatal, base::consts::kDefaultLoggerId);
  2546. base::debug::crashAbort(sig);
  2547. }
  2548. // CrashHandler
  2549. CrashHandler::CrashHandler(bool useDefault) {
  2550. if (useDefault) {
  2551. setHandler(defaultCrashHandler);
  2552. }
  2553. }
  2554. void CrashHandler::setHandler(const Handler& cHandler) {
  2555. m_handler = cHandler;
  2556. #if defined(ELPP_HANDLE_SIGABRT)
  2557. int i = 0; // SIGABRT is at base::consts::kCrashSignals[0]
  2558. #else
  2559. int i = 1;
  2560. #endif // defined(ELPP_HANDLE_SIGABRT)
  2561. for (; i < base::consts::kCrashSignalsCount; ++i) {
  2562. m_handler = signal(base::consts::kCrashSignals[i].numb, cHandler);
  2563. }
  2564. }
  2565. #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
  2566. } // namespace debug
  2567. } // namespace base
  2568. // el
  2569. // Helpers
  2570. #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
  2571. void Helpers::crashAbort(int sig, const char* sourceFile, unsigned int long line) {
  2572. std::stringstream ss;
  2573. ss << base::debug::crashReason(sig).c_str();
  2574. ss << " - [Called el::Helpers::crashAbort(" << sig << ")]";
  2575. if (sourceFile != nullptr && strlen(sourceFile) > 0) {
  2576. ss << " - Source: " << sourceFile;
  2577. if (line > 0)
  2578. ss << ":" << line;
  2579. else
  2580. ss << " (line number not specified)";
  2581. }
  2582. base::utils::abort(sig, ss.str());
  2583. }
  2584. void Helpers::logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) {
  2585. el::base::debug::logCrashReason(sig, stackTraceIfAvailable, level, logger);
  2586. }
  2587. #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
  2588. // Loggers
  2589. Logger* Loggers::getLogger(const std::string& identity, bool registerIfNotAvailable) {
  2590. base::threading::ScopedLock scopedLock(ELPP->lock());
  2591. return ELPP->registeredLoggers()->get(identity, registerIfNotAvailable);
  2592. }
  2593. void Loggers::setDefaultLogBuilder(el::LogBuilderPtr& logBuilderPtr) {
  2594. ELPP->registeredLoggers()->setDefaultLogBuilder(logBuilderPtr);
  2595. }
  2596. bool Loggers::unregisterLogger(const std::string& identity) {
  2597. base::threading::ScopedLock scopedLock(ELPP->lock());
  2598. return ELPP->registeredLoggers()->remove(identity);
  2599. }
  2600. bool Loggers::hasLogger(const std::string& identity) {
  2601. base::threading::ScopedLock scopedLock(ELPP->lock());
  2602. return ELPP->registeredLoggers()->has(identity);
  2603. }
  2604. Logger* Loggers::reconfigureLogger(Logger* logger, const Configurations& configurations) {
  2605. if (!logger) return nullptr;
  2606. logger->configure(configurations);
  2607. return logger;
  2608. }
  2609. Logger* Loggers::reconfigureLogger(const std::string& identity, const Configurations& configurations) {
  2610. return Loggers::reconfigureLogger(Loggers::getLogger(identity), configurations);
  2611. }
  2612. Logger* Loggers::reconfigureLogger(const std::string& identity, ConfigurationType configurationType,
  2613. const std::string& value) {
  2614. Logger* logger = Loggers::getLogger(identity);
  2615. if (logger == nullptr) {
  2616. return nullptr;
  2617. }
  2618. logger->configurations()->set(Level::Global, configurationType, value);
  2619. logger->reconfigure();
  2620. return logger;
  2621. }
  2622. void Loggers::reconfigureAllLoggers(const Configurations& configurations) {
  2623. for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin();
  2624. it != ELPP->registeredLoggers()->end(); ++it) {
  2625. Loggers::reconfigureLogger(it->second, configurations);
  2626. }
  2627. }
  2628. void Loggers::reconfigureAllLoggers(Level level, ConfigurationType configurationType,
  2629. const std::string& value) {
  2630. for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin();
  2631. it != ELPP->registeredLoggers()->end(); ++it) {
  2632. Logger* logger = it->second;
  2633. logger->configurations()->set(level, configurationType, value);
  2634. logger->reconfigure();
  2635. }
  2636. }
  2637. void Loggers::setDefaultConfigurations(const Configurations& configurations, bool reconfigureExistingLoggers) {
  2638. ELPP->registeredLoggers()->setDefaultConfigurations(configurations);
  2639. if (reconfigureExistingLoggers) {
  2640. Loggers::reconfigureAllLoggers(configurations);
  2641. }
  2642. }
  2643. const Configurations* Loggers::defaultConfigurations(void) {
  2644. return ELPP->registeredLoggers()->defaultConfigurations();
  2645. }
  2646. const base::LogStreamsReferenceMap* Loggers::logStreamsReference(void) {
  2647. return ELPP->registeredLoggers()->logStreamsReference();
  2648. }
  2649. base::TypedConfigurations Loggers::defaultTypedConfigurations(void) {
  2650. return base::TypedConfigurations(
  2651. ELPP->registeredLoggers()->defaultConfigurations(),
  2652. ELPP->registeredLoggers()->logStreamsReference());
  2653. }
  2654. std::vector<std::string>* Loggers::populateAllLoggerIds(std::vector<std::string>* targetList) {
  2655. targetList->clear();
  2656. for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->list().begin();
  2657. it != ELPP->registeredLoggers()->list().end(); ++it) {
  2658. targetList->push_back(it->first);
  2659. }
  2660. return targetList;
  2661. }
  2662. void Loggers::configureFromGlobal(const char* globalConfigurationFilePath) {
  2663. std::ifstream gcfStream(globalConfigurationFilePath, std::ifstream::in);
  2664. ELPP_ASSERT(gcfStream.is_open(), "Unable to open global configuration file [" << globalConfigurationFilePath
  2665. << "] for parsing.");
  2666. std::string line = std::string();
  2667. std::stringstream ss;
  2668. Logger* logger = nullptr;
  2669. auto configure = [&](void) {
  2670. ELPP_INTERNAL_INFO(8, "Configuring logger: '" << logger->id() << "' with configurations \n" << ss.str()
  2671. << "\n--------------");
  2672. Configurations c;
  2673. c.parseFromText(ss.str());
  2674. logger->configure(c);
  2675. };
  2676. while (gcfStream.good()) {
  2677. std::getline(gcfStream, line);
  2678. ELPP_INTERNAL_INFO(1, "Parsing line: " << line);
  2679. base::utils::Str::trim(line);
  2680. if (Configurations::Parser::isComment(line)) continue;
  2681. Configurations::Parser::ignoreComments(&line);
  2682. base::utils::Str::trim(line);
  2683. if (line.size() > 2 && base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLoggerId))) {
  2684. if (!ss.str().empty() && logger != nullptr) {
  2685. configure();
  2686. }
  2687. ss.str(std::string(""));
  2688. line = line.substr(2);
  2689. base::utils::Str::trim(line);
  2690. if (line.size() > 1) {
  2691. ELPP_INTERNAL_INFO(1, "Getting logger: '" << line << "'");
  2692. logger = getLogger(line);
  2693. }
  2694. } else {
  2695. ss << line << "\n";
  2696. }
  2697. }
  2698. if (!ss.str().empty() && logger != nullptr) {
  2699. configure();
  2700. }
  2701. }
  2702. bool Loggers::configureFromArg(const char* argKey) {
  2703. #if defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS)
  2704. ELPP_UNUSED(argKey);
  2705. #else
  2706. if (!Helpers::commandLineArgs()->hasParamWithValue(argKey)) {
  2707. return false;
  2708. }
  2709. configureFromGlobal(Helpers::commandLineArgs()->getParamValue(argKey));
  2710. #endif // defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS)
  2711. return true;
  2712. }
  2713. void Loggers::flushAll(void) {
  2714. ELPP->registeredLoggers()->flushAll();
  2715. }
  2716. void Loggers::setVerboseLevel(base::type::VerboseLevel level) {
  2717. ELPP->vRegistry()->setLevel(level);
  2718. }
  2719. base::type::VerboseLevel Loggers::verboseLevel(void) {
  2720. return ELPP->vRegistry()->level();
  2721. }
  2722. void Loggers::setVModules(const char* modules) {
  2723. if (ELPP->vRegistry()->vModulesEnabled()) {
  2724. ELPP->vRegistry()->setModules(modules);
  2725. }
  2726. }
  2727. void Loggers::clearVModules(void) {
  2728. ELPP->vRegistry()->clearModules();
  2729. }
  2730. // VersionInfo
  2731. const std::string VersionInfo::version(void) {
  2732. return std::string("9.95.3");
  2733. }
  2734. /// @brief Release date of current version
  2735. const std::string VersionInfo::releaseDate(void) {
  2736. return std::string("13-10-2017 1134hrs");
  2737. }
  2738. } // namespace el