Digitalisierte Elektroverteilung zur permanenten Verbraucherüberwachung
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

easylogging++.cc 119KB

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