easylogging++.h 180 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611
  1. //
  2. // Bismillah ar-Rahmaan ar-Raheem
  3. //
  4. // Easylogging++ v9.95.3
  5. // Single-header only, cross-platform logging library for C++ applications
  6. //
  7. // Copyright (c) 2017 muflihun.com
  8. //
  9. // This library is released under the MIT Licence.
  10. // http://labs.muflihun.com/easyloggingpp/licence.php
  11. //
  12. // https://github.com/muflihun/easyloggingpp
  13. // https://muflihun.github.io/easyloggingpp
  14. // http://muflihun.com
  15. //
  16. #ifndef EASYLOGGINGPP_H
  17. #define EASYLOGGINGPP_H
  18. #define ELPP_FEATURE_CRASH_LOG
  19. #define ELPP_HANDLE_SIGABRT
  20. #define ELPP_DEFAULT_LOG_FILE "dat_library.log"
  21. #define ELPP_DEBUG_ERRORS
  22. // Compilers and C++0x/C++11 Evaluation
  23. #if __cplusplus >= 201103L
  24. # define ELPP_CXX11 1
  25. #endif // __cplusplus >= 201103L
  26. #if (defined(__GNUC__))
  27. # define ELPP_COMPILER_GCC 1
  28. #else
  29. # define ELPP_COMPILER_GCC 0
  30. #endif
  31. #if ELPP_COMPILER_GCC
  32. # define ELPP_GCC_VERSION (__GNUC__ * 10000 \
  33. + __GNUC_MINOR__ * 100 \
  34. + __GNUC_PATCHLEVEL__)
  35. # if defined(__GXX_EXPERIMENTAL_CXX0X__)
  36. # define ELPP_CXX0X 1
  37. # endif
  38. #endif
  39. // Visual C++
  40. #if defined(_MSC_VER)
  41. # define ELPP_COMPILER_MSVC 1
  42. #else
  43. # define ELPP_COMPILER_MSVC 0
  44. #endif
  45. #define ELPP_CRT_DBG_WARNINGS ELPP_COMPILER_MSVC
  46. #if ELPP_COMPILER_MSVC
  47. # if (_MSC_VER == 1600)
  48. # define ELPP_CXX0X 1
  49. # elif(_MSC_VER >= 1700)
  50. # define ELPP_CXX11 1
  51. # endif
  52. #endif
  53. // Clang++
  54. #if (defined(__clang__) && (__clang__ == 1))
  55. # define ELPP_COMPILER_CLANG 1
  56. #else
  57. # define ELPP_COMPILER_CLANG 0
  58. #endif
  59. #if ELPP_COMPILER_CLANG
  60. # if __has_include(<thread>)
  61. # include <cstddef> // Make __GLIBCXX__ defined when using libstdc++
  62. # if !defined(__GLIBCXX__) || __GLIBCXX__ >= 20150426
  63. # define ELPP_CLANG_SUPPORTS_THREAD
  64. # endif // !defined(__GLIBCXX__) || __GLIBCXX__ >= 20150426
  65. # endif // __has_include(<thread>)
  66. #endif
  67. #if (defined(__MINGW32__) || defined(__MINGW64__))
  68. # define ELPP_MINGW 1
  69. #else
  70. # define ELPP_MINGW 0
  71. #endif
  72. #if (defined(__CYGWIN__) && (__CYGWIN__ == 1))
  73. # define ELPP_CYGWIN 1
  74. #else
  75. # define ELPP_CYGWIN 0
  76. #endif
  77. #if (defined(__INTEL_COMPILER))
  78. # define ELPP_COMPILER_INTEL 1
  79. #else
  80. # define ELPP_COMPILER_INTEL 0
  81. #endif
  82. // Operating System Evaluation
  83. // Windows
  84. #if (defined(_WIN32) || defined(_WIN64))
  85. # define ELPP_OS_WINDOWS 1
  86. #else
  87. # define ELPP_OS_WINDOWS 0
  88. #endif
  89. // Linux
  90. #if (defined(__linux) || defined(__linux__))
  91. # define ELPP_OS_LINUX 1
  92. #else
  93. # define ELPP_OS_LINUX 0
  94. #endif
  95. #if (defined(__APPLE__))
  96. # define ELPP_OS_MAC 1
  97. #else
  98. # define ELPP_OS_MAC 0
  99. #endif
  100. #if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__))
  101. # define ELPP_OS_FREEBSD 1
  102. #else
  103. # define ELPP_OS_FREEBSD 0
  104. #endif
  105. #if (defined(__sun))
  106. # define ELPP_OS_SOLARIS 1
  107. #else
  108. # define ELPP_OS_SOLARIS 0
  109. #endif
  110. #if (defined(_AIX))
  111. # define ELPP_OS_AIX 1
  112. #else
  113. # define ELPP_OS_AIX 0
  114. #endif
  115. #if (defined(__NetBSD__))
  116. # define ELPP_OS_NETBSD 1
  117. #else
  118. # define ELPP_OS_NETBSD 0
  119. #endif
  120. // Unix
  121. #if ((ELPP_OS_LINUX || ELPP_OS_MAC || ELPP_OS_FREEBSD || ELPP_OS_NETBSD || ELPP_OS_SOLARIS || ELPP_OS_AIX) && (!ELPP_OS_WINDOWS))
  122. # define ELPP_OS_UNIX 1
  123. #else
  124. # define ELPP_OS_UNIX 0
  125. #endif
  126. #if (defined(__ANDROID__))
  127. # define ELPP_OS_ANDROID 1
  128. #else
  129. # define ELPP_OS_ANDROID 0
  130. #endif
  131. // Evaluating Cygwin as *nix OS
  132. #if !ELPP_OS_UNIX && !ELPP_OS_WINDOWS && ELPP_CYGWIN
  133. # undef ELPP_OS_UNIX
  134. # undef ELPP_OS_LINUX
  135. # define ELPP_OS_UNIX 1
  136. # define ELPP_OS_LINUX 1
  137. #endif // !ELPP_OS_UNIX && !ELPP_OS_WINDOWS && ELPP_CYGWIN
  138. #if !defined(ELPP_INTERNAL_DEBUGGING_OUT_INFO)
  139. # define ELPP_INTERNAL_DEBUGGING_OUT_INFO std::cout
  140. #endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT)
  141. #if !defined(ELPP_INTERNAL_DEBUGGING_OUT_ERROR)
  142. # define ELPP_INTERNAL_DEBUGGING_OUT_ERROR std::cerr
  143. #endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT)
  144. #if !defined(ELPP_INTERNAL_DEBUGGING_ENDL)
  145. # define ELPP_INTERNAL_DEBUGGING_ENDL std::endl
  146. #endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT)
  147. #if !defined(ELPP_INTERNAL_DEBUGGING_MSG)
  148. # define ELPP_INTERNAL_DEBUGGING_MSG(msg) msg
  149. #endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT)
  150. // Internal Assertions and errors
  151. #if !defined(ELPP_DISABLE_ASSERT)
  152. # if (defined(ELPP_DEBUG_ASSERT_FAILURE))
  153. # define ELPP_ASSERT(expr, msg) if (!(expr)) { \
  154. std::stringstream internalInfoStream; internalInfoStream << msg; \
  155. ELPP_INTERNAL_DEBUGGING_OUT_ERROR \
  156. << "EASYLOGGING++ ASSERTION FAILED (LINE: " << __LINE__ << ") [" #expr << "] WITH MESSAGE \"" \
  157. << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << "\"" << ELPP_INTERNAL_DEBUGGING_ENDL; base::utils::abort(1, \
  158. "ELPP Assertion failure, please define ELPP_DEBUG_ASSERT_FAILURE"); }
  159. # else
  160. # define ELPP_ASSERT(expr, msg) if (!(expr)) { \
  161. std::stringstream internalInfoStream; internalInfoStream << msg; \
  162. ELPP_INTERNAL_DEBUGGING_OUT_ERROR\
  163. << "ASSERTION FAILURE FROM EASYLOGGING++ (LINE: " \
  164. << __LINE__ << ") [" #expr << "] WITH MESSAGE \"" << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << "\"" \
  165. << ELPP_INTERNAL_DEBUGGING_ENDL; }
  166. # endif // (defined(ELPP_DEBUG_ASSERT_FAILURE))
  167. #else
  168. # define ELPP_ASSERT(x, y)
  169. #endif //(!defined(ELPP_DISABLE_ASSERT)
  170. #if ELPP_COMPILER_MSVC
  171. # define ELPP_INTERNAL_DEBUGGING_WRITE_PERROR \
  172. { char buff[256]; strerror_s(buff, 256, errno); \
  173. ELPP_INTERNAL_DEBUGGING_OUT_ERROR << ": " << buff << " [" << errno << "]";} (void)0
  174. #else
  175. # define ELPP_INTERNAL_DEBUGGING_WRITE_PERROR \
  176. ELPP_INTERNAL_DEBUGGING_OUT_ERROR << ": " << strerror(errno) << " [" << errno << "]"; (void)0
  177. #endif // ELPP_COMPILER_MSVC
  178. #if defined(ELPP_DEBUG_ERRORS)
  179. # if !defined(ELPP_INTERNAL_ERROR)
  180. # define ELPP_INTERNAL_ERROR(msg, pe) { \
  181. std::stringstream internalInfoStream; internalInfoStream << "<ERROR> " << msg; \
  182. ELPP_INTERNAL_DEBUGGING_OUT_ERROR \
  183. << "ERROR FROM EASYLOGGING++ (LINE: " << __LINE__ << ") " \
  184. << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << ELPP_INTERNAL_DEBUGGING_ENDL; \
  185. if (pe) { ELPP_INTERNAL_DEBUGGING_OUT_ERROR << " "; ELPP_INTERNAL_DEBUGGING_WRITE_PERROR; }} (void)0
  186. # endif
  187. #else
  188. # undef ELPP_INTERNAL_INFO
  189. # define ELPP_INTERNAL_ERROR(msg, pe)
  190. #endif // defined(ELPP_DEBUG_ERRORS)
  191. #if (defined(ELPP_DEBUG_INFO))
  192. # if !(defined(ELPP_INTERNAL_INFO_LEVEL))
  193. # define ELPP_INTERNAL_INFO_LEVEL 9
  194. # endif // !(defined(ELPP_INTERNAL_INFO_LEVEL))
  195. # if !defined(ELPP_INTERNAL_INFO)
  196. # define ELPP_INTERNAL_INFO(lvl, msg) { if (lvl <= ELPP_INTERNAL_INFO_LEVEL) { \
  197. std::stringstream internalInfoStream; internalInfoStream << "<INFO> " << msg; \
  198. ELPP_INTERNAL_DEBUGGING_OUT_INFO << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) \
  199. << ELPP_INTERNAL_DEBUGGING_ENDL; }}
  200. # endif
  201. #else
  202. # undef ELPP_INTERNAL_INFO
  203. # define ELPP_INTERNAL_INFO(lvl, msg)
  204. #endif // (defined(ELPP_DEBUG_INFO))
  205. #if (defined(ELPP_FEATURE_ALL)) || (defined(ELPP_FEATURE_CRASH_LOG))
  206. # if (ELPP_COMPILER_GCC && !ELPP_MINGW && !ELPP_OS_ANDROID)
  207. # define ELPP_STACKTRACE 1
  208. # else
  209. # if ELPP_COMPILER_MSVC
  210. # pragma message("Stack trace not available for this compiler")
  211. # else
  212. # warning "Stack trace not available for this compiler";
  213. # endif // ELPP_COMPILER_MSVC
  214. # define ELPP_STACKTRACE 0
  215. # endif // ELPP_COMPILER_GCC
  216. #else
  217. # define ELPP_STACKTRACE 0
  218. #endif // (defined(ELPP_FEATURE_ALL)) || (defined(ELPP_FEATURE_CRASH_LOG))
  219. // Miscellaneous macros
  220. #define ELPP_UNUSED(x) (void)x
  221. #if ELPP_OS_UNIX
  222. // Log file permissions for unix-based systems
  223. # define ELPP_LOG_PERMS S_IRUSR | S_IWUSR | S_IXUSR | S_IWGRP | S_IRGRP | S_IXGRP | S_IWOTH | S_IXOTH
  224. #endif // ELPP_OS_UNIX
  225. #if defined(ELPP_AS_DLL) && ELPP_COMPILER_MSVC
  226. # if defined(ELPP_EXPORT_SYMBOLS)
  227. # define ELPP_EXPORT __declspec(dllexport)
  228. # else
  229. # define ELPP_EXPORT __declspec(dllimport)
  230. # endif // defined(ELPP_EXPORT_SYMBOLS)
  231. #else
  232. # define ELPP_EXPORT
  233. #endif // defined(ELPP_AS_DLL) && ELPP_COMPILER_MSVC
  234. // Some special functions that are VC++ specific
  235. #undef STRTOK
  236. #undef STRERROR
  237. #undef STRCAT
  238. #undef STRCPY
  239. #if ELPP_CRT_DBG_WARNINGS
  240. # define STRTOK(a, b, c) strtok_s(a, b, c)
  241. # define STRERROR(a, b, c) strerror_s(a, b, c)
  242. # define STRCAT(a, b, len) strcat_s(a, len, b)
  243. # define STRCPY(a, b, len) strcpy_s(a, len, b)
  244. #else
  245. # define STRTOK(a, b, c) strtok(a, b)
  246. # define STRERROR(a, b, c) strerror(c)
  247. # define STRCAT(a, b, len) strcat(a, b)
  248. # define STRCPY(a, b, len) strcpy(a, b)
  249. #endif
  250. // Compiler specific support evaluations
  251. #if (ELPP_MINGW && !defined(ELPP_FORCE_USE_STD_THREAD))
  252. # define ELPP_USE_STD_THREADING 0
  253. #else
  254. # if ((ELPP_COMPILER_CLANG && defined(ELPP_CLANG_SUPPORTS_THREAD)) || \
  255. (!ELPP_COMPILER_CLANG && defined(ELPP_CXX11)) || \
  256. defined(ELPP_FORCE_USE_STD_THREAD))
  257. # define ELPP_USE_STD_THREADING 1
  258. # else
  259. # define ELPP_USE_STD_THREADING 0
  260. # endif
  261. #endif
  262. #undef ELPP_FINAL
  263. #if ELPP_COMPILER_INTEL || (ELPP_GCC_VERSION < 40702)
  264. # define ELPP_FINAL
  265. #else
  266. # define ELPP_FINAL final
  267. #endif // ELPP_COMPILER_INTEL || (ELPP_GCC_VERSION < 40702)
  268. #if defined(ELPP_EXPERIMENTAL_ASYNC)
  269. # define ELPP_ASYNC_LOGGING 1
  270. #else
  271. # define ELPP_ASYNC_LOGGING 0
  272. #endif // defined(ELPP_EXPERIMENTAL_ASYNC)
  273. #if defined(ELPP_THREAD_SAFE) || ELPP_ASYNC_LOGGING
  274. # define ELPP_THREADING_ENABLED 1
  275. #else
  276. # define ELPP_THREADING_ENABLED 0
  277. #endif // defined(ELPP_THREAD_SAFE) || ELPP_ASYNC_LOGGING
  278. // Function macro ELPP_FUNC
  279. #undef ELPP_FUNC
  280. #if ELPP_COMPILER_MSVC // Visual C++
  281. # define ELPP_FUNC __FUNCSIG__
  282. #elif ELPP_COMPILER_GCC // GCC
  283. # define ELPP_FUNC __PRETTY_FUNCTION__
  284. #elif ELPP_COMPILER_INTEL // Intel C++
  285. # define ELPP_FUNC __PRETTY_FUNCTION__
  286. #elif ELPP_COMPILER_CLANG // Clang++
  287. # define ELPP_FUNC __PRETTY_FUNCTION__
  288. #else
  289. # if defined(__func__)
  290. # define ELPP_FUNC __func__
  291. # else
  292. # define ELPP_FUNC ""
  293. # endif // defined(__func__)
  294. #endif // defined(_MSC_VER)
  295. #undef ELPP_VARIADIC_TEMPLATES_SUPPORTED
  296. // Keep following line commented until features are fixed
  297. #define ELPP_VARIADIC_TEMPLATES_SUPPORTED \
  298. (ELPP_COMPILER_GCC || ELPP_COMPILER_CLANG || ELPP_COMPILER_INTEL || (ELPP_COMPILER_MSVC && _MSC_VER >= 1800))
  299. // Logging Enable/Disable macros
  300. #if defined(ELPP_DISABLE_LOGS)
  301. #define ELPP_LOGGING_ENABLED 0
  302. #else
  303. #define ELPP_LOGGING_ENABLED 1
  304. #endif
  305. #if (!defined(ELPP_DISABLE_DEBUG_LOGS) && (ELPP_LOGGING_ENABLED))
  306. # define ELPP_DEBUG_LOG 1
  307. #else
  308. # define ELPP_DEBUG_LOG 0
  309. #endif // (!defined(ELPP_DISABLE_DEBUG_LOGS) && (ELPP_LOGGING_ENABLED))
  310. #if (!defined(ELPP_DISABLE_INFO_LOGS) && (ELPP_LOGGING_ENABLED))
  311. # define ELPP_INFO_LOG 1
  312. #else
  313. # define ELPP_INFO_LOG 0
  314. #endif // (!defined(ELPP_DISABLE_INFO_LOGS) && (ELPP_LOGGING_ENABLED))
  315. #if (!defined(ELPP_DISABLE_WARNING_LOGS) && (ELPP_LOGGING_ENABLED))
  316. # define ELPP_WARNING_LOG 1
  317. #else
  318. # define ELPP_WARNING_LOG 0
  319. #endif // (!defined(ELPP_DISABLE_WARNING_LOGS) && (ELPP_LOGGING_ENABLED))
  320. #if (!defined(ELPP_DISABLE_ERROR_LOGS) && (ELPP_LOGGING_ENABLED))
  321. # define ELPP_ERROR_LOG 1
  322. #else
  323. # define ELPP_ERROR_LOG 0
  324. #endif // (!defined(ELPP_DISABLE_ERROR_LOGS) && (ELPP_LOGGING_ENABLED))
  325. #if (!defined(ELPP_DISABLE_FATAL_LOGS) && (ELPP_LOGGING_ENABLED))
  326. # define ELPP_FATAL_LOG 1
  327. #else
  328. # define ELPP_FATAL_LOG 0
  329. #endif // (!defined(ELPP_DISABLE_FATAL_LOGS) && (ELPP_LOGGING_ENABLED))
  330. #if (!defined(ELPP_DISABLE_TRACE_LOGS) && (ELPP_LOGGING_ENABLED))
  331. # define ELPP_TRACE_LOG 1
  332. #else
  333. # define ELPP_TRACE_LOG 0
  334. #endif // (!defined(ELPP_DISABLE_TRACE_LOGS) && (ELPP_LOGGING_ENABLED))
  335. #if (!defined(ELPP_DISABLE_VERBOSE_LOGS) && (ELPP_LOGGING_ENABLED))
  336. # define ELPP_VERBOSE_LOG 1
  337. #else
  338. # define ELPP_VERBOSE_LOG 0
  339. #endif // (!defined(ELPP_DISABLE_VERBOSE_LOGS) && (ELPP_LOGGING_ENABLED))
  340. #if (!(ELPP_CXX0X || ELPP_CXX11))
  341. # error "C++0x (or higher) support not detected! (Is `-std=c++11' missing?)"
  342. #endif // (!(ELPP_CXX0X || ELPP_CXX11))
  343. // Headers
  344. #if defined(ELPP_SYSLOG)
  345. # include <syslog.h>
  346. #endif // defined(ELPP_SYSLOG)
  347. #include <ctime>
  348. #include <cstring>
  349. #include <cstdlib>
  350. #include <cctype>
  351. #include <cwchar>
  352. #include <csignal>
  353. #include <cerrno>
  354. #include <cstdarg>
  355. #if defined(ELPP_UNICODE)
  356. # include <locale>
  357. # if ELPP_OS_WINDOWS
  358. # include <codecvt>
  359. # endif // ELPP_OS_WINDOWS
  360. #endif // defined(ELPP_UNICODE)
  361. #if ELPP_STACKTRACE
  362. # include <cxxabi.h>
  363. # include <execinfo.h>
  364. #endif // ELPP_STACKTRACE
  365. #if ELPP_OS_ANDROID
  366. # include <sys/system_properties.h>
  367. #endif // ELPP_OS_ANDROID
  368. #if ELPP_OS_UNIX
  369. # include <sys/stat.h>
  370. # include <sys/time.h>
  371. #elif ELPP_OS_WINDOWS
  372. # include <direct.h>
  373. # include <windows.h>
  374. # if defined(WIN32_LEAN_AND_MEAN)
  375. # if defined(ELPP_WINSOCK2)
  376. # include <winsock2.h>
  377. # else
  378. # include <winsock.h>
  379. # endif // defined(ELPP_WINSOCK2)
  380. # endif // defined(WIN32_LEAN_AND_MEAN)
  381. #endif // ELPP_OS_UNIX
  382. #include <string>
  383. #include <vector>
  384. #include <map>
  385. #include <utility>
  386. #include <functional>
  387. #include <algorithm>
  388. #include <fstream>
  389. #include <iostream>
  390. #include <sstream>
  391. #include <memory>
  392. #include <type_traits>
  393. #if ELPP_THREADING_ENABLED
  394. # if ELPP_USE_STD_THREADING
  395. # include <mutex>
  396. # include <thread>
  397. # else
  398. # if ELPP_OS_UNIX
  399. # include <pthread.h>
  400. # endif // ELPP_OS_UNIX
  401. # endif // ELPP_USE_STD_THREADING
  402. #endif // ELPP_THREADING_ENABLED
  403. #if ELPP_ASYNC_LOGGING
  404. # if defined(ELPP_NO_SLEEP_FOR)
  405. # include <unistd.h>
  406. # endif // defined(ELPP_NO_SLEEP_FOR)
  407. # include <thread>
  408. # include <queue>
  409. # include <condition_variable>
  410. #endif // ELPP_ASYNC_LOGGING
  411. #if defined(ELPP_STL_LOGGING)
  412. // For logging STL based templates
  413. # include <list>
  414. # include <queue>
  415. # include <deque>
  416. # include <set>
  417. # include <bitset>
  418. # include <stack>
  419. # if defined(ELPP_LOG_STD_ARRAY)
  420. # include <array>
  421. # endif // defined(ELPP_LOG_STD_ARRAY)
  422. # if defined(ELPP_LOG_UNORDERED_MAP)
  423. # include <unordered_map>
  424. # endif // defined(ELPP_LOG_UNORDERED_MAP)
  425. # if defined(ELPP_LOG_UNORDERED_SET)
  426. # include <unordered_set>
  427. # endif // defined(ELPP_UNORDERED_SET)
  428. #endif // defined(ELPP_STL_LOGGING)
  429. #if defined(ELPP_QT_LOGGING)
  430. // For logging Qt based classes & templates
  431. # include <QString>
  432. # include <QByteArray>
  433. # include <QVector>
  434. # include <QList>
  435. # include <QPair>
  436. # include <QMap>
  437. # include <QQueue>
  438. # include <QSet>
  439. # include <QLinkedList>
  440. # include <QHash>
  441. # include <QMultiHash>
  442. # include <QStack>
  443. #endif // defined(ELPP_QT_LOGGING)
  444. #if defined(ELPP_BOOST_LOGGING)
  445. // For logging boost based classes & templates
  446. # include <boost/container/vector.hpp>
  447. # include <boost/container/stable_vector.hpp>
  448. # include <boost/container/list.hpp>
  449. # include <boost/container/deque.hpp>
  450. # include <boost/container/map.hpp>
  451. # include <boost/container/flat_map.hpp>
  452. # include <boost/container/set.hpp>
  453. # include <boost/container/flat_set.hpp>
  454. #endif // defined(ELPP_BOOST_LOGGING)
  455. #if defined(ELPP_WXWIDGETS_LOGGING)
  456. // For logging wxWidgets based classes & templates
  457. # include <wx/vector.h>
  458. #endif // defined(ELPP_WXWIDGETS_LOGGING)
  459. #if defined(ELPP_UTC_DATETIME)
  460. # define elpptime_r gmtime_r
  461. # define elpptime_s gmtime_s
  462. # define elpptime gmtime
  463. #else
  464. # define elpptime_r localtime_r
  465. # define elpptime_s localtime_s
  466. # define elpptime localtime
  467. #endif // defined(ELPP_UTC_DATETIME)
  468. // Forward declarations
  469. namespace el {
  470. class Logger;
  471. class LogMessage;
  472. class PerformanceTrackingData;
  473. class Loggers;
  474. class Helpers;
  475. template <typename T> class Callback;
  476. class LogDispatchCallback;
  477. class PerformanceTrackingCallback;
  478. class LoggerRegistrationCallback;
  479. class LogDispatchData;
  480. namespace base {
  481. class Storage;
  482. class RegisteredLoggers;
  483. class PerformanceTracker;
  484. class MessageBuilder;
  485. class Writer;
  486. class PErrorWriter;
  487. class LogDispatcher;
  488. class DefaultLogBuilder;
  489. class DefaultLogDispatchCallback;
  490. #if ELPP_ASYNC_LOGGING
  491. class AsyncLogDispatchCallback;
  492. class AsyncDispatchWorker;
  493. #endif // ELPP_ASYNC_LOGGING
  494. class DefaultPerformanceTrackingCallback;
  495. } // namespace base
  496. } // namespace el
  497. /// @brief Easylogging++ entry namespace
  498. namespace el {
  499. /// @brief Namespace containing base/internal functionality used by Easylogging++
  500. namespace base {
  501. /// @brief Data types used by Easylogging++
  502. namespace type {
  503. #undef ELPP_LITERAL
  504. #undef ELPP_STRLEN
  505. #undef ELPP_COUT
  506. #if defined(ELPP_UNICODE)
  507. # define ELPP_LITERAL(txt) L##txt
  508. # define ELPP_STRLEN wcslen
  509. # if defined ELPP_CUSTOM_COUT
  510. # define ELPP_COUT ELPP_CUSTOM_COUT
  511. # else
  512. # define ELPP_COUT std::wcout
  513. # endif // defined ELPP_CUSTOM_COUT
  514. typedef wchar_t char_t;
  515. typedef std::wstring string_t;
  516. typedef std::wstringstream stringstream_t;
  517. typedef std::wfstream fstream_t;
  518. typedef std::wostream ostream_t;
  519. #else
  520. # define ELPP_LITERAL(txt) txt
  521. # define ELPP_STRLEN strlen
  522. # if defined ELPP_CUSTOM_COUT
  523. # define ELPP_COUT ELPP_CUSTOM_COUT
  524. # else
  525. # define ELPP_COUT std::cout
  526. # endif // defined ELPP_CUSTOM_COUT
  527. typedef char char_t;
  528. typedef std::string string_t;
  529. typedef std::stringstream stringstream_t;
  530. typedef std::fstream fstream_t;
  531. typedef std::ostream ostream_t;
  532. #endif // defined(ELPP_UNICODE)
  533. #if defined(ELPP_CUSTOM_COUT_LINE)
  534. # define ELPP_COUT_LINE(logLine) ELPP_CUSTOM_COUT_LINE(logLine)
  535. #else
  536. # define ELPP_COUT_LINE(logLine) logLine << std::flush
  537. #endif // defined(ELPP_CUSTOM_COUT_LINE)
  538. typedef unsigned int EnumType;
  539. typedef unsigned short VerboseLevel;
  540. typedef unsigned long int LineNumber;
  541. typedef std::shared_ptr<base::Storage> StoragePointer;
  542. typedef std::shared_ptr<LogDispatchCallback> LogDispatchCallbackPtr;
  543. typedef std::shared_ptr<PerformanceTrackingCallback> PerformanceTrackingCallbackPtr;
  544. typedef std::shared_ptr<LoggerRegistrationCallback> LoggerRegistrationCallbackPtr;
  545. typedef std::unique_ptr<el::base::PerformanceTracker> PerformanceTrackerPtr;
  546. } // namespace type
  547. /// @brief Internal helper class that prevent copy constructor for class
  548. ///
  549. /// @detail When using this class simply inherit it privately
  550. class NoCopy {
  551. protected:
  552. NoCopy(void) {}
  553. private:
  554. NoCopy(const NoCopy&);
  555. NoCopy& operator=(const NoCopy&);
  556. };
  557. /// @brief Internal helper class that makes all default constructors private.
  558. ///
  559. /// @detail This prevents initializing class making it static unless an explicit constructor is declared.
  560. /// When using this class simply inherit it privately
  561. class StaticClass {
  562. private:
  563. StaticClass(void);
  564. StaticClass(const StaticClass&);
  565. StaticClass& operator=(const StaticClass&);
  566. };
  567. } // namespace base
  568. /// @brief Represents enumeration for severity level used to determine level of logging
  569. ///
  570. /// @detail With Easylogging++, developers may disable or enable any level regardless of
  571. /// what the severity is. Or they can choose to log using hierarchical logging flag
  572. enum class Level : base::type::EnumType {
  573. /// @brief Generic level that represents all the levels. Useful when setting global configuration for all levels
  574. Global = 1,
  575. /// @brief Information that can be useful to back-trace certain events - mostly useful than debug logs.
  576. Trace = 2,
  577. /// @brief Informational events most useful for developers to debug application
  578. Debug = 4,
  579. /// @brief Severe error information that will presumably abort application
  580. Fatal = 8,
  581. /// @brief Information representing errors in application but application will keep running
  582. Error = 16,
  583. /// @brief Useful when application has potentially harmful situtaions
  584. Warning = 32,
  585. /// @brief Information that can be highly useful and vary with verbose logging level.
  586. Verbose = 64,
  587. /// @brief Mainly useful to represent current progress of application
  588. Info = 128,
  589. /// @brief Represents unknown level
  590. Unknown = 1010
  591. };
  592. /// @brief Static class that contains helper functions for el::Level
  593. class LevelHelper : base::StaticClass {
  594. public:
  595. /// @brief Represents minimum valid level. Useful when iterating through enum.
  596. static const base::type::EnumType kMinValid = static_cast<base::type::EnumType>(Level::Trace);
  597. /// @brief Represents maximum valid level. This is used internally and you should not need it.
  598. static const base::type::EnumType kMaxValid = static_cast<base::type::EnumType>(Level::Info);
  599. /// @brief Casts level to int, useful for iterating through enum.
  600. static base::type::EnumType castToInt(Level level) {
  601. return static_cast<base::type::EnumType>(level);
  602. }
  603. /// @brief Casts int(ushort) to level, useful for iterating through enum.
  604. static Level castFromInt(base::type::EnumType l) {
  605. return static_cast<Level>(l);
  606. }
  607. /// @brief Converts level to associated const char*
  608. /// @return Upper case string based level.
  609. static const char* convertToString(Level level);
  610. /// @brief Converts from levelStr to Level
  611. /// @param levelStr Upper case string based level.
  612. /// Lower case is also valid but providing upper case is recommended.
  613. static Level convertFromString(const char* levelStr);
  614. /// @brief Applies specified function to each level starting from startIndex
  615. /// @param startIndex initial value to start the iteration from. This is passed as pointer and
  616. /// is left-shifted so this can be used inside function (fn) to represent current level.
  617. /// @param fn function to apply with each level. This bool represent whether or not to stop iterating through levels.
  618. static void forEachLevel(base::type::EnumType* startIndex, const std::function<bool(void)>& fn);
  619. };
  620. /// @brief Represents enumeration of ConfigurationType used to configure or access certain aspect
  621. /// of logging
  622. enum class ConfigurationType : base::type::EnumType {
  623. /// @brief Determines whether or not corresponding level and logger of logging is enabled
  624. /// You may disable all logs by using el::Level::Global
  625. Enabled = 1,
  626. /// @brief Whether or not to write corresponding log to log file
  627. ToFile = 2,
  628. /// @brief Whether or not to write corresponding level and logger log to standard output.
  629. /// By standard output meaning termnal, command prompt etc
  630. ToStandardOutput = 4,
  631. /// @brief Determines format of logging corresponding level and logger.
  632. Format = 8,
  633. /// @brief Determines log file (full path) to write logs to for correponding level and logger
  634. Filename = 16,
  635. /// @brief Specifies precision of the subsecond part. It should be within range (1-6).
  636. SubsecondPrecision = 32,
  637. /// @brief Alias of SubsecondPrecision (for backward compatibility)
  638. MillisecondsWidth = SubsecondPrecision,
  639. /// @brief Determines whether or not performance tracking is enabled.
  640. ///
  641. /// @detail This does not depend on logger or level. Performance tracking always uses 'performance' logger
  642. PerformanceTracking = 64,
  643. /// @brief Specifies log file max size.
  644. ///
  645. /// @detail If file size of corresponding log file (for corresponding level) is >= specified size, log file will
  646. /// be truncated and re-initiated.
  647. MaxLogFileSize = 128,
  648. /// @brief Specifies number of log entries to hold until we flush pending log data
  649. LogFlushThreshold = 256,
  650. /// @brief Represents unknown configuration
  651. Unknown = 1010
  652. };
  653. /// @brief Static class that contains helper functions for el::ConfigurationType
  654. class ConfigurationTypeHelper : base::StaticClass {
  655. public:
  656. /// @brief Represents minimum valid configuration type. Useful when iterating through enum.
  657. static const base::type::EnumType kMinValid = static_cast<base::type::EnumType>(ConfigurationType::Enabled);
  658. /// @brief Represents maximum valid configuration type. This is used internally and you should not need it.
  659. static const base::type::EnumType kMaxValid = static_cast<base::type::EnumType>(ConfigurationType::MaxLogFileSize);
  660. /// @brief Casts configuration type to int, useful for iterating through enum.
  661. static base::type::EnumType castToInt(ConfigurationType configurationType) {
  662. return static_cast<base::type::EnumType>(configurationType);
  663. }
  664. /// @brief Casts int(ushort) to configurationt type, useful for iterating through enum.
  665. static ConfigurationType castFromInt(base::type::EnumType c) {
  666. return static_cast<ConfigurationType>(c);
  667. }
  668. /// @brief Converts configuration type to associated const char*
  669. /// @returns Upper case string based configuration type.
  670. static const char* convertToString(ConfigurationType configurationType);
  671. /// @brief Converts from configStr to ConfigurationType
  672. /// @param configStr Upper case string based configuration type.
  673. /// Lower case is also valid but providing upper case is recommended.
  674. static ConfigurationType convertFromString(const char* configStr);
  675. /// @brief Applies specified function to each configuration type starting from startIndex
  676. /// @param startIndex initial value to start the iteration from. This is passed by pointer and is left-shifted
  677. /// so this can be used inside function (fn) to represent current configuration type.
  678. /// @param fn function to apply with each configuration type.
  679. /// This bool represent whether or not to stop iterating through configurations.
  680. static inline void forEachConfigType(base::type::EnumType* startIndex, const std::function<bool(void)>& fn);
  681. };
  682. /// @brief Flags used while writing logs. This flags are set by user
  683. enum class LoggingFlag : base::type::EnumType {
  684. /// @brief Makes sure we have new line for each container log entry
  685. NewLineForContainer = 1,
  686. /// @brief Makes sure if -vmodule is used and does not specifies a module, then verbose
  687. /// logging is allowed via that module.
  688. AllowVerboseIfModuleNotSpecified = 2,
  689. /// @brief When handling crashes by default, detailed crash reason will be logged as well
  690. LogDetailedCrashReason = 4,
  691. /// @brief Allows to disable application abortion when logged using FATAL level
  692. DisableApplicationAbortOnFatalLog = 8,
  693. /// @brief Flushes log with every log-entry (performance sensative) - Disabled by default
  694. ImmediateFlush = 16,
  695. /// @brief Enables strict file rolling
  696. StrictLogFileSizeCheck = 32,
  697. /// @brief Make terminal output colorful for supported terminals
  698. ColoredTerminalOutput = 64,
  699. /// @brief Supports use of multiple logging in same macro, e.g, CLOG(INFO, "default", "network")
  700. MultiLoggerSupport = 128,
  701. /// @brief Disables comparing performance tracker's checkpoints
  702. DisablePerformanceTrackingCheckpointComparison = 256,
  703. /// @brief Disable VModules
  704. DisableVModules = 512,
  705. /// @brief Disable VModules extensions
  706. DisableVModulesExtensions = 1024,
  707. /// @brief Enables hierarchical logging
  708. HierarchicalLogging = 2048,
  709. /// @brief Creates logger automatically when not available
  710. CreateLoggerAutomatically = 4096,
  711. /// @brief Adds spaces b/w logs that separated by left-shift operator
  712. AutoSpacing = 8192,
  713. /// @brief Preserves time format and does not convert it to sec, hour etc (performance tracking only)
  714. FixedTimeFormat = 16384
  715. };
  716. namespace base {
  717. /// @brief Namespace containing constants used internally.
  718. namespace consts {
  719. #if defined(__GNUC__) && !defined(__clang__)
  720. #pragma GCC diagnostic push
  721. #pragma GCC diagnostic ignored "-Wunused-variable"
  722. #endif
  723. // Level log values - These are values that are replaced in place of %level format specifier
  724. // Extra spaces after format specifiers are only for readability purposes in log files
  725. static const base::type::char_t* kInfoLevelLogValue = ELPP_LITERAL("INFO");
  726. static const base::type::char_t* kDebugLevelLogValue = ELPP_LITERAL("DEBUG");
  727. static const base::type::char_t* kWarningLevelLogValue = ELPP_LITERAL("WARNING");
  728. static const base::type::char_t* kErrorLevelLogValue = ELPP_LITERAL("ERROR");
  729. static const base::type::char_t* kFatalLevelLogValue = ELPP_LITERAL("FATAL");
  730. static const base::type::char_t* kVerboseLevelLogValue =
  731. ELPP_LITERAL("VERBOSE"); // will become VERBOSE-x where x = verbose level
  732. static const base::type::char_t* kTraceLevelLogValue = ELPP_LITERAL("TRACE");
  733. static const base::type::char_t* kInfoLevelShortLogValue = ELPP_LITERAL("I");
  734. static const base::type::char_t* kDebugLevelShortLogValue = ELPP_LITERAL("D");
  735. static const base::type::char_t* kWarningLevelShortLogValue = ELPP_LITERAL("W");
  736. static const base::type::char_t* kErrorLevelShortLogValue = ELPP_LITERAL("E");
  737. static const base::type::char_t* kFatalLevelShortLogValue = ELPP_LITERAL("F");
  738. static const base::type::char_t* kVerboseLevelShortLogValue = ELPP_LITERAL("V");
  739. static const base::type::char_t* kTraceLevelShortLogValue = ELPP_LITERAL("T");
  740. // Format specifiers - These are used to define log format
  741. static const base::type::char_t* kAppNameFormatSpecifier = ELPP_LITERAL("%app");
  742. static const base::type::char_t* kLoggerIdFormatSpecifier = ELPP_LITERAL("%logger");
  743. static const base::type::char_t* kThreadIdFormatSpecifier = ELPP_LITERAL("%thread");
  744. static const base::type::char_t* kSeverityLevelFormatSpecifier = ELPP_LITERAL("%level");
  745. static const base::type::char_t* kSeverityLevelShortFormatSpecifier = ELPP_LITERAL("%levshort");
  746. static const base::type::char_t* kDateTimeFormatSpecifier = ELPP_LITERAL("%datetime");
  747. static const base::type::char_t* kLogFileFormatSpecifier = ELPP_LITERAL("%file");
  748. static const base::type::char_t* kLogFileBaseFormatSpecifier = ELPP_LITERAL("%fbase");
  749. static const base::type::char_t* kLogLineFormatSpecifier = ELPP_LITERAL("%line");
  750. static const base::type::char_t* kLogLocationFormatSpecifier = ELPP_LITERAL("%loc");
  751. static const base::type::char_t* kLogFunctionFormatSpecifier = ELPP_LITERAL("%func");
  752. static const base::type::char_t* kCurrentUserFormatSpecifier = ELPP_LITERAL("%user");
  753. static const base::type::char_t* kCurrentHostFormatSpecifier = ELPP_LITERAL("%host");
  754. static const base::type::char_t* kMessageFormatSpecifier = ELPP_LITERAL("%msg");
  755. static const base::type::char_t* kVerboseLevelFormatSpecifier = ELPP_LITERAL("%vlevel");
  756. static const char* kDateTimeFormatSpecifierForFilename = "%datetime";
  757. // Date/time
  758. static const char* kDays[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  759. static const char* kDaysAbbrev[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  760. static const char* kMonths[12] = { "January", "February", "March", "Apri", "May", "June", "July", "August",
  761. "September", "October", "November", "December"
  762. };
  763. static const char* kMonthsAbbrev[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  764. static const char* kDefaultDateTimeFormat = "%Y-%M-%d %H:%m:%s,%g";
  765. static const char* kDefaultDateTimeFormatInFilename = "%Y-%M-%d_%H-%m";
  766. static const int kYearBase = 1900;
  767. static const char* kAm = "AM";
  768. static const char* kPm = "PM";
  769. // Miscellaneous constants
  770. #ifdef ELPP_DEFAULT_LOGGER
  771. static const char* kDefaultLoggerId = ELPP_DEFAULT_LOGGER;
  772. #else
  773. static const char* kDefaultLoggerId = "default";
  774. #endif
  775. #ifdef ELPP_DEFAULT_PERFORMANCE_LOGGER
  776. static const char* kPerformanceLoggerId = ELPP_DEFAULT_PERFORMANCE_LOGGER;
  777. #else
  778. static const char* kPerformanceLoggerId = "performance";
  779. #endif
  780. #if defined(ELPP_SYSLOG)
  781. static const char* kSysLogLoggerId = "syslog";
  782. #endif // defined(ELPP_SYSLOG)
  783. static const char* kNullPointer = "nullptr";
  784. static const char kFormatSpecifierChar = '%';
  785. #if ELPP_VARIADIC_TEMPLATES_SUPPORTED
  786. static const char kFormatSpecifierCharValue = 'v';
  787. #endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED
  788. static const unsigned int kMaxLogPerContainer = 100;
  789. static const unsigned int kMaxLogPerCounter = 100000;
  790. static const unsigned int kDefaultSubsecondPrecision = 3;
  791. static const base::type::VerboseLevel kMaxVerboseLevel = 9;
  792. static const char* kUnknownUser = "user";
  793. static const char* kUnknownHost = "unknown-host";
  794. #if defined(ELPP_DEFAULT_LOG_FILE)
  795. static const char* kDefaultLogFile = ELPP_DEFAULT_LOG_FILE;
  796. #else
  797. # if ELPP_OS_UNIX
  798. # if ELPP_OS_ANDROID
  799. static const char* kDefaultLogFile = "logs/myeasylog.log";
  800. # else
  801. static const char* kDefaultLogFile = "logs/myeasylog.log";
  802. # endif // ELPP_OS_ANDROID
  803. # elif ELPP_OS_WINDOWS
  804. static const char* kDefaultLogFile = "logs\\myeasylog.log";
  805. # endif // ELPP_OS_UNIX
  806. #endif // defined(ELPP_DEFAULT_LOG_FILE)
  807. #if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)
  808. static const char* kDefaultLogFileParam = "--default-log-file";
  809. #endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)
  810. #if defined(ELPP_LOGGING_FLAGS_FROM_ARG)
  811. static const char* kLoggingFlagsParam = "--logging-flags";
  812. #endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG)
  813. #if ELPP_OS_WINDOWS
  814. static const char* kFilePathSeperator = "\\";
  815. #else
  816. static const char* kFilePathSeperator = "/";
  817. #endif // ELPP_OS_WINDOWS
  818. static const char* kValidLoggerIdSymbols =
  819. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._";
  820. static const char* kConfigurationComment = "##";
  821. static const char* kConfigurationLevel = "*";
  822. static const char* kConfigurationLoggerId = "--";
  823. static const std::size_t kSourceFilenameMaxLength = 100;
  824. static const std::size_t kSourceLineMaxLength = 10;
  825. static const Level kPerformanceTrackerDefaultLevel = Level::Info;
  826. const struct {
  827. double value;
  828. const base::type::char_t* unit;
  829. } kTimeFormats[] = {
  830. { 1000.0f, ELPP_LITERAL("us") },
  831. { 1000.0f, ELPP_LITERAL("ms") },
  832. { 60.0f, ELPP_LITERAL("seconds") },
  833. { 60.0f, ELPP_LITERAL("minutes") },
  834. { 24.0f, ELPP_LITERAL("hours") },
  835. { 7.0f, ELPP_LITERAL("days") }
  836. };
  837. static const int kTimeFormatsCount = sizeof(kTimeFormats) / sizeof(kTimeFormats[0]);
  838. const struct {
  839. int numb;
  840. const char* name;
  841. const char* brief;
  842. const char* detail;
  843. } kCrashSignals[] = {
  844. // NOTE: Do not re-order, if you do please check CrashHandler(bool) constructor and CrashHandler::setHandler(..)
  845. {
  846. SIGABRT, "SIGABRT", "Abnormal termination",
  847. "Program was abnormally terminated."
  848. },
  849. {
  850. SIGFPE, "SIGFPE", "Erroneous arithmetic operation",
  851. "Arithemetic operation issue such as division by zero or operation resulting in overflow."
  852. },
  853. {
  854. SIGILL, "SIGILL", "Illegal instruction",
  855. "Generally due to a corruption in the code or to an attempt to execute data."
  856. },
  857. {
  858. SIGSEGV, "SIGSEGV", "Invalid access to memory",
  859. "Program is trying to read an invalid (unallocated, deleted or corrupted) or inaccessible memory."
  860. },
  861. {
  862. SIGINT, "SIGINT", "Interactive attention signal",
  863. "Interruption generated (generally) by user or operating system."
  864. },
  865. };
  866. static const int kCrashSignalsCount = sizeof(kCrashSignals) / sizeof(kCrashSignals[0]);
  867. #if defined(__GNUC__) && !defined(__clang__)
  868. #pragma GCC diagnostic pop
  869. #endif
  870. } // namespace consts
  871. } // namespace base
  872. typedef std::function<void(const char*, std::size_t)> PreRollOutCallback;
  873. namespace base {
  874. static inline void defaultPreRollOutCallback(const char*, std::size_t) {}
  875. /// @brief Enum to represent timestamp unit
  876. enum class TimestampUnit : base::type::EnumType {
  877. Microsecond = 0, Millisecond = 1, Second = 2, Minute = 3, Hour = 4, Day = 5
  878. };
  879. /// @brief Format flags used to determine specifiers that are active for performance improvements.
  880. enum class FormatFlags : base::type::EnumType {
  881. DateTime = 1 << 1,
  882. LoggerId = 1 << 2,
  883. File = 1 << 3,
  884. Line = 1 << 4,
  885. Location = 1 << 5,
  886. Function = 1 << 6,
  887. User = 1 << 7,
  888. Host = 1 << 8,
  889. LogMessage = 1 << 9,
  890. VerboseLevel = 1 << 10,
  891. AppName = 1 << 11,
  892. ThreadId = 1 << 12,
  893. Level = 1 << 13,
  894. FileBase = 1 << 14,
  895. LevelShort = 1 << 15
  896. };
  897. /// @brief A subsecond precision class containing actual width and offset of the subsecond part
  898. class SubsecondPrecision {
  899. public:
  900. SubsecondPrecision(void) {
  901. init(base::consts::kDefaultSubsecondPrecision);
  902. }
  903. explicit SubsecondPrecision(int width) {
  904. init(width);
  905. }
  906. bool operator==(const SubsecondPrecision& ssPrec) {
  907. return m_width == ssPrec.m_width && m_offset == ssPrec.m_offset;
  908. }
  909. int m_width;
  910. unsigned int m_offset;
  911. private:
  912. void init(int width);
  913. };
  914. /// @brief Type alias of SubsecondPrecision
  915. typedef SubsecondPrecision MillisecondsWidth;
  916. /// @brief Namespace containing utility functions/static classes used internally
  917. namespace utils {
  918. /// @brief Deletes memory safely and points to null
  919. template <typename T>
  920. static
  921. typename std::enable_if<std::is_pointer<T*>::value, void>::type
  922. safeDelete(T*& pointer) {
  923. if (pointer == nullptr)
  924. return;
  925. delete pointer;
  926. pointer = nullptr;
  927. }
  928. /// @brief Bitwise operations for C++11 strong enum class. This casts e into Flag_T and returns value after bitwise operation
  929. /// Use these function as <pre>flag = bitwise::Or<MyEnum>(MyEnum::val1, flag);</pre>
  930. namespace bitwise {
  931. template <typename Enum>
  932. static inline base::type::EnumType And(Enum e, base::type::EnumType flag) {
  933. return static_cast<base::type::EnumType>(flag) & static_cast<base::type::EnumType>(e);
  934. }
  935. template <typename Enum>
  936. static inline base::type::EnumType Not(Enum e, base::type::EnumType flag) {
  937. return static_cast<base::type::EnumType>(flag) & ~(static_cast<base::type::EnumType>(e));
  938. }
  939. template <typename Enum>
  940. static inline base::type::EnumType Or(Enum e, base::type::EnumType flag) {
  941. return static_cast<base::type::EnumType>(flag) | static_cast<base::type::EnumType>(e);
  942. }
  943. } // namespace bitwise
  944. template <typename Enum>
  945. static inline void addFlag(Enum e, base::type::EnumType* flag) {
  946. *flag = base::utils::bitwise::Or<Enum>(e, *flag);
  947. }
  948. template <typename Enum>
  949. static inline void removeFlag(Enum e, base::type::EnumType* flag) {
  950. *flag = base::utils::bitwise::Not<Enum>(e, *flag);
  951. }
  952. template <typename Enum>
  953. static inline bool hasFlag(Enum e, base::type::EnumType flag) {
  954. return base::utils::bitwise::And<Enum>(e, flag) > 0x0;
  955. }
  956. } // namespace utils
  957. namespace threading {
  958. #if ELPP_THREADING_ENABLED
  959. # if !ELPP_USE_STD_THREADING
  960. namespace internal {
  961. /// @brief A mutex wrapper for compiler that dont yet support std::recursive_mutex
  962. class Mutex : base::NoCopy {
  963. public:
  964. Mutex(void) {
  965. # if ELPP_OS_UNIX
  966. pthread_mutexattr_t attr;
  967. pthread_mutexattr_init(&attr);
  968. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  969. pthread_mutex_init(&m_underlyingMutex, &attr);
  970. pthread_mutexattr_destroy(&attr);
  971. # elif ELPP_OS_WINDOWS
  972. InitializeCriticalSection(&m_underlyingMutex);
  973. # endif // ELPP_OS_UNIX
  974. }
  975. virtual ~Mutex(void) {
  976. # if ELPP_OS_UNIX
  977. pthread_mutex_destroy(&m_underlyingMutex);
  978. # elif ELPP_OS_WINDOWS
  979. DeleteCriticalSection(&m_underlyingMutex);
  980. # endif // ELPP_OS_UNIX
  981. }
  982. inline void lock(void) {
  983. # if ELPP_OS_UNIX
  984. pthread_mutex_lock(&m_underlyingMutex);
  985. # elif ELPP_OS_WINDOWS
  986. EnterCriticalSection(&m_underlyingMutex);
  987. # endif // ELPP_OS_UNIX
  988. }
  989. inline bool try_lock(void) {
  990. # if ELPP_OS_UNIX
  991. return (pthread_mutex_trylock(&m_underlyingMutex) == 0);
  992. # elif ELPP_OS_WINDOWS
  993. return TryEnterCriticalSection(&m_underlyingMutex);
  994. # endif // ELPP_OS_UNIX
  995. }
  996. inline void unlock(void) {
  997. # if ELPP_OS_UNIX
  998. pthread_mutex_unlock(&m_underlyingMutex);
  999. # elif ELPP_OS_WINDOWS
  1000. LeaveCriticalSection(&m_underlyingMutex);
  1001. # endif // ELPP_OS_UNIX
  1002. }
  1003. private:
  1004. # if ELPP_OS_UNIX
  1005. pthread_mutex_t m_underlyingMutex;
  1006. # elif ELPP_OS_WINDOWS
  1007. CRITICAL_SECTION m_underlyingMutex;
  1008. # endif // ELPP_OS_UNIX
  1009. };
  1010. /// @brief Scoped lock for compiler that dont yet support std::lock_guard
  1011. template <typename M>
  1012. class ScopedLock : base::NoCopy {
  1013. public:
  1014. explicit ScopedLock(M& mutex) {
  1015. m_mutex = &mutex;
  1016. m_mutex->lock();
  1017. }
  1018. virtual ~ScopedLock(void) {
  1019. m_mutex->unlock();
  1020. }
  1021. private:
  1022. M* m_mutex;
  1023. ScopedLock(void);
  1024. };
  1025. } // namespace internal
  1026. typedef base::threading::internal::Mutex Mutex;
  1027. typedef base::threading::internal::ScopedLock<base::threading::Mutex> ScopedLock;
  1028. # else
  1029. typedef std::recursive_mutex Mutex;
  1030. typedef std::lock_guard<base::threading::Mutex> ScopedLock;
  1031. # endif // !ELPP_USE_STD_THREADING
  1032. #else
  1033. namespace internal {
  1034. /// @brief Mutex wrapper used when multi-threading is disabled.
  1035. class NoMutex : base::NoCopy {
  1036. public:
  1037. NoMutex(void) {}
  1038. inline void lock(void) {}
  1039. inline bool try_lock(void) {
  1040. return true;
  1041. }
  1042. inline void unlock(void) {}
  1043. };
  1044. /// @brief Lock guard wrapper used when multi-threading is disabled.
  1045. template <typename Mutex>
  1046. class NoScopedLock : base::NoCopy {
  1047. public:
  1048. explicit NoScopedLock(Mutex&) {
  1049. }
  1050. virtual ~NoScopedLock(void) {
  1051. }
  1052. private:
  1053. NoScopedLock(void);
  1054. };
  1055. } // namespace internal
  1056. typedef base::threading::internal::NoMutex Mutex;
  1057. typedef base::threading::internal::NoScopedLock<base::threading::Mutex> ScopedLock;
  1058. #endif // ELPP_THREADING_ENABLED
  1059. /// @brief Base of thread safe class, this class is inheritable-only
  1060. class ThreadSafe {
  1061. public:
  1062. virtual inline void acquireLock(void) ELPP_FINAL { m_mutex.lock(); }
  1063. virtual inline void releaseLock(void) ELPP_FINAL { m_mutex.unlock(); }
  1064. virtual inline base::threading::Mutex& lock(void) ELPP_FINAL { return m_mutex; }
  1065. protected:
  1066. ThreadSafe(void) {}
  1067. virtual ~ThreadSafe(void) {}
  1068. private:
  1069. base::threading::Mutex m_mutex;
  1070. };
  1071. #if ELPP_THREADING_ENABLED
  1072. # if !ELPP_USE_STD_THREADING
  1073. /// @brief Gets ID of currently running threading in windows systems. On unix, nothing is returned.
  1074. static std::string getCurrentThreadId(void) {
  1075. std::stringstream ss;
  1076. # if (ELPP_OS_WINDOWS)
  1077. ss << GetCurrentThreadId();
  1078. # endif // (ELPP_OS_WINDOWS)
  1079. return ss.str();
  1080. }
  1081. # else
  1082. /// @brief Gets ID of currently running threading using std::this_thread::get_id()
  1083. static std::string getCurrentThreadId(void) {
  1084. std::stringstream ss;
  1085. ss << std::this_thread::get_id();
  1086. return ss.str();
  1087. }
  1088. # endif // !ELPP_USE_STD_THREADING
  1089. #else
  1090. static inline std::string getCurrentThreadId(void) {
  1091. return std::string();
  1092. }
  1093. #endif // ELPP_THREADING_ENABLED
  1094. } // namespace threading
  1095. namespace utils {
  1096. class File : base::StaticClass {
  1097. public:
  1098. /// @brief Creates new out file stream for specified filename.
  1099. /// @return Pointer to newly created fstream or nullptr
  1100. static base::type::fstream_t* newFileStream(const std::string& filename);
  1101. /// @brief Gets size of file provided in stream
  1102. static std::size_t getSizeOfFile(base::type::fstream_t* fs);
  1103. /// @brief Determines whether or not provided path exist in current file system
  1104. static bool pathExists(const char* path, bool considerFile = false);
  1105. /// @brief Creates specified path on file system
  1106. /// @param path Path to create.
  1107. static bool createPath(const std::string& path);
  1108. /// @brief Extracts path of filename with leading slash
  1109. static std::string extractPathFromFilename(const std::string& fullPath,
  1110. const char* seperator = base::consts::kFilePathSeperator);
  1111. /// @brief builds stripped filename and puts it in buff
  1112. static void buildStrippedFilename(const char* filename, char buff[],
  1113. std::size_t limit = base::consts::kSourceFilenameMaxLength);
  1114. /// @brief builds base filename and puts it in buff
  1115. static void buildBaseFilename(const std::string& fullPath, char buff[],
  1116. std::size_t limit = base::consts::kSourceFilenameMaxLength,
  1117. const char* seperator = base::consts::kFilePathSeperator);
  1118. };
  1119. /// @brief String utilities helper class used internally. You should not use it.
  1120. class Str : base::StaticClass {
  1121. public:
  1122. /// @brief Checks if character is digit. Dont use libc implementation of it to prevent locale issues.
  1123. static inline bool isDigit(char c) {
  1124. return c >= '0' && c <= '9';
  1125. }
  1126. /// @brief Matches wildcards, '*' and '?' only supported.
  1127. static bool wildCardMatch(const char* str, const char* pattern);
  1128. static std::string& ltrim(std::string& str);
  1129. static std::string& rtrim(std::string& str);
  1130. static std::string& trim(std::string& str);
  1131. /// @brief Determines whether or not str starts with specified string
  1132. /// @param str String to check
  1133. /// @param start String to check against
  1134. /// @return Returns true if starts with specified string, false otherwise
  1135. static bool startsWith(const std::string& str, const std::string& start);
  1136. /// @brief Determines whether or not str ends with specified string
  1137. /// @param str String to check
  1138. /// @param end String to check against
  1139. /// @return Returns true if ends with specified string, false otherwise
  1140. static bool endsWith(const std::string& str, const std::string& end);
  1141. /// @brief Replaces all instances of replaceWhat with 'replaceWith'. Original variable is changed for performance.
  1142. /// @param [in,out] str String to replace from
  1143. /// @param replaceWhat Character to replace
  1144. /// @param replaceWith Character to replace with
  1145. /// @return Modified version of str
  1146. static std::string& replaceAll(std::string& str, char replaceWhat, char replaceWith);
  1147. /// @brief Replaces all instances of 'replaceWhat' with 'replaceWith'. (String version) Replaces in place
  1148. /// @param str String to replace from
  1149. /// @param replaceWhat Character to replace
  1150. /// @param replaceWith Character to replace with
  1151. /// @return Modified (original) str
  1152. static std::string& replaceAll(std::string& str, const std::string& replaceWhat,
  1153. const std::string& replaceWith);
  1154. static void replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
  1155. const base::type::string_t& replaceWith);
  1156. #if defined(ELPP_UNICODE)
  1157. static void replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
  1158. const std::string& replaceWith);
  1159. #endif // defined(ELPP_UNICODE)
  1160. /// @brief Converts string to uppercase
  1161. /// @param str String to convert
  1162. /// @return Uppercase string
  1163. static std::string& toUpper(std::string& str);
  1164. /// @brief Compares cstring equality - uses strcmp
  1165. static bool cStringEq(const char* s1, const char* s2);
  1166. /// @brief Compares cstring equality (case-insensitive) - uses toupper(char)
  1167. /// Dont use strcasecmp because of CRT (VC++)
  1168. static bool cStringCaseEq(const char* s1, const char* s2);
  1169. /// @brief Returns true if c exist in str
  1170. static bool contains(const char* str, char c);
  1171. static char* convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded = true);
  1172. static char* addToBuff(const char* str, char* buf, const char* bufLim);
  1173. static char* clearBuff(char buff[], std::size_t lim);
  1174. /// @brief Converst wchar* to char*
  1175. /// NOTE: Need to free return value after use!
  1176. static char* wcharPtrToCharPtr(const wchar_t* line);
  1177. };
  1178. /// @brief Operating System helper static class used internally. You should not use it.
  1179. class OS : base::StaticClass {
  1180. public:
  1181. #if ELPP_OS_WINDOWS
  1182. /// @brief Gets environment variables for Windows based OS.
  1183. /// We are not using <code>getenv(const char*)</code> because of CRT deprecation
  1184. /// @param varname Variable name to get environment variable value for
  1185. /// @return If variable exist the value of it otherwise nullptr
  1186. static const char* getWindowsEnvironmentVariable(const char* varname);
  1187. #endif // ELPP_OS_WINDOWS
  1188. #if ELPP_OS_ANDROID
  1189. /// @brief Reads android property value
  1190. static std::string getProperty(const char* prop);
  1191. /// @brief Reads android device name
  1192. static std::string getDeviceName(void);
  1193. #endif // ELPP_OS_ANDROID
  1194. /// @brief Runs command on terminal and returns the output.
  1195. ///
  1196. /// @detail This is applicable only on unix based systems, for all other OS, an empty string is returned.
  1197. /// @param command Bash command
  1198. /// @return Result of bash output or empty string if no result found.
  1199. static const std::string getBashOutput(const char* command);
  1200. /// @brief Gets environment variable. This is cross-platform and CRT safe (for VC++)
  1201. /// @param variableName Environment variable name
  1202. /// @param defaultVal If no environment variable or value found the value to return by default
  1203. /// @param alternativeBashCommand If environment variable not found what would be alternative bash command
  1204. /// in order to look for value user is looking for. E.g, for 'user' alternative command will 'whoami'
  1205. static std::string getEnvironmentVariable(const char* variableName, const char* defaultVal,
  1206. const char* alternativeBashCommand = nullptr);
  1207. /// @brief Gets current username.
  1208. static std::string currentUser(void);
  1209. /// @brief Gets current host name or computer name.
  1210. ///
  1211. /// @detail For android systems this is device name with its manufacturer and model seperated by hyphen
  1212. static std::string currentHost(void);
  1213. /// @brief Whether or not terminal supports colors
  1214. static bool termSupportsColor(void);
  1215. };
  1216. /// @brief Contains utilities for cross-platform date/time. This class make use of el::base::utils::Str
  1217. class DateTime : base::StaticClass {
  1218. public:
  1219. /// @brief Cross platform gettimeofday for Windows and unix platform. This can be used to determine current microsecond.
  1220. ///
  1221. /// @detail For unix system it uses gettimeofday(timeval*, timezone*) and for Windows, a seperate implementation is provided
  1222. /// @param [in,out] tv Pointer that gets updated
  1223. static void gettimeofday(struct timeval* tv);
  1224. /// @brief Gets current date and time with a subsecond part.
  1225. /// @param format User provided date/time format
  1226. /// @param ssPrec A pointer to base::SubsecondPrecision from configuration (non-null)
  1227. /// @returns string based date time in specified format.
  1228. static std::string getDateTime(const char* format, const base::SubsecondPrecision* ssPrec);
  1229. /// @brief Converts timeval (struct from ctime) to string using specified format and subsecond precision
  1230. static std::string timevalToString(struct timeval tval, const char* format,
  1231. const el::base::SubsecondPrecision* ssPrec);
  1232. /// @brief Formats time to get unit accordingly, units like second if > 1000 or minutes if > 60000 etc
  1233. static base::type::string_t formatTime(unsigned long long time, base::TimestampUnit timestampUnit);
  1234. /// @brief Gets time difference in milli/micro second depending on timestampUnit
  1235. static unsigned long long getTimeDifference(const struct timeval& endTime, const struct timeval& startTime,
  1236. base::TimestampUnit timestampUnit);
  1237. private:
  1238. static struct ::tm* buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo);
  1239. static char* parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo,
  1240. std::size_t msec, const base::SubsecondPrecision* ssPrec);
  1241. };
  1242. /// @brief Command line arguments for application if specified using el::Helpers::setArgs(..) or START_EASYLOGGINGPP(..)
  1243. class CommandLineArgs {
  1244. public:
  1245. CommandLineArgs(void) {
  1246. setArgs(0, static_cast<char**>(nullptr));
  1247. }
  1248. CommandLineArgs(int argc, const char** argv) {
  1249. setArgs(argc, argv);
  1250. }
  1251. CommandLineArgs(int argc, char** argv) {
  1252. setArgs(argc, argv);
  1253. }
  1254. virtual ~CommandLineArgs(void) {}
  1255. /// @brief Sets arguments and parses them
  1256. inline void setArgs(int argc, const char** argv) {
  1257. setArgs(argc, const_cast<char**>(argv));
  1258. }
  1259. /// @brief Sets arguments and parses them
  1260. void setArgs(int argc, char** argv);
  1261. /// @brief Returns true if arguments contain paramKey with a value (seperated by '=')
  1262. bool hasParamWithValue(const char* paramKey) const;
  1263. /// @brief Returns value of arguments
  1264. /// @see hasParamWithValue(const char*)
  1265. const char* getParamValue(const char* paramKey) const;
  1266. /// @brief Return true if arguments has a param (not having a value) i,e without '='
  1267. bool hasParam(const char* paramKey) const;
  1268. /// @brief Returns true if no params available. This exclude argv[0]
  1269. bool empty(void) const;
  1270. /// @brief Returns total number of arguments. This exclude argv[0]
  1271. std::size_t size(void) const;
  1272. friend base::type::ostream_t& operator<<(base::type::ostream_t& os, const CommandLineArgs& c);
  1273. private:
  1274. int m_argc;
  1275. char** m_argv;
  1276. std::map<std::string, std::string> m_paramsWithValue;
  1277. std::vector<std::string> m_params;
  1278. };
  1279. /// @brief Abstract registry (aka repository) that provides basic interface for pointer repository specified by T_Ptr type.
  1280. ///
  1281. /// @detail Most of the functions are virtual final methods but anything implementing this abstract class should implement
  1282. /// unregisterAll() and deepCopy(const AbstractRegistry<T_Ptr, Container>&) and write registerNew() method according to container
  1283. /// and few more methods; get() to find element, unregister() to unregister single entry.
  1284. /// Please note that this is thread-unsafe and should also implement thread-safety mechanisms in implementation.
  1285. template <typename T_Ptr, typename Container>
  1286. class AbstractRegistry : public base::threading::ThreadSafe {
  1287. public:
  1288. typedef typename Container::iterator iterator;
  1289. typedef typename Container::const_iterator const_iterator;
  1290. /// @brief Default constructor
  1291. AbstractRegistry(void) {}
  1292. /// @brief Move constructor that is useful for base classes
  1293. AbstractRegistry(AbstractRegistry&& sr) {
  1294. if (this == &sr) {
  1295. return;
  1296. }
  1297. unregisterAll();
  1298. m_list = std::move(sr.m_list);
  1299. }
  1300. bool operator==(const AbstractRegistry<T_Ptr, Container>& other) {
  1301. if (size() != other.size()) {
  1302. return false;
  1303. }
  1304. for (std::size_t i = 0; i < m_list.size(); ++i) {
  1305. if (m_list.at(i) != other.m_list.at(i)) {
  1306. return false;
  1307. }
  1308. }
  1309. return true;
  1310. }
  1311. bool operator!=(const AbstractRegistry<T_Ptr, Container>& other) {
  1312. if (size() != other.size()) {
  1313. return true;
  1314. }
  1315. for (std::size_t i = 0; i < m_list.size(); ++i) {
  1316. if (m_list.at(i) != other.m_list.at(i)) {
  1317. return true;
  1318. }
  1319. }
  1320. return false;
  1321. }
  1322. /// @brief Assignment move operator
  1323. AbstractRegistry& operator=(AbstractRegistry&& sr) {
  1324. if (this == &sr) {
  1325. return *this;
  1326. }
  1327. unregisterAll();
  1328. m_list = std::move(sr.m_list);
  1329. return *this;
  1330. }
  1331. virtual ~AbstractRegistry(void) {
  1332. }
  1333. /// @return Iterator pointer from start of repository
  1334. virtual inline iterator begin(void) ELPP_FINAL {
  1335. return m_list.begin();
  1336. }
  1337. /// @return Iterator pointer from end of repository
  1338. virtual inline iterator end(void) ELPP_FINAL {
  1339. return m_list.end();
  1340. }
  1341. /// @return Constant iterator pointer from start of repository
  1342. virtual inline const_iterator cbegin(void) const ELPP_FINAL {
  1343. return m_list.cbegin();
  1344. }
  1345. /// @return End of repository
  1346. virtual inline const_iterator cend(void) const ELPP_FINAL {
  1347. return m_list.cend();
  1348. }
  1349. /// @return Whether or not repository is empty
  1350. virtual inline bool empty(void) const ELPP_FINAL {
  1351. return m_list.empty();
  1352. }
  1353. /// @return Size of repository
  1354. virtual inline std::size_t size(void) const ELPP_FINAL {
  1355. return m_list.size();
  1356. }
  1357. /// @brief Returns underlying container by reference
  1358. virtual inline Container& list(void) ELPP_FINAL {
  1359. return m_list;
  1360. }
  1361. /// @brief Returns underlying container by constant reference.
  1362. virtual inline const Container& list(void) const ELPP_FINAL {
  1363. return m_list;
  1364. }
  1365. /// @brief Unregisters all the pointers from current repository.
  1366. virtual void unregisterAll(void) = 0;
  1367. protected:
  1368. virtual void deepCopy(const AbstractRegistry<T_Ptr, Container>&) = 0;
  1369. void reinitDeepCopy(const AbstractRegistry<T_Ptr, Container>& sr) {
  1370. unregisterAll();
  1371. deepCopy(sr);
  1372. }
  1373. private:
  1374. Container m_list;
  1375. };
  1376. /// @brief A pointer registry mechanism to manage memory and provide search functionalities. (non-predicate version)
  1377. ///
  1378. /// @detail NOTE: This is thread-unsafe implementation (although it contains lock function, it does not use these functions)
  1379. /// of AbstractRegistry<T_Ptr, Container>. Any implementation of this class should be
  1380. /// explicitly (by using lock functions)
  1381. template <typename T_Ptr, typename T_Key = const char*>
  1382. class Registry : public AbstractRegistry<T_Ptr, std::map<T_Key, T_Ptr*>> {
  1383. public:
  1384. typedef typename Registry<T_Ptr, T_Key>::iterator iterator;
  1385. typedef typename Registry<T_Ptr, T_Key>::const_iterator const_iterator;
  1386. Registry(void) {}
  1387. /// @brief Copy constructor that is useful for base classes. Try to avoid this constructor, use move constructor.
  1388. Registry(const Registry& sr) : AbstractRegistry<T_Ptr, std::vector<T_Ptr*>>() {
  1389. if (this == &sr) {
  1390. return;
  1391. }
  1392. this->reinitDeepCopy(sr);
  1393. }
  1394. /// @brief Assignment operator that unregisters all the existing registeries and deeply copies each of repo element
  1395. /// @see unregisterAll()
  1396. /// @see deepCopy(const AbstractRegistry&)
  1397. Registry& operator=(const Registry& sr) {
  1398. if (this == &sr) {
  1399. return *this;
  1400. }
  1401. this->reinitDeepCopy(sr);
  1402. return *this;
  1403. }
  1404. virtual ~Registry(void) {
  1405. unregisterAll();
  1406. }
  1407. protected:
  1408. virtual void unregisterAll(void) ELPP_FINAL {
  1409. if (!this->empty()) {
  1410. for (auto&& curr : this->list()) {
  1411. base::utils::safeDelete(curr.second);
  1412. }
  1413. this->list().clear();
  1414. }
  1415. }
  1416. /// @brief Registers new registry to repository.
  1417. virtual void registerNew(const T_Key& uniqKey, T_Ptr* ptr) ELPP_FINAL {
  1418. unregister(uniqKey);
  1419. this->list().insert(std::make_pair(uniqKey, ptr));
  1420. }
  1421. /// @brief Unregisters single entry mapped to specified unique key
  1422. void unregister(const T_Key& uniqKey) {
  1423. T_Ptr* existing = get(uniqKey);
  1424. if (existing != nullptr) {
  1425. this->list().erase(uniqKey);
  1426. base::utils::safeDelete(existing);
  1427. }
  1428. }
  1429. /// @brief Gets pointer from repository. If none found, nullptr is returned.
  1430. T_Ptr* get(const T_Key& uniqKey) {
  1431. iterator it = this->list().find(uniqKey);
  1432. return it == this->list().end()
  1433. ? nullptr
  1434. : it->second;
  1435. }
  1436. private:
  1437. virtual void deepCopy(const AbstractRegistry<T_Ptr, std::map<T_Key, T_Ptr*>>& sr) ELPP_FINAL {
  1438. for (const_iterator it = sr.cbegin(); it != sr.cend(); ++it) {
  1439. registerNew(it->first, new T_Ptr(*it->second));
  1440. }
  1441. }
  1442. };
  1443. /// @brief A pointer registry mechanism to manage memory and provide search functionalities. (predicate version)
  1444. ///
  1445. /// @detail NOTE: This is thread-unsafe implementation of AbstractRegistry<T_Ptr, Container>. Any implementation of this class
  1446. /// should be made thread-safe explicitly
  1447. template <typename T_Ptr, typename Pred>
  1448. class RegistryWithPred : public AbstractRegistry<T_Ptr, std::vector<T_Ptr*>> {
  1449. public:
  1450. typedef typename RegistryWithPred<T_Ptr, Pred>::iterator iterator;
  1451. typedef typename RegistryWithPred<T_Ptr, Pred>::const_iterator const_iterator;
  1452. RegistryWithPred(void) {
  1453. }
  1454. virtual ~RegistryWithPred(void) {
  1455. unregisterAll();
  1456. }
  1457. /// @brief Copy constructor that is useful for base classes. Try to avoid this constructor, use move constructor.
  1458. RegistryWithPred(const RegistryWithPred& sr) : AbstractRegistry<T_Ptr, std::vector<T_Ptr*>>() {
  1459. if (this == &sr) {
  1460. return;
  1461. }
  1462. this->reinitDeepCopy(sr);
  1463. }
  1464. /// @brief Assignment operator that unregisters all the existing registeries and deeply copies each of repo element
  1465. /// @see unregisterAll()
  1466. /// @see deepCopy(const AbstractRegistry&)
  1467. RegistryWithPred& operator=(const RegistryWithPred& sr) {
  1468. if (this == &sr) {
  1469. return *this;
  1470. }
  1471. this->reinitDeepCopy(sr);
  1472. return *this;
  1473. }
  1474. friend base::type::ostream_t& operator<<(base::type::ostream_t& os, const RegistryWithPred& sr) {
  1475. for (const_iterator it = sr.list().begin(); it != sr.list().end(); ++it) {
  1476. os << ELPP_LITERAL(" ") << **it << ELPP_LITERAL("\n");
  1477. }
  1478. return os;
  1479. }
  1480. protected:
  1481. virtual void unregisterAll(void) ELPP_FINAL {
  1482. if (!this->empty()) {
  1483. for (auto&& curr : this->list()) {
  1484. base::utils::safeDelete(curr);
  1485. }
  1486. this->list().clear();
  1487. }
  1488. }
  1489. virtual void unregister(T_Ptr*& ptr) ELPP_FINAL {
  1490. if (ptr) {
  1491. iterator iter = this->begin();
  1492. for (; iter != this->end(); ++iter) {
  1493. if (ptr == *iter) {
  1494. break;
  1495. }
  1496. }
  1497. if (iter != this->end() && *iter != nullptr) {
  1498. this->list().erase(iter);
  1499. base::utils::safeDelete(*iter);
  1500. }
  1501. }
  1502. }
  1503. virtual inline void registerNew(T_Ptr* ptr) ELPP_FINAL {
  1504. this->list().push_back(ptr);
  1505. }
  1506. /// @brief Gets pointer from repository with speicifed arguments. Arguments are passed to predicate
  1507. /// in order to validate pointer.
  1508. template <typename T, typename T2>
  1509. T_Ptr* get(const T& arg1, const T2 arg2) {
  1510. iterator iter = std::find_if(this->list().begin(), this->list().end(), Pred(arg1, arg2));
  1511. if (iter != this->list().end() && *iter != nullptr) {
  1512. return *iter;
  1513. }
  1514. return nullptr;
  1515. }
  1516. private:
  1517. virtual void deepCopy(const AbstractRegistry<T_Ptr, std::vector<T_Ptr*>>& sr) {
  1518. for (const_iterator it = sr.list().begin(); it != sr.list().end(); ++it) {
  1519. registerNew(new T_Ptr(**it));
  1520. }
  1521. }
  1522. };
  1523. class Utils {
  1524. public:
  1525. template <typename T, typename TPtr>
  1526. static bool installCallback(const std::string& id, std::map<std::string, TPtr>* mapT) {
  1527. if (mapT->find(id) == mapT->end()) {
  1528. mapT->insert(std::make_pair(id, TPtr(new T())));
  1529. return true;
  1530. }
  1531. return false;
  1532. }
  1533. template <typename T, typename TPtr>
  1534. static void uninstallCallback(const std::string& id, std::map<std::string, TPtr>* mapT) {
  1535. if (mapT->find(id) != mapT->end()) {
  1536. mapT->erase(id);
  1537. }
  1538. }
  1539. template <typename T, typename TPtr>
  1540. static T* callback(const std::string& id, std::map<std::string, TPtr>* mapT) {
  1541. typename std::map<std::string, TPtr>::iterator iter = mapT->find(id);
  1542. if (iter != mapT->end()) {
  1543. return static_cast<T*>(iter->second.get());
  1544. }
  1545. return nullptr;
  1546. }
  1547. };
  1548. } // namespace utils
  1549. } // namespace base
  1550. /// @brief Base of Easylogging++ friendly class
  1551. ///
  1552. /// @detail After inheriting this class publicly, implement pure-virtual function `void log(std::ostream&) const`
  1553. class Loggable {
  1554. public:
  1555. virtual ~Loggable(void) {}
  1556. virtual void log(el::base::type::ostream_t&) const = 0;
  1557. private:
  1558. friend inline el::base::type::ostream_t& operator<<(el::base::type::ostream_t& os, const Loggable& loggable) {
  1559. loggable.log(os);
  1560. return os;
  1561. }
  1562. };
  1563. namespace base {
  1564. /// @brief Represents log format containing flags and date format. This is used internally to start initial log
  1565. class LogFormat : public Loggable {
  1566. public:
  1567. LogFormat(void);
  1568. LogFormat(Level level, const base::type::string_t& format);
  1569. LogFormat(const LogFormat& logFormat);
  1570. LogFormat(LogFormat&& logFormat);
  1571. LogFormat& operator=(const LogFormat& logFormat);
  1572. virtual ~LogFormat(void) {}
  1573. bool operator==(const LogFormat& other);
  1574. /// @brief Updates format to be used while logging.
  1575. /// @param userFormat User provided format
  1576. void parseFromFormat(const base::type::string_t& userFormat);
  1577. inline Level level(void) const {
  1578. return m_level;
  1579. }
  1580. inline const base::type::string_t& userFormat(void) const {
  1581. return m_userFormat;
  1582. }
  1583. inline const base::type::string_t& format(void) const {
  1584. return m_format;
  1585. }
  1586. inline const std::string& dateTimeFormat(void) const {
  1587. return m_dateTimeFormat;
  1588. }
  1589. inline base::type::EnumType flags(void) const {
  1590. return m_flags;
  1591. }
  1592. inline bool hasFlag(base::FormatFlags flag) const {
  1593. return base::utils::hasFlag(flag, m_flags);
  1594. }
  1595. virtual void log(el::base::type::ostream_t& os) const {
  1596. os << m_format;
  1597. }
  1598. protected:
  1599. /// @brief Updates date time format if available in currFormat.
  1600. /// @param index Index where %datetime, %date or %time was found
  1601. /// @param [in,out] currFormat current format that is being used to format
  1602. virtual void updateDateFormat(std::size_t index, base::type::string_t& currFormat) ELPP_FINAL;
  1603. /// @brief Updates %level from format. This is so that we dont have to do it at log-writing-time. It uses m_format and m_level
  1604. virtual void updateFormatSpec(void) ELPP_FINAL;
  1605. inline void addFlag(base::FormatFlags flag) {
  1606. base::utils::addFlag(flag, &m_flags);
  1607. }
  1608. private:
  1609. Level m_level;
  1610. base::type::string_t m_userFormat;
  1611. base::type::string_t m_format;
  1612. std::string m_dateTimeFormat;
  1613. base::type::EnumType m_flags;
  1614. std::string m_currentUser;
  1615. std::string m_currentHost;
  1616. friend class el::Logger; // To resolve loggerId format specifier easily
  1617. };
  1618. } // namespace base
  1619. /// @brief Resolving function for format specifier
  1620. typedef std::function<std::string(const LogMessage*)> FormatSpecifierValueResolver;
  1621. /// @brief User-provided custom format specifier
  1622. /// @see el::Helpers::installCustomFormatSpecifier
  1623. /// @see FormatSpecifierValueResolver
  1624. class CustomFormatSpecifier {
  1625. public:
  1626. CustomFormatSpecifier(const char* formatSpecifier, const FormatSpecifierValueResolver& resolver) :
  1627. m_formatSpecifier(formatSpecifier), m_resolver(resolver) {}
  1628. inline const char* formatSpecifier(void) const {
  1629. return m_formatSpecifier;
  1630. }
  1631. inline const FormatSpecifierValueResolver& resolver(void) const {
  1632. return m_resolver;
  1633. }
  1634. inline bool operator==(const char* formatSpecifier) {
  1635. return strcmp(m_formatSpecifier, formatSpecifier) == 0;
  1636. }
  1637. private:
  1638. const char* m_formatSpecifier;
  1639. FormatSpecifierValueResolver m_resolver;
  1640. };
  1641. /// @brief Represents single configuration that has representing level, configuration type and a string based value.
  1642. ///
  1643. /// @detail String based value means any value either its boolean, integer or string itself, it will be embedded inside quotes
  1644. /// and will be parsed later.
  1645. ///
  1646. /// Consider some examples below:
  1647. /// * el::Configuration confEnabledInfo(el::Level::Info, el::ConfigurationType::Enabled, "true");
  1648. /// * el::Configuration confMaxLogFileSizeInfo(el::Level::Info, el::ConfigurationType::MaxLogFileSize, "2048");
  1649. /// * el::Configuration confFilenameInfo(el::Level::Info, el::ConfigurationType::Filename, "/var/log/my.log");
  1650. class Configuration : public Loggable {
  1651. public:
  1652. Configuration(const Configuration& c);
  1653. Configuration& operator=(const Configuration& c);
  1654. virtual ~Configuration(void) {
  1655. }
  1656. /// @brief Full constructor used to sets value of configuration
  1657. Configuration(Level level, ConfigurationType configurationType, const std::string& value);
  1658. /// @brief Gets level of current configuration
  1659. inline Level level(void) const {
  1660. return m_level;
  1661. }
  1662. /// @brief Gets configuration type of current configuration
  1663. inline ConfigurationType configurationType(void) const {
  1664. return m_configurationType;
  1665. }
  1666. /// @brief Gets string based configuration value
  1667. inline const std::string& value(void) const {
  1668. return m_value;
  1669. }
  1670. /// @brief Set string based configuration value
  1671. /// @param value Value to set. Values have to be std::string; For boolean values use "true", "false", for any integral values
  1672. /// use them in quotes. They will be parsed when configuring
  1673. inline void setValue(const std::string& value) {
  1674. m_value = value;
  1675. }
  1676. virtual void log(el::base::type::ostream_t& os) const;
  1677. /// @brief Used to find configuration from configuration (pointers) repository. Avoid using it.
  1678. class Predicate {
  1679. public:
  1680. Predicate(Level level, ConfigurationType configurationType);
  1681. bool operator()(const Configuration* conf) const;
  1682. private:
  1683. Level m_level;
  1684. ConfigurationType m_configurationType;
  1685. };
  1686. private:
  1687. Level m_level;
  1688. ConfigurationType m_configurationType;
  1689. std::string m_value;
  1690. };
  1691. /// @brief Thread-safe Configuration repository
  1692. ///
  1693. /// @detail This repository represents configurations for all the levels and configuration type mapped to a value.
  1694. class Configurations : public base::utils::RegistryWithPred<Configuration, Configuration::Predicate> {
  1695. public:
  1696. /// @brief Default constructor with empty repository
  1697. Configurations(void);
  1698. /// @brief Constructor used to set configurations using configuration file.
  1699. /// @param configurationFile Full path to configuration file
  1700. /// @param useDefaultsForRemaining Lets you set the remaining configurations to default.
  1701. /// @param base If provided, this configuration will be based off existing repository that this argument is pointing to.
  1702. /// @see parseFromFile(const std::string&, Configurations* base)
  1703. /// @see setRemainingToDefault()
  1704. Configurations(const std::string& configurationFile, bool useDefaultsForRemaining = true,
  1705. Configurations* base = nullptr);
  1706. virtual ~Configurations(void) {
  1707. }
  1708. /// @brief Parses configuration from file.
  1709. /// @param configurationFile Full path to configuration file
  1710. /// @param base Configurations to base new configuration repository off. This value is used when you want to use
  1711. /// existing Configurations to base all the values and then set rest of configuration via configuration file.
  1712. /// @return True if successfully parsed, false otherwise. You may define 'ELPP_DEBUG_ASSERT_FAILURE' to make sure you
  1713. /// do not proceed without successful parse.
  1714. bool parseFromFile(const std::string& configurationFile, Configurations* base = nullptr);
  1715. /// @brief Parse configurations from configuration string.
  1716. ///
  1717. /// @detail This configuration string has same syntax as configuration file contents. Make sure all the necessary
  1718. /// new line characters are provided.
  1719. /// @param base Configurations to base new configuration repository off. This value is used when you want to use
  1720. /// existing Configurations to base all the values and then set rest of configuration via configuration text.
  1721. /// @return True if successfully parsed, false otherwise. You may define 'ELPP_DEBUG_ASSERT_FAILURE' to make sure you
  1722. /// do not proceed without successful parse.
  1723. bool parseFromText(const std::string& configurationsString, Configurations* base = nullptr);
  1724. /// @brief Sets configuration based-off an existing configurations.
  1725. /// @param base Pointer to existing configurations.
  1726. void setFromBase(Configurations* base);
  1727. /// @brief Determines whether or not specified configuration type exists in the repository.
  1728. ///
  1729. /// @detail Returns as soon as first level is found.
  1730. /// @param configurationType Type of configuration to check existence for.
  1731. bool hasConfiguration(ConfigurationType configurationType);
  1732. /// @brief Determines whether or not specified configuration type exists for specified level
  1733. /// @param level Level to check
  1734. /// @param configurationType Type of configuration to check existence for.
  1735. bool hasConfiguration(Level level, ConfigurationType configurationType);
  1736. /// @brief Sets value of configuration for specified level.
  1737. ///
  1738. /// @detail Any existing configuration for specified level will be replaced. Also note that configuration types
  1739. /// ConfigurationType::SubsecondPrecision and ConfigurationType::PerformanceTracking will be ignored if not set for
  1740. /// Level::Global because these configurations are not dependant on level.
  1741. /// @param level Level to set configuration for (el::Level).
  1742. /// @param configurationType Type of configuration (el::ConfigurationType)
  1743. /// @param value A string based value. Regardless of what the data type of configuration is, it will always be string
  1744. /// from users' point of view. This is then parsed later to be used internally.
  1745. /// @see Configuration::setValue(const std::string& value)
  1746. /// @see el::Level
  1747. /// @see el::ConfigurationType
  1748. void set(Level level, ConfigurationType configurationType, const std::string& value);
  1749. /// @brief Sets single configuration based on other single configuration.
  1750. /// @see set(Level level, ConfigurationType configurationType, const std::string& value)
  1751. void set(Configuration* conf);
  1752. inline Configuration* get(Level level, ConfigurationType configurationType) {
  1753. base::threading::ScopedLock scopedLock(lock());
  1754. return RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType);
  1755. }
  1756. /// @brief Sets configuration for all levels.
  1757. /// @param configurationType Type of configuration
  1758. /// @param value String based value
  1759. /// @see Configurations::set(Level level, ConfigurationType configurationType, const std::string& value)
  1760. inline void setGlobally(ConfigurationType configurationType, const std::string& value) {
  1761. setGlobally(configurationType, value, false);
  1762. }
  1763. /// @brief Clears repository so that all the configurations are unset
  1764. inline void clear(void) {
  1765. base::threading::ScopedLock scopedLock(lock());
  1766. unregisterAll();
  1767. }
  1768. /// @brief Gets configuration file used in parsing this configurations.
  1769. ///
  1770. /// @detail If this repository was set manually or by text this returns empty string.
  1771. inline const std::string& configurationFile(void) const {
  1772. return m_configurationFile;
  1773. }
  1774. /// @brief Sets configurations to "factory based" configurations.
  1775. void setToDefault(void);
  1776. /// @brief Lets you set the remaining configurations to default.
  1777. ///
  1778. /// @detail By remaining, it means that the level/type a configuration does not exist for.
  1779. /// This function is useful when you want to minimize chances of failures, e.g, if you have a configuration file that sets
  1780. /// configuration for all the configurations except for Enabled or not, we use this so that ENABLED is set to default i.e,
  1781. /// true. If you dont do this explicitly (either by calling this function or by using second param in Constructor
  1782. /// and try to access a value, an error is thrown
  1783. void setRemainingToDefault(void);
  1784. /// @brief Parser used internally to parse configurations from file or text.
  1785. ///
  1786. /// @detail This class makes use of base::utils::Str.
  1787. /// You should not need this unless you are working on some tool for Easylogging++
  1788. class Parser : base::StaticClass {
  1789. public:
  1790. /// @brief Parses configuration from file.
  1791. /// @param configurationFile Full path to configuration file
  1792. /// @param sender Sender configurations pointer. Usually 'this' is used from calling class
  1793. /// @param base Configurations to base new configuration repository off. This value is used when you want to use
  1794. /// existing Configurations to base all the values and then set rest of configuration via configuration file.
  1795. /// @return True if successfully parsed, false otherwise. You may define '_STOP_ON_FIRSTELPP_ASSERTION' to make sure you
  1796. /// do not proceed without successful parse.
  1797. static bool parseFromFile(const std::string& configurationFile, Configurations* sender,
  1798. Configurations* base = nullptr);
  1799. /// @brief Parse configurations from configuration string.
  1800. ///
  1801. /// @detail This configuration string has same syntax as configuration file contents. Make sure all the necessary
  1802. /// new line characters are provided. You may define '_STOP_ON_FIRSTELPP_ASSERTION' to make sure you
  1803. /// do not proceed without successful parse (This is recommended)
  1804. /// @param configurationsString the configuration in plain text format
  1805. /// @param sender Sender configurations pointer. Usually 'this' is used from calling class
  1806. /// @param base Configurations to base new configuration repository off. This value is used when you want to use
  1807. /// existing Configurations to base all the values and then set rest of configuration via configuration text.
  1808. /// @return True if successfully parsed, false otherwise.
  1809. static bool parseFromText(const std::string& configurationsString, Configurations* sender,
  1810. Configurations* base = nullptr);
  1811. private:
  1812. friend class el::Loggers;
  1813. static void ignoreComments(std::string* line);
  1814. static bool isLevel(const std::string& line);
  1815. static bool isComment(const std::string& line);
  1816. static inline bool isConfig(const std::string& line);
  1817. static bool parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr, Level* currLevel,
  1818. Configurations* conf);
  1819. };
  1820. private:
  1821. std::string m_configurationFile;
  1822. bool m_isFromFile;
  1823. friend class el::Loggers;
  1824. /// @brief Unsafely sets configuration if does not already exist
  1825. void unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value);
  1826. /// @brief Thread unsafe set
  1827. void unsafeSet(Level level, ConfigurationType configurationType, const std::string& value);
  1828. /// @brief Sets configurations for all levels including Level::Global if includeGlobalLevel is true
  1829. /// @see Configurations::setGlobally(ConfigurationType configurationType, const std::string& value)
  1830. void setGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel);
  1831. /// @brief Sets configurations (Unsafely) for all levels including Level::Global if includeGlobalLevel is true
  1832. /// @see Configurations::setGlobally(ConfigurationType configurationType, const std::string& value)
  1833. void unsafeSetGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel);
  1834. };
  1835. namespace base {
  1836. typedef std::shared_ptr<base::type::fstream_t> FileStreamPtr;
  1837. typedef std::map<std::string, FileStreamPtr> LogStreamsReferenceMap;
  1838. /// @brief Configurations with data types.
  1839. ///
  1840. /// @detail el::Configurations have string based values. This is whats used internally in order to read correct configurations.
  1841. /// This is to perform faster while writing logs using correct configurations.
  1842. ///
  1843. /// This is thread safe and final class containing non-virtual destructor (means nothing should inherit this class)
  1844. class TypedConfigurations : public base::threading::ThreadSafe {
  1845. public:
  1846. /// @brief Constructor to initialize (construct) the object off el::Configurations
  1847. /// @param configurations Configurations pointer/reference to base this typed configurations off.
  1848. /// @param logStreamsReference Use ELPP->registeredLoggers()->logStreamsReference()
  1849. TypedConfigurations(Configurations* configurations, base::LogStreamsReferenceMap* logStreamsReference);
  1850. TypedConfigurations(const TypedConfigurations& other);
  1851. virtual ~TypedConfigurations(void) {
  1852. }
  1853. const Configurations* configurations(void) const {
  1854. return m_configurations;
  1855. }
  1856. bool enabled(Level level);
  1857. bool toFile(Level level);
  1858. const std::string& filename(Level level);
  1859. bool toStandardOutput(Level level);
  1860. const base::LogFormat& logFormat(Level level);
  1861. const base::SubsecondPrecision& subsecondPrecision(Level level = Level::Global);
  1862. const base::MillisecondsWidth& millisecondsWidth(Level level = Level::Global);
  1863. bool performanceTracking(Level level = Level::Global);
  1864. base::type::fstream_t* fileStream(Level level);
  1865. std::size_t maxLogFileSize(Level level);
  1866. std::size_t logFlushThreshold(Level level);
  1867. private:
  1868. Configurations* m_configurations;
  1869. std::map<Level, bool> m_enabledMap;
  1870. std::map<Level, bool> m_toFileMap;
  1871. std::map<Level, std::string> m_filenameMap;
  1872. std::map<Level, bool> m_toStandardOutputMap;
  1873. std::map<Level, base::LogFormat> m_logFormatMap;
  1874. std::map<Level, base::SubsecondPrecision> m_subsecondPrecisionMap;
  1875. std::map<Level, bool> m_performanceTrackingMap;
  1876. std::map<Level, base::FileStreamPtr> m_fileStreamMap;
  1877. std::map<Level, std::size_t> m_maxLogFileSizeMap;
  1878. std::map<Level, std::size_t> m_logFlushThresholdMap;
  1879. base::LogStreamsReferenceMap* m_logStreamsReference;
  1880. friend class el::Helpers;
  1881. friend class el::base::MessageBuilder;
  1882. friend class el::base::Writer;
  1883. friend class el::base::DefaultLogDispatchCallback;
  1884. friend class el::base::LogDispatcher;
  1885. template <typename Conf_T>
  1886. inline Conf_T getConfigByVal(Level level, const std::map<Level, Conf_T>* confMap, const char* confName) {
  1887. base::threading::ScopedLock scopedLock(lock());
  1888. return unsafeGetConfigByVal(level, confMap, confName); // This is not unsafe anymore - mutex locked in scope
  1889. }
  1890. template <typename Conf_T>
  1891. inline Conf_T& getConfigByRef(Level level, std::map<Level, Conf_T>* confMap, const char* confName) {
  1892. base::threading::ScopedLock scopedLock(lock());
  1893. return unsafeGetConfigByRef(level, confMap, confName); // This is not unsafe anymore - mutex locked in scope
  1894. }
  1895. template <typename Conf_T>
  1896. Conf_T unsafeGetConfigByVal(Level level, const std::map<Level, Conf_T>* confMap, const char* confName) {
  1897. ELPP_UNUSED(confName);
  1898. typename std::map<Level, Conf_T>::const_iterator it = confMap->find(level);
  1899. if (it == confMap->end()) {
  1900. try {
  1901. return confMap->at(Level::Global);
  1902. } catch (...) {
  1903. ELPP_INTERNAL_ERROR("Unable to get configuration [" << confName << "] for level ["
  1904. << LevelHelper::convertToString(level) << "]"
  1905. << std::endl << "Please ensure you have properly configured logger.", false);
  1906. return Conf_T();
  1907. }
  1908. }
  1909. return it->second;
  1910. }
  1911. template <typename Conf_T>
  1912. Conf_T& unsafeGetConfigByRef(Level level, std::map<Level, Conf_T>* confMap, const char* confName) {
  1913. ELPP_UNUSED(confName);
  1914. typename std::map<Level, Conf_T>::iterator it = confMap->find(level);
  1915. if (it == confMap->end()) {
  1916. try {
  1917. return confMap->at(Level::Global);
  1918. } catch (...) {
  1919. ELPP_INTERNAL_ERROR("Unable to get configuration [" << confName << "] for level ["
  1920. << LevelHelper::convertToString(level) << "]"
  1921. << std::endl << "Please ensure you have properly configured logger.", false);
  1922. }
  1923. }
  1924. return it->second;
  1925. }
  1926. template <typename Conf_T>
  1927. void setValue(Level level, const Conf_T& value, std::map<Level, Conf_T>* confMap, bool includeGlobalLevel = true) {
  1928. // If map is empty and we are allowed to add into generic level (Level::Global), do it!
  1929. if (confMap->empty() && includeGlobalLevel) {
  1930. confMap->insert(std::make_pair(Level::Global, value));
  1931. return;
  1932. }
  1933. // If same value exist in generic level already, dont add it to explicit level
  1934. typename std::map<Level, Conf_T>::iterator it = confMap->find(Level::Global);
  1935. if (it != confMap->end() && it->second == value) {
  1936. return;
  1937. }
  1938. // Now make sure we dont double up values if we really need to add it to explicit level
  1939. it = confMap->find(level);
  1940. if (it == confMap->end()) {
  1941. // Value not found for level, add new
  1942. confMap->insert(std::make_pair(level, value));
  1943. } else {
  1944. // Value found, just update value
  1945. confMap->at(level) = value;
  1946. }
  1947. }
  1948. void build(Configurations* configurations);
  1949. unsigned long getULong(std::string confVal);
  1950. std::string resolveFilename(const std::string& filename);
  1951. void insertFile(Level level, const std::string& fullFilename);
  1952. bool unsafeValidateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback);
  1953. inline bool validateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback) {
  1954. base::threading::ScopedLock scopedLock(lock());
  1955. return unsafeValidateFileRolling(level, preRollOutCallback);
  1956. }
  1957. };
  1958. /// @brief Class that keeps record of current line hit for occasional logging
  1959. class HitCounter {
  1960. public:
  1961. HitCounter(void) :
  1962. m_filename(""),
  1963. m_lineNumber(0),
  1964. m_hitCounts(0) {
  1965. }
  1966. HitCounter(const char* filename, base::type::LineNumber lineNumber) :
  1967. m_filename(filename),
  1968. m_lineNumber(lineNumber),
  1969. m_hitCounts(0) {
  1970. }
  1971. HitCounter(const HitCounter& hitCounter) :
  1972. m_filename(hitCounter.m_filename),
  1973. m_lineNumber(hitCounter.m_lineNumber),
  1974. m_hitCounts(hitCounter.m_hitCounts) {
  1975. }
  1976. HitCounter& operator=(const HitCounter& hitCounter) {
  1977. if (&hitCounter != this) {
  1978. m_filename = hitCounter.m_filename;
  1979. m_lineNumber = hitCounter.m_lineNumber;
  1980. m_hitCounts = hitCounter.m_hitCounts;
  1981. }
  1982. return *this;
  1983. }
  1984. virtual ~HitCounter(void) {
  1985. }
  1986. /// @brief Resets location of current hit counter
  1987. inline void resetLocation(const char* filename, base::type::LineNumber lineNumber) {
  1988. m_filename = filename;
  1989. m_lineNumber = lineNumber;
  1990. }
  1991. /// @brief Validates hit counts and resets it if necessary
  1992. inline void validateHitCounts(std::size_t n) {
  1993. if (m_hitCounts >= base::consts::kMaxLogPerCounter) {
  1994. m_hitCounts = (n >= 1 ? base::consts::kMaxLogPerCounter % n : 0);
  1995. }
  1996. ++m_hitCounts;
  1997. }
  1998. inline const char* filename(void) const {
  1999. return m_filename;
  2000. }
  2001. inline base::type::LineNumber lineNumber(void) const {
  2002. return m_lineNumber;
  2003. }
  2004. inline std::size_t hitCounts(void) const {
  2005. return m_hitCounts;
  2006. }
  2007. inline void increment(void) {
  2008. ++m_hitCounts;
  2009. }
  2010. class Predicate {
  2011. public:
  2012. Predicate(const char* filename, base::type::LineNumber lineNumber)
  2013. : m_filename(filename),
  2014. m_lineNumber(lineNumber) {
  2015. }
  2016. inline bool operator()(const HitCounter* counter) {
  2017. return ((counter != nullptr) &&
  2018. (strcmp(counter->m_filename, m_filename) == 0) &&
  2019. (counter->m_lineNumber == m_lineNumber));
  2020. }
  2021. private:
  2022. const char* m_filename;
  2023. base::type::LineNumber m_lineNumber;
  2024. };
  2025. private:
  2026. const char* m_filename;
  2027. base::type::LineNumber m_lineNumber;
  2028. std::size_t m_hitCounts;
  2029. };
  2030. /// @brief Repository for hit counters used across the application
  2031. class RegisteredHitCounters : public base::utils::RegistryWithPred<base::HitCounter, base::HitCounter::Predicate> {
  2032. public:
  2033. /// @brief Validates counter for every N, i.e, registers new if does not exist otherwise updates original one
  2034. /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned
  2035. bool validateEveryN(const char* filename, base::type::LineNumber lineNumber, std::size_t n);
  2036. /// @brief Validates counter for hits >= N, i.e, registers new if does not exist otherwise updates original one
  2037. /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned
  2038. bool validateAfterN(const char* filename, base::type::LineNumber lineNumber, std::size_t n);
  2039. /// @brief Validates counter for hits are <= n, i.e, registers new if does not exist otherwise updates original one
  2040. /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned
  2041. bool validateNTimes(const char* filename, base::type::LineNumber lineNumber, std::size_t n);
  2042. /// @brief Gets hit counter registered at specified position
  2043. inline const base::HitCounter* getCounter(const char* filename, base::type::LineNumber lineNumber) {
  2044. base::threading::ScopedLock scopedLock(lock());
  2045. return get(filename, lineNumber);
  2046. }
  2047. };
  2048. /// @brief Action to be taken for dispatching
  2049. enum class DispatchAction : base::type::EnumType {
  2050. None = 1, NormalLog = 2, SysLog = 4
  2051. };
  2052. } // namespace base
  2053. template <typename T>
  2054. class Callback : protected base::threading::ThreadSafe {
  2055. public:
  2056. Callback(void) : m_enabled(true) {}
  2057. inline bool enabled(void) const {
  2058. return m_enabled;
  2059. }
  2060. inline void setEnabled(bool enabled) {
  2061. base::threading::ScopedLock scopedLock(lock());
  2062. m_enabled = enabled;
  2063. }
  2064. protected:
  2065. virtual void handle(const T* handlePtr) = 0;
  2066. private:
  2067. bool m_enabled;
  2068. };
  2069. class LogDispatchData {
  2070. public:
  2071. LogDispatchData() : m_logMessage(nullptr), m_dispatchAction(base::DispatchAction::None) {}
  2072. inline const LogMessage* logMessage(void) const {
  2073. return m_logMessage;
  2074. }
  2075. inline base::DispatchAction dispatchAction(void) const {
  2076. return m_dispatchAction;
  2077. }
  2078. private:
  2079. LogMessage* m_logMessage;
  2080. base::DispatchAction m_dispatchAction;
  2081. friend class base::LogDispatcher;
  2082. inline void setLogMessage(LogMessage* logMessage) {
  2083. m_logMessage = logMessage;
  2084. }
  2085. inline void setDispatchAction(base::DispatchAction dispatchAction) {
  2086. m_dispatchAction = dispatchAction;
  2087. }
  2088. };
  2089. class LogDispatchCallback : public Callback<LogDispatchData> {
  2090. private:
  2091. friend class base::LogDispatcher;
  2092. };
  2093. class PerformanceTrackingCallback : public Callback<PerformanceTrackingData> {
  2094. private:
  2095. friend class base::PerformanceTracker;
  2096. };
  2097. class LoggerRegistrationCallback : public Callback<Logger> {
  2098. private:
  2099. friend class base::RegisteredLoggers;
  2100. };
  2101. class LogBuilder : base::NoCopy {
  2102. public:
  2103. LogBuilder() : m_termSupportsColor(base::utils::OS::termSupportsColor()) {}
  2104. virtual ~LogBuilder(void) {
  2105. ELPP_INTERNAL_INFO(3, "Destroying log builder...")
  2106. }
  2107. virtual base::type::string_t build(const LogMessage* logMessage, bool appendNewLine) const = 0;
  2108. void convertToColoredOutput(base::type::string_t* logLine, Level level);
  2109. private:
  2110. bool m_termSupportsColor;
  2111. friend class el::base::DefaultLogDispatchCallback;
  2112. };
  2113. typedef std::shared_ptr<LogBuilder> LogBuilderPtr;
  2114. /// @brief Represents a logger holding ID and configurations we need to write logs
  2115. ///
  2116. /// @detail This class does not write logs itself instead its used by writer to read configuations from.
  2117. class Logger : public base::threading::ThreadSafe, public Loggable {
  2118. public:
  2119. Logger(const std::string& id, base::LogStreamsReferenceMap* logStreamsReference);
  2120. Logger(const std::string& id, const Configurations& configurations, base::LogStreamsReferenceMap* logStreamsReference);
  2121. Logger(const Logger& logger);
  2122. Logger& operator=(const Logger& logger);
  2123. virtual ~Logger(void) {
  2124. base::utils::safeDelete(m_typedConfigurations);
  2125. }
  2126. virtual inline void log(el::base::type::ostream_t& os) const {
  2127. os << m_id.c_str();
  2128. }
  2129. /// @brief Configures the logger using specified configurations.
  2130. void configure(const Configurations& configurations);
  2131. /// @brief Reconfigures logger using existing configurations
  2132. void reconfigure(void);
  2133. inline const std::string& id(void) const {
  2134. return m_id;
  2135. }
  2136. inline const std::string& parentApplicationName(void) const {
  2137. return m_parentApplicationName;
  2138. }
  2139. inline void setParentApplicationName(const std::string& parentApplicationName) {
  2140. m_parentApplicationName = parentApplicationName;
  2141. }
  2142. inline Configurations* configurations(void) {
  2143. return &m_configurations;
  2144. }
  2145. inline base::TypedConfigurations* typedConfigurations(void) {
  2146. return m_typedConfigurations;
  2147. }
  2148. static bool isValidId(const std::string& id);
  2149. /// @brief Flushes logger to sync all log files for all levels
  2150. void flush(void);
  2151. void flush(Level level, base::type::fstream_t* fs);
  2152. inline bool isFlushNeeded(Level level) {
  2153. return ++m_unflushedCount.find(level)->second >= m_typedConfigurations->logFlushThreshold(level);
  2154. }
  2155. inline LogBuilder* logBuilder(void) const {
  2156. return m_logBuilder.get();
  2157. }
  2158. inline void setLogBuilder(const LogBuilderPtr& logBuilder) {
  2159. m_logBuilder = logBuilder;
  2160. }
  2161. inline bool enabled(Level level) const {
  2162. return m_typedConfigurations->enabled(level);
  2163. }
  2164. #if ELPP_VARIADIC_TEMPLATES_SUPPORTED
  2165. # define LOGGER_LEVEL_WRITERS_SIGNATURES(FUNCTION_NAME)\
  2166. template <typename T, typename... Args>\
  2167. inline void FUNCTION_NAME(const char*, const T&, const Args&...);\
  2168. template <typename T>\
  2169. inline void FUNCTION_NAME(const T&);
  2170. template <typename T, typename... Args>
  2171. inline void verbose(int, const char*, const T&, const Args&...);
  2172. template <typename T>
  2173. inline void verbose(int, const T&);
  2174. LOGGER_LEVEL_WRITERS_SIGNATURES(info)
  2175. LOGGER_LEVEL_WRITERS_SIGNATURES(debug)
  2176. LOGGER_LEVEL_WRITERS_SIGNATURES(warn)
  2177. LOGGER_LEVEL_WRITERS_SIGNATURES(error)
  2178. LOGGER_LEVEL_WRITERS_SIGNATURES(fatal)
  2179. LOGGER_LEVEL_WRITERS_SIGNATURES(trace)
  2180. # undef LOGGER_LEVEL_WRITERS_SIGNATURES
  2181. #endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED
  2182. private:
  2183. std::string m_id;
  2184. base::TypedConfigurations* m_typedConfigurations;
  2185. base::type::stringstream_t m_stream;
  2186. std::string m_parentApplicationName;
  2187. bool m_isConfigured;
  2188. Configurations m_configurations;
  2189. std::map<Level, unsigned int> m_unflushedCount;
  2190. base::LogStreamsReferenceMap* m_logStreamsReference;
  2191. LogBuilderPtr m_logBuilder;
  2192. friend class el::LogMessage;
  2193. friend class el::Loggers;
  2194. friend class el::Helpers;
  2195. friend class el::base::RegisteredLoggers;
  2196. friend class el::base::DefaultLogDispatchCallback;
  2197. friend class el::base::MessageBuilder;
  2198. friend class el::base::Writer;
  2199. friend class el::base::PErrorWriter;
  2200. friend class el::base::Storage;
  2201. friend class el::base::PerformanceTracker;
  2202. friend class el::base::LogDispatcher;
  2203. Logger(void);
  2204. #if ELPP_VARIADIC_TEMPLATES_SUPPORTED
  2205. template <typename T, typename... Args>
  2206. void log_(Level, int, const char*, const T&, const Args&...);
  2207. template <typename T>
  2208. inline void log_(Level, int, const T&);
  2209. template <typename T, typename... Args>
  2210. void log(Level, const char*, const T&, const Args&...);
  2211. template <typename T>
  2212. inline void log(Level, const T&);
  2213. #endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED
  2214. void initUnflushedCount(void);
  2215. inline base::type::stringstream_t& stream(void) {
  2216. return m_stream;
  2217. }
  2218. void resolveLoggerFormatSpec(void) const;
  2219. };
  2220. namespace base {
  2221. /// @brief Loggers repository
  2222. class RegisteredLoggers : public base::utils::Registry<Logger, std::string> {
  2223. public:
  2224. explicit RegisteredLoggers(const LogBuilderPtr& defaultLogBuilder);
  2225. virtual ~RegisteredLoggers(void) {
  2226. unsafeFlushAll();
  2227. }
  2228. inline void setDefaultConfigurations(const Configurations& configurations) {
  2229. base::threading::ScopedLock scopedLock(lock());
  2230. m_defaultConfigurations.setFromBase(const_cast<Configurations*>(&configurations));
  2231. }
  2232. inline Configurations* defaultConfigurations(void) {
  2233. return &m_defaultConfigurations;
  2234. }
  2235. Logger* get(const std::string& id, bool forceCreation = true);
  2236. template <typename T>
  2237. inline bool installLoggerRegistrationCallback(const std::string& id) {
  2238. return base::utils::Utils::installCallback<T, base::type::LoggerRegistrationCallbackPtr>(id,
  2239. &m_loggerRegistrationCallbacks);
  2240. }
  2241. template <typename T>
  2242. inline void uninstallLoggerRegistrationCallback(const std::string& id) {
  2243. base::utils::Utils::uninstallCallback<T, base::type::LoggerRegistrationCallbackPtr>(id, &m_loggerRegistrationCallbacks);
  2244. }
  2245. template <typename T>
  2246. inline T* loggerRegistrationCallback(const std::string& id) {
  2247. return base::utils::Utils::callback<T, base::type::LoggerRegistrationCallbackPtr>(id, &m_loggerRegistrationCallbacks);
  2248. }
  2249. bool remove(const std::string& id);
  2250. inline bool has(const std::string& id) {
  2251. return get(id, false) != nullptr;
  2252. }
  2253. inline void unregister(Logger*& logger) {
  2254. base::threading::ScopedLock scopedLock(lock());
  2255. base::utils::Registry<Logger, std::string>::unregister(logger->id());
  2256. }
  2257. inline base::LogStreamsReferenceMap* logStreamsReference(void) {
  2258. return &m_logStreamsReference;
  2259. }
  2260. inline void flushAll(void) {
  2261. base::threading::ScopedLock scopedLock(lock());
  2262. unsafeFlushAll();
  2263. }
  2264. inline void setDefaultLogBuilder(LogBuilderPtr& logBuilderPtr) {
  2265. base::threading::ScopedLock scopedLock(lock());
  2266. m_defaultLogBuilder = logBuilderPtr;
  2267. }
  2268. private:
  2269. LogBuilderPtr m_defaultLogBuilder;
  2270. Configurations m_defaultConfigurations;
  2271. base::LogStreamsReferenceMap m_logStreamsReference;
  2272. std::map<std::string, base::type::LoggerRegistrationCallbackPtr> m_loggerRegistrationCallbacks;
  2273. friend class el::base::Storage;
  2274. void unsafeFlushAll(void);
  2275. };
  2276. /// @brief Represents registries for verbose logging
  2277. class VRegistry : base::NoCopy, public base::threading::ThreadSafe {
  2278. public:
  2279. explicit VRegistry(base::type::VerboseLevel level, base::type::EnumType* pFlags);
  2280. /// @brief Sets verbose level. Accepted range is 0-9
  2281. void setLevel(base::type::VerboseLevel level);
  2282. inline base::type::VerboseLevel level(void) const {
  2283. return m_level;
  2284. }
  2285. inline void clearModules(void) {
  2286. base::threading::ScopedLock scopedLock(lock());
  2287. m_modules.clear();
  2288. }
  2289. void setModules(const char* modules);
  2290. bool allowed(base::type::VerboseLevel vlevel, const char* file);
  2291. inline const std::map<std::string, base::type::VerboseLevel>& modules(void) const {
  2292. return m_modules;
  2293. }
  2294. void setFromArgs(const base::utils::CommandLineArgs* commandLineArgs);
  2295. /// @brief Whether or not vModules enabled
  2296. inline bool vModulesEnabled(void) {
  2297. return !base::utils::hasFlag(LoggingFlag::DisableVModules, *m_pFlags);
  2298. }
  2299. private:
  2300. base::type::VerboseLevel m_level;
  2301. base::type::EnumType* m_pFlags;
  2302. std::map<std::string, base::type::VerboseLevel> m_modules;
  2303. };
  2304. } // namespace base
  2305. class LogMessage {
  2306. public:
  2307. LogMessage(Level level, const std::string& file, base::type::LineNumber line, const std::string& func,
  2308. base::type::VerboseLevel verboseLevel, Logger* logger) :
  2309. m_level(level), m_file(file), m_line(line), m_func(func),
  2310. m_verboseLevel(verboseLevel), m_logger(logger), m_message(logger->stream().str()) {
  2311. }
  2312. inline Level level(void) const {
  2313. return m_level;
  2314. }
  2315. inline const std::string& file(void) const {
  2316. return m_file;
  2317. }
  2318. inline base::type::LineNumber line(void) const {
  2319. return m_line;
  2320. }
  2321. inline const std::string& func(void) const {
  2322. return m_func;
  2323. }
  2324. inline base::type::VerboseLevel verboseLevel(void) const {
  2325. return m_verboseLevel;
  2326. }
  2327. inline Logger* logger(void) const {
  2328. return m_logger;
  2329. }
  2330. inline const base::type::string_t& message(void) const {
  2331. return m_message;
  2332. }
  2333. private:
  2334. Level m_level;
  2335. std::string m_file;
  2336. base::type::LineNumber m_line;
  2337. std::string m_func;
  2338. base::type::VerboseLevel m_verboseLevel;
  2339. Logger* m_logger;
  2340. base::type::string_t m_message;
  2341. };
  2342. namespace base {
  2343. #if ELPP_ASYNC_LOGGING
  2344. class AsyncLogItem {
  2345. public:
  2346. explicit AsyncLogItem(const LogMessage& logMessage, const LogDispatchData& data, const base::type::string_t& logLine)
  2347. : m_logMessage(logMessage), m_dispatchData(data), m_logLine(logLine) {}
  2348. virtual ~AsyncLogItem() {}
  2349. inline LogMessage* logMessage(void) {
  2350. return &m_logMessage;
  2351. }
  2352. inline LogDispatchData* data(void) {
  2353. return &m_dispatchData;
  2354. }
  2355. inline base::type::string_t logLine(void) {
  2356. return m_logLine;
  2357. }
  2358. private:
  2359. LogMessage m_logMessage;
  2360. LogDispatchData m_dispatchData;
  2361. base::type::string_t m_logLine;
  2362. };
  2363. class AsyncLogQueue : public base::threading::ThreadSafe {
  2364. public:
  2365. virtual ~AsyncLogQueue() {
  2366. ELPP_INTERNAL_INFO(6, "~AsyncLogQueue");
  2367. }
  2368. inline AsyncLogItem next(void) {
  2369. base::threading::ScopedLock scopedLock(lock());
  2370. AsyncLogItem result = m_queue.front();
  2371. m_queue.pop();
  2372. return result;
  2373. }
  2374. inline void push(const AsyncLogItem& item) {
  2375. base::threading::ScopedLock scopedLock(lock());
  2376. m_queue.push(item);
  2377. }
  2378. inline void pop(void) {
  2379. base::threading::ScopedLock scopedLock(lock());
  2380. m_queue.pop();
  2381. }
  2382. inline AsyncLogItem front(void) {
  2383. base::threading::ScopedLock scopedLock(lock());
  2384. return m_queue.front();
  2385. }
  2386. inline bool empty(void) {
  2387. base::threading::ScopedLock scopedLock(lock());
  2388. return m_queue.empty();
  2389. }
  2390. private:
  2391. std::queue<AsyncLogItem> m_queue;
  2392. };
  2393. class IWorker {
  2394. public:
  2395. virtual ~IWorker() {}
  2396. virtual void start() = 0;
  2397. };
  2398. #endif // ELPP_ASYNC_LOGGING
  2399. /// @brief Easylogging++ management storage
  2400. class Storage : base::NoCopy, public base::threading::ThreadSafe {
  2401. public:
  2402. #if ELPP_ASYNC_LOGGING
  2403. Storage(const LogBuilderPtr& defaultLogBuilder, base::IWorker* asyncDispatchWorker);
  2404. #else
  2405. explicit Storage(const LogBuilderPtr& defaultLogBuilder);
  2406. #endif // ELPP_ASYNC_LOGGING
  2407. virtual ~Storage(void);
  2408. inline bool validateEveryNCounter(const char* filename, base::type::LineNumber lineNumber, std::size_t occasion) {
  2409. return hitCounters()->validateEveryN(filename, lineNumber, occasion);
  2410. }
  2411. inline bool validateAfterNCounter(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
  2412. return hitCounters()->validateAfterN(filename, lineNumber, n);
  2413. }
  2414. inline bool validateNTimesCounter(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
  2415. return hitCounters()->validateNTimes(filename, lineNumber, n);
  2416. }
  2417. inline base::RegisteredHitCounters* hitCounters(void) const {
  2418. return m_registeredHitCounters;
  2419. }
  2420. inline base::RegisteredLoggers* registeredLoggers(void) const {
  2421. return m_registeredLoggers;
  2422. }
  2423. inline base::VRegistry* vRegistry(void) const {
  2424. return m_vRegistry;
  2425. }
  2426. #if ELPP_ASYNC_LOGGING
  2427. inline base::AsyncLogQueue* asyncLogQueue(void) const {
  2428. return m_asyncLogQueue;
  2429. }
  2430. #endif // ELPP_ASYNC_LOGGING
  2431. inline const base::utils::CommandLineArgs* commandLineArgs(void) const {
  2432. return &m_commandLineArgs;
  2433. }
  2434. inline void addFlag(LoggingFlag flag) {
  2435. base::utils::addFlag(flag, &m_flags);
  2436. }
  2437. inline void removeFlag(LoggingFlag flag) {
  2438. base::utils::removeFlag(flag, &m_flags);
  2439. }
  2440. inline bool hasFlag(LoggingFlag flag) const {
  2441. return base::utils::hasFlag(flag, m_flags);
  2442. }
  2443. inline base::type::EnumType flags(void) const {
  2444. return m_flags;
  2445. }
  2446. inline void setFlags(base::type::EnumType flags) {
  2447. m_flags = flags;
  2448. }
  2449. inline void setPreRollOutCallback(const PreRollOutCallback& callback) {
  2450. m_preRollOutCallback = callback;
  2451. }
  2452. inline void unsetPreRollOutCallback(void) {
  2453. m_preRollOutCallback = base::defaultPreRollOutCallback;
  2454. }
  2455. inline PreRollOutCallback& preRollOutCallback(void) {
  2456. return m_preRollOutCallback;
  2457. }
  2458. bool hasCustomFormatSpecifier(const char* formatSpecifier);
  2459. void installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier);
  2460. bool uninstallCustomFormatSpecifier(const char* formatSpecifier);
  2461. const std::vector<CustomFormatSpecifier>* customFormatSpecifiers(void) const {
  2462. return &m_customFormatSpecifiers;
  2463. }
  2464. inline void setLoggingLevel(Level level) {
  2465. m_loggingLevel = level;
  2466. }
  2467. template <typename T>
  2468. inline bool installLogDispatchCallback(const std::string& id) {
  2469. return base::utils::Utils::installCallback<T, base::type::LogDispatchCallbackPtr>(id, &m_logDispatchCallbacks);
  2470. }
  2471. template <typename T>
  2472. inline void uninstallLogDispatchCallback(const std::string& id) {
  2473. base::utils::Utils::uninstallCallback<T, base::type::LogDispatchCallbackPtr>(id, &m_logDispatchCallbacks);
  2474. }
  2475. template <typename T>
  2476. inline T* logDispatchCallback(const std::string& id) {
  2477. return base::utils::Utils::callback<T, base::type::LogDispatchCallbackPtr>(id, &m_logDispatchCallbacks);
  2478. }
  2479. #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
  2480. template <typename T>
  2481. inline bool installPerformanceTrackingCallback(const std::string& id) {
  2482. return base::utils::Utils::installCallback<T, base::type::PerformanceTrackingCallbackPtr>(id,
  2483. &m_performanceTrackingCallbacks);
  2484. }
  2485. template <typename T>
  2486. inline void uninstallPerformanceTrackingCallback(const std::string& id) {
  2487. base::utils::Utils::uninstallCallback<T, base::type::PerformanceTrackingCallbackPtr>(id,
  2488. &m_performanceTrackingCallbacks);
  2489. }
  2490. template <typename T>
  2491. inline T* performanceTrackingCallback(const std::string& id) {
  2492. return base::utils::Utils::callback<T, base::type::PerformanceTrackingCallbackPtr>(id, &m_performanceTrackingCallbacks);
  2493. }
  2494. #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
  2495. /// @brief Sets thread name for current thread. Requires std::thread
  2496. inline void setThreadName(const std::string& name) {
  2497. if (name.empty()) return;
  2498. base::threading::ScopedLock scopedLock(lock());
  2499. m_threadNames[base::threading::getCurrentThreadId()] = name;
  2500. }
  2501. inline std::string getThreadName(const std::string& threadId) {
  2502. std::map<std::string, std::string>::const_iterator it = m_threadNames.find(threadId);
  2503. if (it == m_threadNames.end()) {
  2504. return threadId;
  2505. }
  2506. return it->second;
  2507. }
  2508. private:
  2509. base::RegisteredHitCounters* m_registeredHitCounters;
  2510. base::RegisteredLoggers* m_registeredLoggers;
  2511. base::type::EnumType m_flags;
  2512. base::VRegistry* m_vRegistry;
  2513. #if ELPP_ASYNC_LOGGING
  2514. base::AsyncLogQueue* m_asyncLogQueue;
  2515. base::IWorker* m_asyncDispatchWorker;
  2516. #endif // ELPP_ASYNC_LOGGING
  2517. base::utils::CommandLineArgs m_commandLineArgs;
  2518. PreRollOutCallback m_preRollOutCallback;
  2519. std::map<std::string, base::type::LogDispatchCallbackPtr> m_logDispatchCallbacks;
  2520. std::map<std::string, base::type::PerformanceTrackingCallbackPtr> m_performanceTrackingCallbacks;
  2521. std::map<std::string, std::string> m_threadNames;
  2522. std::vector<CustomFormatSpecifier> m_customFormatSpecifiers;
  2523. Level m_loggingLevel;
  2524. friend class el::Helpers;
  2525. friend class el::base::DefaultLogDispatchCallback;
  2526. friend class el::LogBuilder;
  2527. friend class el::base::MessageBuilder;
  2528. friend class el::base::Writer;
  2529. friend class el::base::PerformanceTracker;
  2530. friend class el::base::LogDispatcher;
  2531. void setApplicationArguments(int argc, char** argv);
  2532. inline void setApplicationArguments(int argc, const char** argv) {
  2533. setApplicationArguments(argc, const_cast<char**>(argv));
  2534. }
  2535. };
  2536. extern ELPP_EXPORT base::type::StoragePointer elStorage;
  2537. #define ELPP el::base::elStorage
  2538. class DefaultLogDispatchCallback : public LogDispatchCallback {
  2539. protected:
  2540. void handle(const LogDispatchData* data);
  2541. private:
  2542. const LogDispatchData* m_data;
  2543. void dispatch(base::type::string_t&& logLine);
  2544. };
  2545. #if ELPP_ASYNC_LOGGING
  2546. class AsyncLogDispatchCallback : public LogDispatchCallback {
  2547. protected:
  2548. void handle(const LogDispatchData* data);
  2549. };
  2550. class AsyncDispatchWorker : public base::IWorker, public base::threading::ThreadSafe {
  2551. public:
  2552. AsyncDispatchWorker();
  2553. virtual ~AsyncDispatchWorker();
  2554. bool clean(void);
  2555. void emptyQueue(void);
  2556. virtual void start(void);
  2557. void handle(AsyncLogItem* logItem);
  2558. void run(void);
  2559. void setContinueRunning(bool value) {
  2560. base::threading::ScopedLock scopedLock(m_continueRunningMutex);
  2561. m_continueRunning = value;
  2562. }
  2563. bool continueRunning(void) const {
  2564. return m_continueRunning;
  2565. }
  2566. private:
  2567. std::condition_variable cv;
  2568. bool m_continueRunning;
  2569. base::threading::Mutex m_continueRunningMutex;
  2570. };
  2571. #endif // ELPP_ASYNC_LOGGING
  2572. } // namespace base
  2573. namespace base {
  2574. class DefaultLogBuilder : public LogBuilder {
  2575. public:
  2576. base::type::string_t build(const LogMessage* logMessage, bool appendNewLine) const;
  2577. };
  2578. /// @brief Dispatches log messages
  2579. class LogDispatcher : base::NoCopy {
  2580. public:
  2581. LogDispatcher(bool proceed, LogMessage&& logMessage, base::DispatchAction dispatchAction) :
  2582. m_proceed(proceed),
  2583. m_logMessage(std::move(logMessage)),
  2584. m_dispatchAction(std::move(dispatchAction)) {
  2585. }
  2586. void dispatch(void);
  2587. private:
  2588. bool m_proceed;
  2589. LogMessage m_logMessage;
  2590. base::DispatchAction m_dispatchAction;
  2591. };
  2592. #if defined(ELPP_STL_LOGGING)
  2593. /// @brief Workarounds to write some STL logs
  2594. ///
  2595. /// @detail There is workaround needed to loop through some stl containers. In order to do that, we need iterable containers
  2596. /// of same type and provide iterator interface and pass it on to writeIterator().
  2597. /// Remember, this is passed by value in constructor so that we dont change original containers.
  2598. /// This operation is as expensive as Big-O(std::min(class_.size(), base::consts::kMaxLogPerContainer))
  2599. namespace workarounds {
  2600. /// @brief Abstract IterableContainer template that provides interface for iterable classes of type T
  2601. template <typename T, typename Container>
  2602. class IterableContainer {
  2603. public:
  2604. typedef typename Container::iterator iterator;
  2605. typedef typename Container::const_iterator const_iterator;
  2606. IterableContainer(void) {}
  2607. virtual ~IterableContainer(void) {}
  2608. iterator begin(void) {
  2609. return getContainer().begin();
  2610. }
  2611. iterator end(void) {
  2612. return getContainer().end();
  2613. }
  2614. private:
  2615. virtual Container& getContainer(void) = 0;
  2616. };
  2617. /// @brief Implements IterableContainer and provides iterable std::priority_queue class
  2618. template<typename T, typename Container = std::vector<T>, typename Comparator = std::less<typename Container::value_type>>
  2619. class IterablePriorityQueue : public IterableContainer<T, Container>,
  2620. public std::priority_queue<T, Container, Comparator> {
  2621. public:
  2622. IterablePriorityQueue(std::priority_queue<T, Container, Comparator> queue_) {
  2623. std::size_t count_ = 0;
  2624. while (++count_ < base::consts::kMaxLogPerContainer && !queue_.empty()) {
  2625. this->push(queue_.top());
  2626. queue_.pop();
  2627. }
  2628. }
  2629. private:
  2630. inline Container& getContainer(void) {
  2631. return this->c;
  2632. }
  2633. };
  2634. /// @brief Implements IterableContainer and provides iterable std::queue class
  2635. template<typename T, typename Container = std::deque<T>>
  2636. class IterableQueue : public IterableContainer<T, Container>, public std::queue<T, Container> {
  2637. public:
  2638. IterableQueue(std::queue<T, Container> queue_) {
  2639. std::size_t count_ = 0;
  2640. while (++count_ < base::consts::kMaxLogPerContainer && !queue_.empty()) {
  2641. this->push(queue_.front());
  2642. queue_.pop();
  2643. }
  2644. }
  2645. private:
  2646. inline Container& getContainer(void) {
  2647. return this->c;
  2648. }
  2649. };
  2650. /// @brief Implements IterableContainer and provides iterable std::stack class
  2651. template<typename T, typename Container = std::deque<T>>
  2652. class IterableStack : public IterableContainer<T, Container>, public std::stack<T, Container> {
  2653. public:
  2654. IterableStack(std::stack<T, Container> stack_) {
  2655. std::size_t count_ = 0;
  2656. while (++count_ < base::consts::kMaxLogPerContainer && !stack_.empty()) {
  2657. this->push(stack_.top());
  2658. stack_.pop();
  2659. }
  2660. }
  2661. private:
  2662. inline Container& getContainer(void) {
  2663. return this->c;
  2664. }
  2665. };
  2666. } // namespace workarounds
  2667. #endif // defined(ELPP_STL_LOGGING)
  2668. // Log message builder
  2669. class MessageBuilder {
  2670. public:
  2671. MessageBuilder(void) : m_logger(nullptr), m_containerLogSeperator(ELPP_LITERAL("")) {}
  2672. void initialize(Logger* logger);
  2673. # define ELPP_SIMPLE_LOG(LOG_TYPE)\
  2674. MessageBuilder& operator<<(LOG_TYPE msg) {\
  2675. m_logger->stream() << msg;\
  2676. if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) {\
  2677. m_logger->stream() << " ";\
  2678. }\
  2679. return *this;\
  2680. }
  2681. inline MessageBuilder& operator<<(const std::string& msg) {
  2682. return operator<<(msg.c_str());
  2683. }
  2684. ELPP_SIMPLE_LOG(char)
  2685. ELPP_SIMPLE_LOG(bool)
  2686. ELPP_SIMPLE_LOG(signed short)
  2687. ELPP_SIMPLE_LOG(unsigned short)
  2688. ELPP_SIMPLE_LOG(signed int)
  2689. ELPP_SIMPLE_LOG(unsigned int)
  2690. ELPP_SIMPLE_LOG(signed long)
  2691. ELPP_SIMPLE_LOG(unsigned long)
  2692. ELPP_SIMPLE_LOG(float)
  2693. ELPP_SIMPLE_LOG(double)
  2694. ELPP_SIMPLE_LOG(char*)
  2695. ELPP_SIMPLE_LOG(const char*)
  2696. ELPP_SIMPLE_LOG(const void*)
  2697. ELPP_SIMPLE_LOG(long double)
  2698. inline MessageBuilder& operator<<(const std::wstring& msg) {
  2699. return operator<<(msg.c_str());
  2700. }
  2701. MessageBuilder& operator<<(const wchar_t* msg);
  2702. // ostream manipulators
  2703. inline MessageBuilder& operator<<(std::ostream& (*OStreamMani)(std::ostream&)) {
  2704. m_logger->stream() << OStreamMani;
  2705. return *this;
  2706. }
  2707. #define ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(temp) \
  2708. template <typename T> \
  2709. inline MessageBuilder& operator<<(const temp<T>& template_inst) { \
  2710. return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \
  2711. }
  2712. #define ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(temp) \
  2713. template <typename T1, typename T2> \
  2714. inline MessageBuilder& operator<<(const temp<T1, T2>& template_inst) { \
  2715. return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \
  2716. }
  2717. #define ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(temp) \
  2718. template <typename T1, typename T2, typename T3> \
  2719. inline MessageBuilder& operator<<(const temp<T1, T2, T3>& template_inst) { \
  2720. return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \
  2721. }
  2722. #define ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(temp) \
  2723. template <typename T1, typename T2, typename T3, typename T4> \
  2724. inline MessageBuilder& operator<<(const temp<T1, T2, T3, T4>& template_inst) { \
  2725. return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \
  2726. }
  2727. #define ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(temp) \
  2728. template <typename T1, typename T2, typename T3, typename T4, typename T5> \
  2729. inline MessageBuilder& operator<<(const temp<T1, T2, T3, T4, T5>& template_inst) { \
  2730. return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \
  2731. }
  2732. #if defined(ELPP_STL_LOGGING)
  2733. ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::vector)
  2734. ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::list)
  2735. ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::deque)
  2736. ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(std::set)
  2737. ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(std::multiset)
  2738. ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::map)
  2739. ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::multimap)
  2740. template <class T, class Container>
  2741. inline MessageBuilder& operator<<(const std::queue<T, Container>& queue_) {
  2742. base::workarounds::IterableQueue<T, Container> iterableQueue_ =
  2743. static_cast<base::workarounds::IterableQueue<T, Container> >(queue_);
  2744. return writeIterator(iterableQueue_.begin(), iterableQueue_.end(), iterableQueue_.size());
  2745. }
  2746. template <class T, class Container>
  2747. inline MessageBuilder& operator<<(const std::stack<T, Container>& stack_) {
  2748. base::workarounds::IterableStack<T, Container> iterableStack_ =
  2749. static_cast<base::workarounds::IterableStack<T, Container> >(stack_);
  2750. return writeIterator(iterableStack_.begin(), iterableStack_.end(), iterableStack_.size());
  2751. }
  2752. template <class T, class Container, class Comparator>
  2753. inline MessageBuilder& operator<<(const std::priority_queue<T, Container, Comparator>& priorityQueue_) {
  2754. base::workarounds::IterablePriorityQueue<T, Container, Comparator> iterablePriorityQueue_ =
  2755. static_cast<base::workarounds::IterablePriorityQueue<T, Container, Comparator> >(priorityQueue_);
  2756. return writeIterator(iterablePriorityQueue_.begin(), iterablePriorityQueue_.end(), iterablePriorityQueue_.size());
  2757. }
  2758. template <class First, class Second>
  2759. MessageBuilder& operator<<(const std::pair<First, Second>& pair_) {
  2760. m_logger->stream() << ELPP_LITERAL("(");
  2761. operator << (static_cast<First>(pair_.first));
  2762. m_logger->stream() << ELPP_LITERAL(", ");
  2763. operator << (static_cast<Second>(pair_.second));
  2764. m_logger->stream() << ELPP_LITERAL(")");
  2765. return *this;
  2766. }
  2767. template <std::size_t Size>
  2768. MessageBuilder& operator<<(const std::bitset<Size>& bitset_) {
  2769. m_logger->stream() << ELPP_LITERAL("[");
  2770. operator << (bitset_.to_string());
  2771. m_logger->stream() << ELPP_LITERAL("]");
  2772. return *this;
  2773. }
  2774. # if defined(ELPP_LOG_STD_ARRAY)
  2775. template <class T, std::size_t Size>
  2776. inline MessageBuilder& operator<<(const std::array<T, Size>& array) {
  2777. return writeIterator(array.begin(), array.end(), array.size());
  2778. }
  2779. # endif // defined(ELPP_LOG_STD_ARRAY)
  2780. # if defined(ELPP_LOG_UNORDERED_MAP)
  2781. ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(std::unordered_map)
  2782. ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(std::unordered_multimap)
  2783. # endif // defined(ELPP_LOG_UNORDERED_MAP)
  2784. # if defined(ELPP_LOG_UNORDERED_SET)
  2785. ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::unordered_set)
  2786. ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::unordered_multiset)
  2787. # endif // defined(ELPP_LOG_UNORDERED_SET)
  2788. #endif // defined(ELPP_STL_LOGGING)
  2789. #if defined(ELPP_QT_LOGGING)
  2790. inline MessageBuilder& operator<<(const QString& msg) {
  2791. # if defined(ELPP_UNICODE)
  2792. m_logger->stream() << msg.toStdWString();
  2793. # else
  2794. m_logger->stream() << msg.toStdString();
  2795. # endif // defined(ELPP_UNICODE)
  2796. return *this;
  2797. }
  2798. inline MessageBuilder& operator<<(const QByteArray& msg) {
  2799. return operator << (QString(msg));
  2800. }
  2801. inline MessageBuilder& operator<<(const QStringRef& msg) {
  2802. return operator<<(msg.toString());
  2803. }
  2804. inline MessageBuilder& operator<<(qint64 msg) {
  2805. # if defined(ELPP_UNICODE)
  2806. m_logger->stream() << QString::number(msg).toStdWString();
  2807. # else
  2808. m_logger->stream() << QString::number(msg).toStdString();
  2809. # endif // defined(ELPP_UNICODE)
  2810. return *this;
  2811. }
  2812. inline MessageBuilder& operator<<(quint64 msg) {
  2813. # if defined(ELPP_UNICODE)
  2814. m_logger->stream() << QString::number(msg).toStdWString();
  2815. # else
  2816. m_logger->stream() << QString::number(msg).toStdString();
  2817. # endif // defined(ELPP_UNICODE)
  2818. return *this;
  2819. }
  2820. inline MessageBuilder& operator<<(QChar msg) {
  2821. m_logger->stream() << msg.toLatin1();
  2822. return *this;
  2823. }
  2824. inline MessageBuilder& operator<<(const QLatin1String& msg) {
  2825. m_logger->stream() << msg.latin1();
  2826. return *this;
  2827. }
  2828. ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QList)
  2829. ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QVector)
  2830. ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QQueue)
  2831. ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QSet)
  2832. ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QLinkedList)
  2833. ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QStack)
  2834. template <typename First, typename Second>
  2835. MessageBuilder& operator<<(const QPair<First, Second>& pair_) {
  2836. m_logger->stream() << ELPP_LITERAL("(");
  2837. operator << (static_cast<First>(pair_.first));
  2838. m_logger->stream() << ELPP_LITERAL(", ");
  2839. operator << (static_cast<Second>(pair_.second));
  2840. m_logger->stream() << ELPP_LITERAL(")");
  2841. return *this;
  2842. }
  2843. template <typename K, typename V>
  2844. MessageBuilder& operator<<(const QMap<K, V>& map_) {
  2845. m_logger->stream() << ELPP_LITERAL("[");
  2846. QList<K> keys = map_.keys();
  2847. typename QList<K>::const_iterator begin = keys.begin();
  2848. typename QList<K>::const_iterator end = keys.end();
  2849. int max_ = static_cast<int>(base::consts::kMaxLogPerContainer); // to prevent warning
  2850. for (int index_ = 0; begin != end && index_ < max_; ++index_, ++begin) {
  2851. m_logger->stream() << ELPP_LITERAL("(");
  2852. operator << (static_cast<K>(*begin));
  2853. m_logger->stream() << ELPP_LITERAL(", ");
  2854. operator << (static_cast<V>(map_.value(*begin)));
  2855. m_logger->stream() << ELPP_LITERAL(")");
  2856. m_logger->stream() << ((index_ < keys.size() -1) ? m_containerLogSeperator : ELPP_LITERAL(""));
  2857. }
  2858. if (begin != end) {
  2859. m_logger->stream() << ELPP_LITERAL("...");
  2860. }
  2861. m_logger->stream() << ELPP_LITERAL("]");
  2862. return *this;
  2863. }
  2864. template <typename K, typename V>
  2865. inline MessageBuilder& operator<<(const QMultiMap<K, V>& map_) {
  2866. operator << (static_cast<QMap<K, V>>(map_));
  2867. return *this;
  2868. }
  2869. template <typename K, typename V>
  2870. MessageBuilder& operator<<(const QHash<K, V>& hash_) {
  2871. m_logger->stream() << ELPP_LITERAL("[");
  2872. QList<K> keys = hash_.keys();
  2873. typename QList<K>::const_iterator begin = keys.begin();
  2874. typename QList<K>::const_iterator end = keys.end();
  2875. int max_ = static_cast<int>(base::consts::kMaxLogPerContainer); // prevent type warning
  2876. for (int index_ = 0; begin != end && index_ < max_; ++index_, ++begin) {
  2877. m_logger->stream() << ELPP_LITERAL("(");
  2878. operator << (static_cast<K>(*begin));
  2879. m_logger->stream() << ELPP_LITERAL(", ");
  2880. operator << (static_cast<V>(hash_.value(*begin)));
  2881. m_logger->stream() << ELPP_LITERAL(")");
  2882. m_logger->stream() << ((index_ < keys.size() -1) ? m_containerLogSeperator : ELPP_LITERAL(""));
  2883. }
  2884. if (begin != end) {
  2885. m_logger->stream() << ELPP_LITERAL("...");
  2886. }
  2887. m_logger->stream() << ELPP_LITERAL("]");
  2888. return *this;
  2889. }
  2890. template <typename K, typename V>
  2891. inline MessageBuilder& operator<<(const QMultiHash<K, V>& multiHash_) {
  2892. operator << (static_cast<QHash<K, V>>(multiHash_));
  2893. return *this;
  2894. }
  2895. #endif // defined(ELPP_QT_LOGGING)
  2896. #if defined(ELPP_BOOST_LOGGING)
  2897. ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::vector)
  2898. ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::stable_vector)
  2899. ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::list)
  2900. ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::deque)
  2901. ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(boost::container::map)
  2902. ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(boost::container::flat_map)
  2903. ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(boost::container::set)
  2904. ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(boost::container::flat_set)
  2905. #endif // defined(ELPP_BOOST_LOGGING)
  2906. /// @brief Macro used internally that can be used externally to make containers easylogging++ friendly
  2907. ///
  2908. /// @detail This macro expands to write an ostream& operator<< for container. This container is expected to
  2909. /// have begin() and end() methods that return respective iterators
  2910. /// @param ContainerType Type of container e.g, MyList from WX_DECLARE_LIST(int, MyList); in wxwidgets
  2911. /// @param SizeMethod Method used to get size of container.
  2912. /// @param ElementInstance Instance of element to be fed out. Insance name is "elem". See WXELPP_ENABLED macro
  2913. /// for an example usage
  2914. #define MAKE_CONTAINERELPP_FRIENDLY(ContainerType, SizeMethod, ElementInstance) \
  2915. el::base::type::ostream_t& operator<<(el::base::type::ostream_t& ss, const ContainerType& container) {\
  2916. const el::base::type::char_t* sep = ELPP->hasFlag(el::LoggingFlag::NewLineForContainer) ? \
  2917. ELPP_LITERAL("\n ") : ELPP_LITERAL(", ");\
  2918. ContainerType::const_iterator elem = container.begin();\
  2919. ContainerType::const_iterator endElem = container.end();\
  2920. std::size_t size_ = container.SizeMethod; \
  2921. ss << ELPP_LITERAL("[");\
  2922. for (std::size_t i = 0; elem != endElem && i < el::base::consts::kMaxLogPerContainer; ++i, ++elem) { \
  2923. ss << ElementInstance;\
  2924. ss << ((i < size_ - 1) ? sep : ELPP_LITERAL(""));\
  2925. }\
  2926. if (elem != endElem) {\
  2927. ss << ELPP_LITERAL("...");\
  2928. }\
  2929. ss << ELPP_LITERAL("]");\
  2930. return ss;\
  2931. }
  2932. #if defined(ELPP_WXWIDGETS_LOGGING)
  2933. ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(wxVector)
  2934. # define ELPP_WX_PTR_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), *(*elem))
  2935. # define ELPP_WX_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), (*elem))
  2936. # define ELPP_WX_HASH_MAP_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), \
  2937. ELPP_LITERAL("(") << elem->first << ELPP_LITERAL(", ") << elem->second << ELPP_LITERAL(")")
  2938. #else
  2939. # define ELPP_WX_PTR_ENABLED(ContainerType)
  2940. # define ELPP_WX_ENABLED(ContainerType)
  2941. # define ELPP_WX_HASH_MAP_ENABLED(ContainerType)
  2942. #endif // defined(ELPP_WXWIDGETS_LOGGING)
  2943. // Other classes
  2944. template <class Class>
  2945. ELPP_SIMPLE_LOG(const Class&)
  2946. #undef ELPP_SIMPLE_LOG
  2947. #undef ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG
  2948. #undef ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG
  2949. #undef ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG
  2950. #undef ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG
  2951. #undef ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG
  2952. private:
  2953. Logger* m_logger;
  2954. const base::type::char_t* m_containerLogSeperator;
  2955. template<class Iterator>
  2956. MessageBuilder& writeIterator(Iterator begin_, Iterator end_, std::size_t size_) {
  2957. m_logger->stream() << ELPP_LITERAL("[");
  2958. for (std::size_t i = 0; begin_ != end_ && i < base::consts::kMaxLogPerContainer; ++i, ++begin_) {
  2959. operator << (*begin_);
  2960. m_logger->stream() << ((i < size_ - 1) ? m_containerLogSeperator : ELPP_LITERAL(""));
  2961. }
  2962. if (begin_ != end_) {
  2963. m_logger->stream() << ELPP_LITERAL("...");
  2964. }
  2965. m_logger->stream() << ELPP_LITERAL("]");
  2966. if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) {
  2967. m_logger->stream() << " ";
  2968. }
  2969. return *this;
  2970. }
  2971. };
  2972. /// @brief Writes nothing - Used when certain log is disabled
  2973. class NullWriter : base::NoCopy {
  2974. public:
  2975. NullWriter(void) {}
  2976. // Null manipulator
  2977. inline NullWriter& operator<<(std::ostream& (*)(std::ostream&)) {
  2978. return *this;
  2979. }
  2980. template <typename T>
  2981. inline NullWriter& operator<<(const T&) {
  2982. return *this;
  2983. }
  2984. inline operator bool() {
  2985. return true;
  2986. }
  2987. };
  2988. /// @brief Main entry point of each logging
  2989. class Writer : base::NoCopy {
  2990. public:
  2991. Writer(Level level, const char* file, base::type::LineNumber line,
  2992. const char* func, base::DispatchAction dispatchAction = base::DispatchAction::NormalLog,
  2993. base::type::VerboseLevel verboseLevel = 0) :
  2994. m_level(level), m_file(file), m_line(line), m_func(func), m_verboseLevel(verboseLevel),
  2995. m_logger(nullptr), m_proceed(false), m_dispatchAction(dispatchAction) {
  2996. }
  2997. virtual ~Writer(void) {
  2998. processDispatch();
  2999. }
  3000. template <typename T>
  3001. inline Writer& operator<<(const T& log) {
  3002. #if ELPP_LOGGING_ENABLED
  3003. if (m_proceed) {
  3004. m_messageBuilder << log;
  3005. }
  3006. #endif // ELPP_LOGGING_ENABLED
  3007. return *this;
  3008. }
  3009. inline Writer& operator<<(std::ostream& (*log)(std::ostream&)) {
  3010. #if ELPP_LOGGING_ENABLED
  3011. if (m_proceed) {
  3012. m_messageBuilder << log;
  3013. }
  3014. #endif // ELPP_LOGGING_ENABLED
  3015. return *this;
  3016. }
  3017. inline operator bool() {
  3018. return true;
  3019. }
  3020. Writer& construct(Logger* logger, bool needLock = true);
  3021. Writer& construct(int count, const char* loggerIds, ...);
  3022. protected:
  3023. Level m_level;
  3024. const char* m_file;
  3025. const base::type::LineNumber m_line;
  3026. const char* m_func;
  3027. base::type::VerboseLevel m_verboseLevel;
  3028. Logger* m_logger;
  3029. bool m_proceed;
  3030. base::MessageBuilder m_messageBuilder;
  3031. base::DispatchAction m_dispatchAction;
  3032. std::vector<std::string> m_loggerIds;
  3033. friend class el::Helpers;
  3034. void initializeLogger(const std::string& loggerId, bool lookup = true, bool needLock = true);
  3035. void processDispatch();
  3036. void triggerDispatch(void);
  3037. };
  3038. class PErrorWriter : public base::Writer {
  3039. public:
  3040. PErrorWriter(Level level, const char* file, base::type::LineNumber line,
  3041. const char* func, base::DispatchAction dispatchAction = base::DispatchAction::NormalLog,
  3042. base::type::VerboseLevel verboseLevel = 0) :
  3043. base::Writer(level, file, line, func, dispatchAction, verboseLevel) {
  3044. }
  3045. virtual ~PErrorWriter(void);
  3046. };
  3047. } // namespace base
  3048. // Logging from Logger class. Why this is here? Because we have Storage and Writer class available
  3049. #if ELPP_VARIADIC_TEMPLATES_SUPPORTED
  3050. template <typename T, typename... Args>
  3051. void Logger::log_(Level level, int vlevel, const char* s, const T& value, const Args&... args) {
  3052. base::MessageBuilder b;
  3053. b.initialize(this);
  3054. while (*s) {
  3055. if (*s == base::consts::kFormatSpecifierChar) {
  3056. if (*(s + 1) == base::consts::kFormatSpecifierChar) {
  3057. ++s;
  3058. } else {
  3059. if (*(s + 1) == base::consts::kFormatSpecifierCharValue) {
  3060. ++s;
  3061. b << value;
  3062. log_(level, vlevel, ++s, args...);
  3063. return;
  3064. }
  3065. }
  3066. }
  3067. b << *s++;
  3068. }
  3069. ELPP_INTERNAL_ERROR("Too many arguments provided. Unable to handle. Please provide more format specifiers", false);
  3070. }
  3071. template <typename T>
  3072. void Logger::log_(Level level, int vlevel, const T& log) {
  3073. if (level == Level::Verbose) {
  3074. if (ELPP->vRegistry()->allowed(vlevel, __FILE__)) {
  3075. base::Writer(Level::Verbose, "FILE", 0, "FUNCTION",
  3076. base::DispatchAction::NormalLog, vlevel).construct(this, false) << log;
  3077. } else {
  3078. stream().str(ELPP_LITERAL(""));
  3079. releaseLock();
  3080. }
  3081. } else {
  3082. base::Writer(level, "FILE", 0, "FUNCTION").construct(this, false) << log;
  3083. }
  3084. }
  3085. template <typename T, typename... Args>
  3086. inline void Logger::log(Level level, const char* s, const T& value, const Args&... args) {
  3087. acquireLock(); // released in Writer!
  3088. log_(level, 0, s, value, args...);
  3089. }
  3090. template <typename T>
  3091. inline void Logger::log(Level level, const T& log) {
  3092. acquireLock(); // released in Writer!
  3093. log_(level, 0, log);
  3094. }
  3095. # if ELPP_VERBOSE_LOG
  3096. template <typename T, typename... Args>
  3097. inline void Logger::verbose(int vlevel, const char* s, const T& value, const Args&... args) {
  3098. acquireLock(); // released in Writer!
  3099. log_(el::Level::Verbose, vlevel, s, value, args...);
  3100. }
  3101. template <typename T>
  3102. inline void Logger::verbose(int vlevel, const T& log) {
  3103. acquireLock(); // released in Writer!
  3104. log_(el::Level::Verbose, vlevel, log);
  3105. }
  3106. # else
  3107. template <typename T, typename... Args>
  3108. inline void Logger::verbose(int, const char*, const T&, const Args&...) {
  3109. return;
  3110. }
  3111. template <typename T>
  3112. inline void Logger::verbose(int, const T&) {
  3113. return;
  3114. }
  3115. # endif // ELPP_VERBOSE_LOG
  3116. # define LOGGER_LEVEL_WRITERS(FUNCTION_NAME, LOG_LEVEL)\
  3117. template <typename T, typename... Args>\
  3118. inline void Logger::FUNCTION_NAME(const char* s, const T& value, const Args&... args) {\
  3119. log(LOG_LEVEL, s, value, args...);\
  3120. }\
  3121. template <typename T>\
  3122. inline void Logger::FUNCTION_NAME(const T& value) {\
  3123. log(LOG_LEVEL, value);\
  3124. }
  3125. # define LOGGER_LEVEL_WRITERS_DISABLED(FUNCTION_NAME, LOG_LEVEL)\
  3126. template <typename T, typename... Args>\
  3127. inline void Logger::FUNCTION_NAME(const char*, const T&, const Args&...) {\
  3128. return;\
  3129. }\
  3130. template <typename T>\
  3131. inline void Logger::FUNCTION_NAME(const T&) {\
  3132. return;\
  3133. }
  3134. # if ELPP_INFO_LOG
  3135. LOGGER_LEVEL_WRITERS(info, Level::Info)
  3136. # else
  3137. LOGGER_LEVEL_WRITERS_DISABLED(info, Level::Info)
  3138. # endif // ELPP_INFO_LOG
  3139. # if ELPP_DEBUG_LOG
  3140. LOGGER_LEVEL_WRITERS(debug, Level::Debug)
  3141. # else
  3142. LOGGER_LEVEL_WRITERS_DISABLED(debug, Level::Debug)
  3143. # endif // ELPP_DEBUG_LOG
  3144. # if ELPP_WARNING_LOG
  3145. LOGGER_LEVEL_WRITERS(warn, Level::Warning)
  3146. # else
  3147. LOGGER_LEVEL_WRITERS_DISABLED(warn, Level::Warning)
  3148. # endif // ELPP_WARNING_LOG
  3149. # if ELPP_ERROR_LOG
  3150. LOGGER_LEVEL_WRITERS(error, Level::Error)
  3151. # else
  3152. LOGGER_LEVEL_WRITERS_DISABLED(error, Level::Error)
  3153. # endif // ELPP_ERROR_LOG
  3154. # if ELPP_FATAL_LOG
  3155. LOGGER_LEVEL_WRITERS(fatal, Level::Fatal)
  3156. # else
  3157. LOGGER_LEVEL_WRITERS_DISABLED(fatal, Level::Fatal)
  3158. # endif // ELPP_FATAL_LOG
  3159. # if ELPP_TRACE_LOG
  3160. LOGGER_LEVEL_WRITERS(trace, Level::Trace)
  3161. # else
  3162. LOGGER_LEVEL_WRITERS_DISABLED(trace, Level::Trace)
  3163. # endif // ELPP_TRACE_LOG
  3164. # undef LOGGER_LEVEL_WRITERS
  3165. # undef LOGGER_LEVEL_WRITERS_DISABLED
  3166. #endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED
  3167. #if ELPP_COMPILER_MSVC
  3168. # define ELPP_VARIADIC_FUNC_MSVC(variadicFunction, variadicArgs) variadicFunction variadicArgs
  3169. # define ELPP_VARIADIC_FUNC_MSVC_RUN(variadicFunction, ...) ELPP_VARIADIC_FUNC_MSVC(variadicFunction, (__VA_ARGS__))
  3170. # define el_getVALength(...) ELPP_VARIADIC_FUNC_MSVC_RUN(el_resolveVALength, 0, ## __VA_ARGS__,\
  3171. 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
  3172. #else
  3173. # if ELPP_COMPILER_CLANG
  3174. # define el_getVALength(...) el_resolveVALength(0, __VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
  3175. # else
  3176. # define el_getVALength(...) el_resolveVALength(0, ## __VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
  3177. # endif // ELPP_COMPILER_CLANG
  3178. #endif // ELPP_COMPILER_MSVC
  3179. #define el_resolveVALength(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  3180. #define ELPP_WRITE_LOG(writer, level, dispatchAction, ...) \
  3181. writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
  3182. #define ELPP_WRITE_LOG_IF(writer, condition, level, dispatchAction, ...) if (condition) \
  3183. writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
  3184. #define ELPP_WRITE_LOG_EVERY_N(writer, occasion, level, dispatchAction, ...) \
  3185. ELPP->validateEveryNCounter(__FILE__, __LINE__, occasion) && \
  3186. writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
  3187. #define ELPP_WRITE_LOG_AFTER_N(writer, n, level, dispatchAction, ...) \
  3188. ELPP->validateAfterNCounter(__FILE__, __LINE__, n) && \
  3189. writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
  3190. #define ELPP_WRITE_LOG_N_TIMES(writer, n, level, dispatchAction, ...) \
  3191. ELPP->validateNTimesCounter(__FILE__, __LINE__, n) && \
  3192. writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
  3193. #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
  3194. class PerformanceTrackingData {
  3195. public:
  3196. enum class DataType : base::type::EnumType {
  3197. Checkpoint = 1, Complete = 2
  3198. };
  3199. // Do not use constructor, will run into multiple definition error, use init(PerformanceTracker*)
  3200. explicit PerformanceTrackingData(DataType dataType) : m_performanceTracker(nullptr),
  3201. m_dataType(dataType), m_firstCheckpoint(false), m_file(""), m_line(0), m_func("") {}
  3202. inline const std::string* blockName(void) const;
  3203. inline const struct timeval* startTime(void) const;
  3204. inline const struct timeval* endTime(void) const;
  3205. inline const struct timeval* lastCheckpointTime(void) const;
  3206. inline const base::PerformanceTracker* performanceTracker(void) const {
  3207. return m_performanceTracker;
  3208. }
  3209. inline PerformanceTrackingData::DataType dataType(void) const {
  3210. return m_dataType;
  3211. }
  3212. inline bool firstCheckpoint(void) const {
  3213. return m_firstCheckpoint;
  3214. }
  3215. inline std::string checkpointId(void) const {
  3216. return m_checkpointId;
  3217. }
  3218. inline const char* file(void) const {
  3219. return m_file;
  3220. }
  3221. inline base::type::LineNumber line(void) const {
  3222. return m_line;
  3223. }
  3224. inline const char* func(void) const {
  3225. return m_func;
  3226. }
  3227. inline const base::type::string_t* formattedTimeTaken() const {
  3228. return &m_formattedTimeTaken;
  3229. }
  3230. inline const std::string& loggerId(void) const;
  3231. private:
  3232. base::PerformanceTracker* m_performanceTracker;
  3233. base::type::string_t m_formattedTimeTaken;
  3234. PerformanceTrackingData::DataType m_dataType;
  3235. bool m_firstCheckpoint;
  3236. std::string m_checkpointId;
  3237. const char* m_file;
  3238. base::type::LineNumber m_line;
  3239. const char* m_func;
  3240. inline void init(base::PerformanceTracker* performanceTracker, bool firstCheckpoint = false) {
  3241. m_performanceTracker = performanceTracker;
  3242. m_firstCheckpoint = firstCheckpoint;
  3243. }
  3244. friend class el::base::PerformanceTracker;
  3245. };
  3246. namespace base {
  3247. /// @brief Represents performanceTracker block of code that conditionally adds performance status to log
  3248. /// either when goes outside the scope of when checkpoint() is called
  3249. class PerformanceTracker : public base::threading::ThreadSafe, public Loggable {
  3250. public:
  3251. PerformanceTracker(const std::string& blockName,
  3252. base::TimestampUnit timestampUnit = base::TimestampUnit::Millisecond,
  3253. const std::string& loggerId = std::string(el::base::consts::kPerformanceLoggerId),
  3254. bool scopedLog = true, Level level = base::consts::kPerformanceTrackerDefaultLevel);
  3255. /// @brief Copy constructor
  3256. PerformanceTracker(const PerformanceTracker& t) :
  3257. m_blockName(t.m_blockName), m_timestampUnit(t.m_timestampUnit), m_loggerId(t.m_loggerId), m_scopedLog(t.m_scopedLog),
  3258. m_level(t.m_level), m_hasChecked(t.m_hasChecked), m_lastCheckpointId(t.m_lastCheckpointId), m_enabled(t.m_enabled),
  3259. m_startTime(t.m_startTime), m_endTime(t.m_endTime), m_lastCheckpointTime(t.m_lastCheckpointTime) {
  3260. }
  3261. virtual ~PerformanceTracker(void);
  3262. /// @brief A checkpoint for current performanceTracker block.
  3263. void checkpoint(const std::string& id = std::string(), const char* file = __FILE__,
  3264. base::type::LineNumber line = __LINE__,
  3265. const char* func = "");
  3266. inline Level level(void) const {
  3267. return m_level;
  3268. }
  3269. private:
  3270. std::string m_blockName;
  3271. base::TimestampUnit m_timestampUnit;
  3272. std::string m_loggerId;
  3273. bool m_scopedLog;
  3274. Level m_level;
  3275. bool m_hasChecked;
  3276. std::string m_lastCheckpointId;
  3277. bool m_enabled;
  3278. struct timeval m_startTime, m_endTime, m_lastCheckpointTime;
  3279. PerformanceTracker(void);
  3280. friend class el::PerformanceTrackingData;
  3281. friend class base::DefaultPerformanceTrackingCallback;
  3282. const inline base::type::string_t getFormattedTimeTaken() const {
  3283. return getFormattedTimeTaken(m_startTime);
  3284. }
  3285. const base::type::string_t getFormattedTimeTaken(struct timeval startTime) const;
  3286. virtual inline void log(el::base::type::ostream_t& os) const {
  3287. os << getFormattedTimeTaken();
  3288. }
  3289. };
  3290. class DefaultPerformanceTrackingCallback : public PerformanceTrackingCallback {
  3291. protected:
  3292. void handle(const PerformanceTrackingData* data) {
  3293. m_data = data;
  3294. base::type::stringstream_t ss;
  3295. if (m_data->dataType() == PerformanceTrackingData::DataType::Complete) {
  3296. ss << ELPP_LITERAL("Executed [") << m_data->blockName()->c_str() << ELPP_LITERAL("] in [") <<
  3297. *m_data->formattedTimeTaken() << ELPP_LITERAL("]");
  3298. } else {
  3299. ss << ELPP_LITERAL("Performance checkpoint");
  3300. if (!m_data->checkpointId().empty()) {
  3301. ss << ELPP_LITERAL(" [") << m_data->checkpointId().c_str() << ELPP_LITERAL("]");
  3302. }
  3303. ss << ELPP_LITERAL(" for block [") << m_data->blockName()->c_str() << ELPP_LITERAL("] : [") <<
  3304. *m_data->performanceTracker();
  3305. if (!ELPP->hasFlag(LoggingFlag::DisablePerformanceTrackingCheckpointComparison)
  3306. && m_data->performanceTracker()->m_hasChecked) {
  3307. ss << ELPP_LITERAL(" ([") << *m_data->formattedTimeTaken() << ELPP_LITERAL("] from ");
  3308. if (m_data->performanceTracker()->m_lastCheckpointId.empty()) {
  3309. ss << ELPP_LITERAL("last checkpoint");
  3310. } else {
  3311. ss << ELPP_LITERAL("checkpoint '") << m_data->performanceTracker()->m_lastCheckpointId.c_str() << ELPP_LITERAL("'");
  3312. }
  3313. ss << ELPP_LITERAL(")]");
  3314. } else {
  3315. ss << ELPP_LITERAL("]");
  3316. }
  3317. }
  3318. el::base::Writer(m_data->performanceTracker()->level(), m_data->file(), m_data->line(), m_data->func()).construct(1,
  3319. m_data->loggerId().c_str()) << ss.str();
  3320. }
  3321. private:
  3322. const PerformanceTrackingData* m_data;
  3323. };
  3324. } // namespace base
  3325. inline const std::string* PerformanceTrackingData::blockName() const {
  3326. return const_cast<const std::string*>(&m_performanceTracker->m_blockName);
  3327. }
  3328. inline const struct timeval* PerformanceTrackingData::startTime() const {
  3329. return const_cast<const struct timeval*>(&m_performanceTracker->m_startTime);
  3330. }
  3331. inline const struct timeval* PerformanceTrackingData::endTime() const {
  3332. return const_cast<const struct timeval*>(&m_performanceTracker->m_endTime);
  3333. }
  3334. inline const struct timeval* PerformanceTrackingData::lastCheckpointTime() const {
  3335. return const_cast<const struct timeval*>(&m_performanceTracker->m_lastCheckpointTime);
  3336. }
  3337. inline const std::string& PerformanceTrackingData::loggerId(void) const {
  3338. return m_performanceTracker->m_loggerId;
  3339. }
  3340. #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
  3341. namespace base {
  3342. /// @brief Contains some internal debugging tools like crash handler and stack tracer
  3343. namespace debug {
  3344. #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
  3345. class StackTrace : base::NoCopy {
  3346. public:
  3347. static const unsigned int kMaxStack = 64;
  3348. static const unsigned int kStackStart = 2; // We want to skip c'tor and StackTrace::generateNew()
  3349. class StackTraceEntry {
  3350. public:
  3351. StackTraceEntry(std::size_t index, const char* loc, const char* demang, const char* hex, const char* addr);
  3352. StackTraceEntry(std::size_t index, char* loc) :
  3353. m_index(index),
  3354. m_location(loc) {
  3355. }
  3356. std::size_t m_index;
  3357. std::string m_location;
  3358. std::string m_demangled;
  3359. std::string m_hex;
  3360. std::string m_addr;
  3361. friend std::ostream& operator<<(std::ostream& ss, const StackTraceEntry& si);
  3362. private:
  3363. StackTraceEntry(void);
  3364. };
  3365. StackTrace(void) {
  3366. generateNew();
  3367. }
  3368. virtual ~StackTrace(void) {
  3369. }
  3370. inline std::vector<StackTraceEntry>& getLatestStack(void) {
  3371. return m_stack;
  3372. }
  3373. friend std::ostream& operator<<(std::ostream& os, const StackTrace& st);
  3374. private:
  3375. std::vector<StackTraceEntry> m_stack;
  3376. void generateNew(void);
  3377. };
  3378. /// @brief Handles unexpected crashes
  3379. class CrashHandler : base::NoCopy {
  3380. public:
  3381. typedef void (*Handler)(int);
  3382. explicit CrashHandler(bool useDefault);
  3383. explicit CrashHandler(const Handler& cHandler) {
  3384. setHandler(cHandler);
  3385. }
  3386. void setHandler(const Handler& cHandler);
  3387. private:
  3388. Handler m_handler;
  3389. };
  3390. #else
  3391. class CrashHandler {
  3392. public:
  3393. explicit CrashHandler(bool) {}
  3394. };
  3395. #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
  3396. } // namespace debug
  3397. } // namespace base
  3398. extern base::debug::CrashHandler elCrashHandler;
  3399. #define MAKE_LOGGABLE(ClassType, ClassInstance, OutputStreamInstance) \
  3400. el::base::type::ostream_t& operator<<(el::base::type::ostream_t& OutputStreamInstance, const ClassType& ClassInstance)
  3401. /// @brief Initializes syslog with process ID, options and facility. calls closelog() on d'tor
  3402. class SysLogInitializer {
  3403. public:
  3404. SysLogInitializer(const char* processIdent, int options = 0, int facility = 0) {
  3405. #if defined(ELPP_SYSLOG)
  3406. openlog(processIdent, options, facility);
  3407. #else
  3408. ELPP_UNUSED(processIdent);
  3409. ELPP_UNUSED(options);
  3410. ELPP_UNUSED(facility);
  3411. #endif // defined(ELPP_SYSLOG)
  3412. }
  3413. virtual ~SysLogInitializer(void) {
  3414. #if defined(ELPP_SYSLOG)
  3415. closelog();
  3416. #endif // defined(ELPP_SYSLOG)
  3417. }
  3418. };
  3419. #define ELPP_INITIALIZE_SYSLOG(id, opt, fac) el::SysLogInitializer elSyslogInit(id, opt, fac)
  3420. /// @brief Static helpers for developers
  3421. class Helpers : base::StaticClass {
  3422. public:
  3423. /// @brief Shares logging repository (base::Storage)
  3424. static inline void setStorage(base::type::StoragePointer storage) {
  3425. ELPP = storage;
  3426. }
  3427. /// @return Main storage repository
  3428. static inline base::type::StoragePointer storage() {
  3429. return ELPP;
  3430. }
  3431. /// @brief Sets application arguments and figures out whats active for logging and whats not.
  3432. static inline void setArgs(int argc, char** argv) {
  3433. ELPP->setApplicationArguments(argc, argv);
  3434. }
  3435. /// @copydoc setArgs(int argc, char** argv)
  3436. static inline void setArgs(int argc, const char** argv) {
  3437. ELPP->setApplicationArguments(argc, const_cast<char**>(argv));
  3438. }
  3439. /// @brief Sets thread name for current thread. Requires std::thread
  3440. static inline void setThreadName(const std::string& name) {
  3441. ELPP->setThreadName(name);
  3442. }
  3443. static inline std::string getThreadName() {
  3444. return ELPP->getThreadName(base::threading::getCurrentThreadId());
  3445. }
  3446. #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
  3447. /// @brief Overrides default crash handler and installs custom handler.
  3448. /// @param crashHandler A functor with no return type that takes single int argument.
  3449. /// Handler is a typedef with specification: void (*Handler)(int)
  3450. static inline void setCrashHandler(const el::base::debug::CrashHandler::Handler& crashHandler) {
  3451. el::elCrashHandler.setHandler(crashHandler);
  3452. }
  3453. /// @brief Abort due to crash with signal in parameter
  3454. /// @param sig Crash signal
  3455. static void crashAbort(int sig, const char* sourceFile = "", unsigned int long line = 0);
  3456. /// @brief Logs reason of crash as per sig
  3457. /// @param sig Crash signal
  3458. /// @param stackTraceIfAvailable Includes stack trace if available
  3459. /// @param level Logging level
  3460. /// @param logger Logger to use for logging
  3461. static void logCrashReason(int sig, bool stackTraceIfAvailable = false,
  3462. Level level = Level::Fatal, const char* logger = base::consts::kDefaultLoggerId);
  3463. #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
  3464. /// @brief Installs pre rollout callback, this callback is triggered when log file is about to be rolled out
  3465. /// (can be useful for backing up)
  3466. static inline void installPreRollOutCallback(const PreRollOutCallback& callback) {
  3467. ELPP->setPreRollOutCallback(callback);
  3468. }
  3469. /// @brief Uninstalls pre rollout callback
  3470. static inline void uninstallPreRollOutCallback(void) {
  3471. ELPP->unsetPreRollOutCallback();
  3472. }
  3473. /// @brief Installs post log dispatch callback, this callback is triggered when log is dispatched
  3474. template <typename T>
  3475. static inline bool installLogDispatchCallback(const std::string& id) {
  3476. return ELPP->installLogDispatchCallback<T>(id);
  3477. }
  3478. /// @brief Uninstalls log dispatch callback
  3479. template <typename T>
  3480. static inline void uninstallLogDispatchCallback(const std::string& id) {
  3481. ELPP->uninstallLogDispatchCallback<T>(id);
  3482. }
  3483. template <typename T>
  3484. static inline T* logDispatchCallback(const std::string& id) {
  3485. return ELPP->logDispatchCallback<T>(id);
  3486. }
  3487. #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
  3488. /// @brief Installs post performance tracking callback, this callback is triggered when performance tracking is finished
  3489. template <typename T>
  3490. static inline bool installPerformanceTrackingCallback(const std::string& id) {
  3491. return ELPP->installPerformanceTrackingCallback<T>(id);
  3492. }
  3493. /// @brief Uninstalls post performance tracking handler
  3494. template <typename T>
  3495. static inline void uninstallPerformanceTrackingCallback(const std::string& id) {
  3496. ELPP->uninstallPerformanceTrackingCallback<T>(id);
  3497. }
  3498. template <typename T>
  3499. static inline T* performanceTrackingCallback(const std::string& id) {
  3500. return ELPP->performanceTrackingCallback<T>(id);
  3501. }
  3502. #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
  3503. /// @brief Converts template to std::string - useful for loggable classes to log containers within log(std::ostream&) const
  3504. template <typename T>
  3505. static std::string convertTemplateToStdString(const T& templ) {
  3506. el::Logger* logger =
  3507. ELPP->registeredLoggers()->get(el::base::consts::kDefaultLoggerId);
  3508. if (logger == nullptr) {
  3509. return std::string();
  3510. }
  3511. base::MessageBuilder b;
  3512. b.initialize(logger);
  3513. logger->acquireLock();
  3514. b << templ;
  3515. #if defined(ELPP_UNICODE)
  3516. std::string s = std::string(logger->stream().str().begin(), logger->stream().str().end());
  3517. #else
  3518. std::string s = logger->stream().str();
  3519. #endif // defined(ELPP_UNICODE)
  3520. logger->stream().str(ELPP_LITERAL(""));
  3521. logger->releaseLock();
  3522. return s;
  3523. }
  3524. /// @brief Returns command line arguments (pointer) provided to easylogging++
  3525. static inline const el::base::utils::CommandLineArgs* commandLineArgs(void) {
  3526. return ELPP->commandLineArgs();
  3527. }
  3528. /// @brief Installs user defined format specifier and handler
  3529. static inline void installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) {
  3530. ELPP->installCustomFormatSpecifier(customFormatSpecifier);
  3531. }
  3532. /// @brief Uninstalls user defined format specifier and handler
  3533. static inline bool uninstallCustomFormatSpecifier(const char* formatSpecifier) {
  3534. return ELPP->uninstallCustomFormatSpecifier(formatSpecifier);
  3535. }
  3536. /// @brief Returns true if custom format specifier is installed
  3537. static inline bool hasCustomFormatSpecifier(const char* formatSpecifier) {
  3538. return ELPP->hasCustomFormatSpecifier(formatSpecifier);
  3539. }
  3540. static inline void validateFileRolling(Logger* logger, Level level) {
  3541. if (logger == nullptr) return;
  3542. logger->m_typedConfigurations->validateFileRolling(level, ELPP->preRollOutCallback());
  3543. }
  3544. };
  3545. /// @brief Static helpers to deal with loggers and their configurations
  3546. class Loggers : base::StaticClass {
  3547. public:
  3548. /// @brief Gets existing or registers new logger
  3549. static Logger* getLogger(const std::string& identity, bool registerIfNotAvailable = true);
  3550. /// @brief Changes default log builder for future loggers
  3551. static void setDefaultLogBuilder(el::LogBuilderPtr& logBuilderPtr);
  3552. /// @brief Installs logger registration callback, this callback is triggered when new logger is registered
  3553. template <typename T>
  3554. static inline bool installLoggerRegistrationCallback(const std::string& id) {
  3555. return ELPP->registeredLoggers()->installLoggerRegistrationCallback<T>(id);
  3556. }
  3557. /// @brief Uninstalls log dispatch callback
  3558. template <typename T>
  3559. static inline void uninstallLoggerRegistrationCallback(const std::string& id) {
  3560. ELPP->registeredLoggers()->uninstallLoggerRegistrationCallback<T>(id);
  3561. }
  3562. template <typename T>
  3563. static inline T* loggerRegistrationCallback(const std::string& id) {
  3564. return ELPP->registeredLoggers()->loggerRegistrationCallback<T>(id);
  3565. }
  3566. /// @brief Unregisters logger - use it only when you know what you are doing, you may unregister
  3567. /// loggers initialized / used by third-party libs.
  3568. static bool unregisterLogger(const std::string& identity);
  3569. /// @brief Whether or not logger with id is registered
  3570. static bool hasLogger(const std::string& identity);
  3571. /// @brief Reconfigures specified logger with new configurations
  3572. static Logger* reconfigureLogger(Logger* logger, const Configurations& configurations);
  3573. /// @brief Reconfigures logger with new configurations after looking it up using identity
  3574. static Logger* reconfigureLogger(const std::string& identity, const Configurations& configurations);
  3575. /// @brief Reconfigures logger's single configuration
  3576. static Logger* reconfigureLogger(const std::string& identity, ConfigurationType configurationType,
  3577. const std::string& value);
  3578. /// @brief Reconfigures all the existing loggers with new configurations
  3579. static void reconfigureAllLoggers(const Configurations& configurations);
  3580. /// @brief Reconfigures single configuration for all the loggers
  3581. static inline void reconfigureAllLoggers(ConfigurationType configurationType, const std::string& value) {
  3582. reconfigureAllLoggers(Level::Global, configurationType, value);
  3583. }
  3584. /// @brief Reconfigures single configuration for all the loggers for specified level
  3585. static void reconfigureAllLoggers(Level level, ConfigurationType configurationType,
  3586. const std::string& value);
  3587. /// @brief Sets default configurations. This configuration is used for future (and conditionally for existing) loggers
  3588. static void setDefaultConfigurations(const Configurations& configurations,
  3589. bool reconfigureExistingLoggers = false);
  3590. /// @brief Returns current default
  3591. static const Configurations* defaultConfigurations(void);
  3592. /// @brief Returns log stream reference pointer if needed by user
  3593. static const base::LogStreamsReferenceMap* logStreamsReference(void);
  3594. /// @brief Default typed configuration based on existing defaultConf
  3595. static base::TypedConfigurations defaultTypedConfigurations(void);
  3596. /// @brief Populates all logger IDs in current repository.
  3597. /// @param [out] targetList List of fill up.
  3598. static std::vector<std::string>* populateAllLoggerIds(std::vector<std::string>* targetList);
  3599. /// @brief Sets configurations from global configuration file.
  3600. static void configureFromGlobal(const char* globalConfigurationFilePath);
  3601. /// @brief Configures loggers using command line arg. Ensure you have already set command line args,
  3602. /// @return False if invalid argument or argument with no value provided, true if attempted to configure logger.
  3603. /// If true is returned that does not mean it has been configured successfully, it only means that it
  3604. /// has attempeted to configure logger using configuration file provided in argument
  3605. static bool configureFromArg(const char* argKey);
  3606. /// @brief Flushes all loggers for all levels - Be careful if you dont know how many loggers are registered
  3607. static void flushAll(void);
  3608. /// @brief Adds logging flag used internally.
  3609. static inline void addFlag(LoggingFlag flag) {
  3610. ELPP->addFlag(flag);
  3611. }
  3612. /// @brief Removes logging flag used internally.
  3613. static inline void removeFlag(LoggingFlag flag) {
  3614. ELPP->removeFlag(flag);
  3615. }
  3616. /// @brief Determines whether or not certain flag is active
  3617. static inline bool hasFlag(LoggingFlag flag) {
  3618. return ELPP->hasFlag(flag);
  3619. }
  3620. /// @brief Adds flag and removes it when scope goes out
  3621. class ScopedAddFlag {
  3622. public:
  3623. ScopedAddFlag(LoggingFlag flag) : m_flag(flag) {
  3624. Loggers::addFlag(m_flag);
  3625. }
  3626. ~ScopedAddFlag(void) {
  3627. Loggers::removeFlag(m_flag);
  3628. }
  3629. private:
  3630. LoggingFlag m_flag;
  3631. };
  3632. /// @brief Removes flag and add it when scope goes out
  3633. class ScopedRemoveFlag {
  3634. public:
  3635. ScopedRemoveFlag(LoggingFlag flag) : m_flag(flag) {
  3636. Loggers::removeFlag(m_flag);
  3637. }
  3638. ~ScopedRemoveFlag(void) {
  3639. Loggers::addFlag(m_flag);
  3640. }
  3641. private:
  3642. LoggingFlag m_flag;
  3643. };
  3644. /// @brief Sets hierarchy for logging. Needs to enable logging flag (HierarchicalLogging)
  3645. static void setLoggingLevel(Level level) {
  3646. ELPP->setLoggingLevel(level);
  3647. }
  3648. /// @brief Sets verbose level on the fly
  3649. static void setVerboseLevel(base::type::VerboseLevel level);
  3650. /// @brief Gets current verbose level
  3651. static base::type::VerboseLevel verboseLevel(void);
  3652. /// @brief Sets vmodules as specified (on the fly)
  3653. static void setVModules(const char* modules);
  3654. /// @brief Clears vmodules
  3655. static void clearVModules(void);
  3656. };
  3657. class VersionInfo : base::StaticClass {
  3658. public:
  3659. /// @brief Current version number
  3660. static const std::string version(void);
  3661. /// @brief Release date of current version
  3662. static const std::string releaseDate(void);
  3663. };
  3664. } // namespace el
  3665. #undef VLOG_IS_ON
  3666. /// @brief Determines whether verbose logging is on for specified level current file.
  3667. #define VLOG_IS_ON(verboseLevel) (ELPP->vRegistry()->allowed(verboseLevel, __FILE__))
  3668. #undef TIMED_BLOCK
  3669. #undef TIMED_SCOPE
  3670. #undef TIMED_SCOPE_IF
  3671. #undef TIMED_FUNC
  3672. #undef TIMED_FUNC_IF
  3673. #undef ELPP_MIN_UNIT
  3674. #if defined(ELPP_PERFORMANCE_MICROSECONDS)
  3675. # define ELPP_MIN_UNIT el::base::TimestampUnit::Microsecond
  3676. #else
  3677. # define ELPP_MIN_UNIT el::base::TimestampUnit::Millisecond
  3678. #endif // (defined(ELPP_PERFORMANCE_MICROSECONDS))
  3679. /// @brief Performance tracked scope. Performance gets written when goes out of scope using
  3680. /// 'performance' logger.
  3681. ///
  3682. /// @detail Please note in order to check the performance at a certain time you can use obj->checkpoint();
  3683. /// @see el::base::PerformanceTracker
  3684. /// @see el::base::PerformanceTracker::checkpoint
  3685. // Note: Do not surround this definition with null macro because of obj instance
  3686. #define TIMED_SCOPE_IF(obj, blockname, condition) el::base::type::PerformanceTrackerPtr obj( condition ? \
  3687. new el::base::PerformanceTracker(blockname, ELPP_MIN_UNIT) : nullptr )
  3688. #define TIMED_SCOPE(obj, blockname) TIMED_SCOPE_IF(obj, blockname, true)
  3689. #define TIMED_BLOCK(obj, blockName) for (struct { int i; el::base::type::PerformanceTrackerPtr timer; } obj = { 0, \
  3690. el::base::type::PerformanceTrackerPtr(new el::base::PerformanceTracker(blockName, ELPP_MIN_UNIT)) }; obj.i < 1; ++obj.i)
  3691. /// @brief Performance tracked function. Performance gets written when goes out of scope using
  3692. /// 'performance' logger.
  3693. ///
  3694. /// @detail Please note in order to check the performance at a certain time you can use obj->checkpoint();
  3695. /// @see el::base::PerformanceTracker
  3696. /// @see el::base::PerformanceTracker::checkpoint
  3697. #define TIMED_FUNC_IF(obj,condition) TIMED_SCOPE_IF(obj, ELPP_FUNC, condition)
  3698. #define TIMED_FUNC(obj) TIMED_SCOPE(obj, ELPP_FUNC)
  3699. #undef PERFORMANCE_CHECKPOINT
  3700. #undef PERFORMANCE_CHECKPOINT_WITH_ID
  3701. #define PERFORMANCE_CHECKPOINT(obj) obj->checkpoint(std::string(), __FILE__, __LINE__, ELPP_FUNC)
  3702. #define PERFORMANCE_CHECKPOINT_WITH_ID(obj, id) obj->checkpoint(id, __FILE__, __LINE__, ELPP_FUNC)
  3703. #undef ELPP_COUNTER
  3704. #undef ELPP_COUNTER_POS
  3705. /// @brief Gets hit counter for file/line
  3706. #define ELPP_COUNTER (ELPP->hitCounters()->getCounter(__FILE__, __LINE__))
  3707. /// @brief Gets hit counter position for file/line, -1 if not registered yet
  3708. #define ELPP_COUNTER_POS (ELPP_COUNTER == nullptr ? -1 : ELPP_COUNTER->hitCounts())
  3709. // Undef levels to support LOG(LEVEL)
  3710. #undef INFO
  3711. #undef WARNING
  3712. #undef DEBUG
  3713. #undef ERROR
  3714. #undef FATAL
  3715. #undef TRACE
  3716. #undef VERBOSE
  3717. // Undef existing
  3718. #undef CINFO
  3719. #undef CWARNING
  3720. #undef CDEBUG
  3721. #undef CFATAL
  3722. #undef CERROR
  3723. #undef CTRACE
  3724. #undef CVERBOSE
  3725. #undef CINFO_IF
  3726. #undef CWARNING_IF
  3727. #undef CDEBUG_IF
  3728. #undef CERROR_IF
  3729. #undef CFATAL_IF
  3730. #undef CTRACE_IF
  3731. #undef CVERBOSE_IF
  3732. #undef CINFO_EVERY_N
  3733. #undef CWARNING_EVERY_N
  3734. #undef CDEBUG_EVERY_N
  3735. #undef CERROR_EVERY_N
  3736. #undef CFATAL_EVERY_N
  3737. #undef CTRACE_EVERY_N
  3738. #undef CVERBOSE_EVERY_N
  3739. #undef CINFO_AFTER_N
  3740. #undef CWARNING_AFTER_N
  3741. #undef CDEBUG_AFTER_N
  3742. #undef CERROR_AFTER_N
  3743. #undef CFATAL_AFTER_N
  3744. #undef CTRACE_AFTER_N
  3745. #undef CVERBOSE_AFTER_N
  3746. #undef CINFO_N_TIMES
  3747. #undef CWARNING_N_TIMES
  3748. #undef CDEBUG_N_TIMES
  3749. #undef CERROR_N_TIMES
  3750. #undef CFATAL_N_TIMES
  3751. #undef CTRACE_N_TIMES
  3752. #undef CVERBOSE_N_TIMES
  3753. // Normal logs
  3754. #if ELPP_INFO_LOG
  3755. # define CINFO(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Info, dispatchAction, __VA_ARGS__)
  3756. #else
  3757. # define CINFO(writer, dispatchAction, ...) el::base::NullWriter()
  3758. #endif // ELPP_INFO_LOG
  3759. #if ELPP_WARNING_LOG
  3760. # define CWARNING(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Warning, dispatchAction, __VA_ARGS__)
  3761. #else
  3762. # define CWARNING(writer, dispatchAction, ...) el::base::NullWriter()
  3763. #endif // ELPP_WARNING_LOG
  3764. #if ELPP_DEBUG_LOG
  3765. # define CDEBUG(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Debug, dispatchAction, __VA_ARGS__)
  3766. #else
  3767. # define CDEBUG(writer, dispatchAction, ...) el::base::NullWriter()
  3768. #endif // ELPP_DEBUG_LOG
  3769. #if ELPP_ERROR_LOG
  3770. # define CERROR(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Error, dispatchAction, __VA_ARGS__)
  3771. #else
  3772. # define CERROR(writer, dispatchAction, ...) el::base::NullWriter()
  3773. #endif // ELPP_ERROR_LOG
  3774. #if ELPP_FATAL_LOG
  3775. # define CFATAL(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Fatal, dispatchAction, __VA_ARGS__)
  3776. #else
  3777. # define CFATAL(writer, dispatchAction, ...) el::base::NullWriter()
  3778. #endif // ELPP_FATAL_LOG
  3779. #if ELPP_TRACE_LOG
  3780. # define CTRACE(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Trace, dispatchAction, __VA_ARGS__)
  3781. #else
  3782. # define CTRACE(writer, dispatchAction, ...) el::base::NullWriter()
  3783. #endif // ELPP_TRACE_LOG
  3784. #if ELPP_VERBOSE_LOG
  3785. # define CVERBOSE(writer, vlevel, dispatchAction, ...) if (VLOG_IS_ON(vlevel)) writer(\
  3786. el::Level::Verbose, __FILE__, __LINE__, ELPP_FUNC, dispatchAction, vlevel).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
  3787. #else
  3788. # define CVERBOSE(writer, vlevel, dispatchAction, ...) el::base::NullWriter()
  3789. #endif // ELPP_VERBOSE_LOG
  3790. // Conditional logs
  3791. #if ELPP_INFO_LOG
  3792. # define CINFO_IF(writer, condition_, dispatchAction, ...) \
  3793. ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Info, dispatchAction, __VA_ARGS__)
  3794. #else
  3795. # define CINFO_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter()
  3796. #endif // ELPP_INFO_LOG
  3797. #if ELPP_WARNING_LOG
  3798. # define CWARNING_IF(writer, condition_, dispatchAction, ...)\
  3799. ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Warning, dispatchAction, __VA_ARGS__)
  3800. #else
  3801. # define CWARNING_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter()
  3802. #endif // ELPP_WARNING_LOG
  3803. #if ELPP_DEBUG_LOG
  3804. # define CDEBUG_IF(writer, condition_, dispatchAction, ...)\
  3805. ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Debug, dispatchAction, __VA_ARGS__)
  3806. #else
  3807. # define CDEBUG_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter()
  3808. #endif // ELPP_DEBUG_LOG
  3809. #if ELPP_ERROR_LOG
  3810. # define CERROR_IF(writer, condition_, dispatchAction, ...)\
  3811. ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Error, dispatchAction, __VA_ARGS__)
  3812. #else
  3813. # define CERROR_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter()
  3814. #endif // ELPP_ERROR_LOG
  3815. #if ELPP_FATAL_LOG
  3816. # define CFATAL_IF(writer, condition_, dispatchAction, ...)\
  3817. ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Fatal, dispatchAction, __VA_ARGS__)
  3818. #else
  3819. # define CFATAL_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter()
  3820. #endif // ELPP_FATAL_LOG
  3821. #if ELPP_TRACE_LOG
  3822. # define CTRACE_IF(writer, condition_, dispatchAction, ...)\
  3823. ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Trace, dispatchAction, __VA_ARGS__)
  3824. #else
  3825. # define CTRACE_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter()
  3826. #endif // ELPP_TRACE_LOG
  3827. #if ELPP_VERBOSE_LOG
  3828. # define CVERBOSE_IF(writer, condition_, vlevel, dispatchAction, ...) if (VLOG_IS_ON(vlevel) && (condition_)) writer( \
  3829. el::Level::Verbose, __FILE__, __LINE__, ELPP_FUNC, dispatchAction, vlevel).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
  3830. #else
  3831. # define CVERBOSE_IF(writer, condition_, vlevel, dispatchAction, ...) el::base::NullWriter()
  3832. #endif // ELPP_VERBOSE_LOG
  3833. // Occasional logs
  3834. #if ELPP_INFO_LOG
  3835. # define CINFO_EVERY_N(writer, occasion, dispatchAction, ...)\
  3836. ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Info, dispatchAction, __VA_ARGS__)
  3837. #else
  3838. # define CINFO_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter()
  3839. #endif // ELPP_INFO_LOG
  3840. #if ELPP_WARNING_LOG
  3841. # define CWARNING_EVERY_N(writer, occasion, dispatchAction, ...)\
  3842. ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Warning, dispatchAction, __VA_ARGS__)
  3843. #else
  3844. # define CWARNING_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter()
  3845. #endif // ELPP_WARNING_LOG
  3846. #if ELPP_DEBUG_LOG
  3847. # define CDEBUG_EVERY_N(writer, occasion, dispatchAction, ...)\
  3848. ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Debug, dispatchAction, __VA_ARGS__)
  3849. #else
  3850. # define CDEBUG_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter()
  3851. #endif // ELPP_DEBUG_LOG
  3852. #if ELPP_ERROR_LOG
  3853. # define CERROR_EVERY_N(writer, occasion, dispatchAction, ...)\
  3854. ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Error, dispatchAction, __VA_ARGS__)
  3855. #else
  3856. # define CERROR_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter()
  3857. #endif // ELPP_ERROR_LOG
  3858. #if ELPP_FATAL_LOG
  3859. # define CFATAL_EVERY_N(writer, occasion, dispatchAction, ...)\
  3860. ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Fatal, dispatchAction, __VA_ARGS__)
  3861. #else
  3862. # define CFATAL_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter()
  3863. #endif // ELPP_FATAL_LOG
  3864. #if ELPP_TRACE_LOG
  3865. # define CTRACE_EVERY_N(writer, occasion, dispatchAction, ...)\
  3866. ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Trace, dispatchAction, __VA_ARGS__)
  3867. #else
  3868. # define CTRACE_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter()
  3869. #endif // ELPP_TRACE_LOG
  3870. #if ELPP_VERBOSE_LOG
  3871. # define CVERBOSE_EVERY_N(writer, occasion, vlevel, dispatchAction, ...)\
  3872. CVERBOSE_IF(writer, ELPP->validateEveryNCounter(__FILE__, __LINE__, occasion), vlevel, dispatchAction, __VA_ARGS__)
  3873. #else
  3874. # define CVERBOSE_EVERY_N(writer, occasion, vlevel, dispatchAction, ...) el::base::NullWriter()
  3875. #endif // ELPP_VERBOSE_LOG
  3876. // After N logs
  3877. #if ELPP_INFO_LOG
  3878. # define CINFO_AFTER_N(writer, n, dispatchAction, ...)\
  3879. ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Info, dispatchAction, __VA_ARGS__)
  3880. #else
  3881. # define CINFO_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter()
  3882. #endif // ELPP_INFO_LOG
  3883. #if ELPP_WARNING_LOG
  3884. # define CWARNING_AFTER_N(writer, n, dispatchAction, ...)\
  3885. ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Warning, dispatchAction, __VA_ARGS__)
  3886. #else
  3887. # define CWARNING_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter()
  3888. #endif // ELPP_WARNING_LOG
  3889. #if ELPP_DEBUG_LOG
  3890. # define CDEBUG_AFTER_N(writer, n, dispatchAction, ...)\
  3891. ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Debug, dispatchAction, __VA_ARGS__)
  3892. #else
  3893. # define CDEBUG_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter()
  3894. #endif // ELPP_DEBUG_LOG
  3895. #if ELPP_ERROR_LOG
  3896. # define CERROR_AFTER_N(writer, n, dispatchAction, ...)\
  3897. ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Error, dispatchAction, __VA_ARGS__)
  3898. #else
  3899. # define CERROR_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter()
  3900. #endif // ELPP_ERROR_LOG
  3901. #if ELPP_FATAL_LOG
  3902. # define CFATAL_AFTER_N(writer, n, dispatchAction, ...)\
  3903. ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Fatal, dispatchAction, __VA_ARGS__)
  3904. #else
  3905. # define CFATAL_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter()
  3906. #endif // ELPP_FATAL_LOG
  3907. #if ELPP_TRACE_LOG
  3908. # define CTRACE_AFTER_N(writer, n, dispatchAction, ...)\
  3909. ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Trace, dispatchAction, __VA_ARGS__)
  3910. #else
  3911. # define CTRACE_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter()
  3912. #endif // ELPP_TRACE_LOG
  3913. #if ELPP_VERBOSE_LOG
  3914. # define CVERBOSE_AFTER_N(writer, n, vlevel, dispatchAction, ...)\
  3915. CVERBOSE_IF(writer, ELPP->validateAfterNCounter(__FILE__, __LINE__, n), vlevel, dispatchAction, __VA_ARGS__)
  3916. #else
  3917. # define CVERBOSE_AFTER_N(writer, n, vlevel, dispatchAction, ...) el::base::NullWriter()
  3918. #endif // ELPP_VERBOSE_LOG
  3919. // N Times logs
  3920. #if ELPP_INFO_LOG
  3921. # define CINFO_N_TIMES(writer, n, dispatchAction, ...)\
  3922. ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Info, dispatchAction, __VA_ARGS__)
  3923. #else
  3924. # define CINFO_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter()
  3925. #endif // ELPP_INFO_LOG
  3926. #if ELPP_WARNING_LOG
  3927. # define CWARNING_N_TIMES(writer, n, dispatchAction, ...)\
  3928. ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Warning, dispatchAction, __VA_ARGS__)
  3929. #else
  3930. # define CWARNING_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter()
  3931. #endif // ELPP_WARNING_LOG
  3932. #if ELPP_DEBUG_LOG
  3933. # define CDEBUG_N_TIMES(writer, n, dispatchAction, ...)\
  3934. ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Debug, dispatchAction, __VA_ARGS__)
  3935. #else
  3936. # define CDEBUG_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter()
  3937. #endif // ELPP_DEBUG_LOG
  3938. #if ELPP_ERROR_LOG
  3939. # define CERROR_N_TIMES(writer, n, dispatchAction, ...)\
  3940. ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Error, dispatchAction, __VA_ARGS__)
  3941. #else
  3942. # define CERROR_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter()
  3943. #endif // ELPP_ERROR_LOG
  3944. #if ELPP_FATAL_LOG
  3945. # define CFATAL_N_TIMES(writer, n, dispatchAction, ...)\
  3946. ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Fatal, dispatchAction, __VA_ARGS__)
  3947. #else
  3948. # define CFATAL_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter()
  3949. #endif // ELPP_FATAL_LOG
  3950. #if ELPP_TRACE_LOG
  3951. # define CTRACE_N_TIMES(writer, n, dispatchAction, ...)\
  3952. ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Trace, dispatchAction, __VA_ARGS__)
  3953. #else
  3954. # define CTRACE_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter()
  3955. #endif // ELPP_TRACE_LOG
  3956. #if ELPP_VERBOSE_LOG
  3957. # define CVERBOSE_N_TIMES(writer, n, vlevel, dispatchAction, ...)\
  3958. CVERBOSE_IF(writer, ELPP->validateNTimesCounter(__FILE__, __LINE__, n), vlevel, dispatchAction, __VA_ARGS__)
  3959. #else
  3960. # define CVERBOSE_N_TIMES(writer, n, vlevel, dispatchAction, ...) el::base::NullWriter()
  3961. #endif // ELPP_VERBOSE_LOG
  3962. //
  3963. // Custom Loggers - Requires (level, dispatchAction, loggerId/s)
  3964. //
  3965. // undef existing
  3966. #undef CLOG
  3967. #undef CLOG_VERBOSE
  3968. #undef CVLOG
  3969. #undef CLOG_IF
  3970. #undef CLOG_VERBOSE_IF
  3971. #undef CVLOG_IF
  3972. #undef CLOG_EVERY_N
  3973. #undef CVLOG_EVERY_N
  3974. #undef CLOG_AFTER_N
  3975. #undef CVLOG_AFTER_N
  3976. #undef CLOG_N_TIMES
  3977. #undef CVLOG_N_TIMES
  3978. // Normal logs
  3979. #define CLOG(LEVEL, ...)\
  3980. C##LEVEL(el::base::Writer, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  3981. #define CVLOG(vlevel, ...) CVERBOSE(el::base::Writer, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  3982. // Conditional logs
  3983. #define CLOG_IF(condition, LEVEL, ...)\
  3984. C##LEVEL##_IF(el::base::Writer, condition, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  3985. #define CVLOG_IF(condition, vlevel, ...)\
  3986. CVERBOSE_IF(el::base::Writer, condition, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  3987. // Hit counts based logs
  3988. #define CLOG_EVERY_N(n, LEVEL, ...)\
  3989. C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  3990. #define CVLOG_EVERY_N(n, vlevel, ...)\
  3991. CVERBOSE_EVERY_N(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  3992. #define CLOG_AFTER_N(n, LEVEL, ...)\
  3993. C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  3994. #define CVLOG_AFTER_N(n, vlevel, ...)\
  3995. CVERBOSE_AFTER_N(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  3996. #define CLOG_N_TIMES(n, LEVEL, ...)\
  3997. C##LEVEL##_N_TIMES(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  3998. #define CVLOG_N_TIMES(n, vlevel, ...)\
  3999. CVERBOSE_N_TIMES(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  4000. //
  4001. // Default Loggers macro using CLOG(), CLOG_VERBOSE() and CVLOG() macros
  4002. //
  4003. // undef existing
  4004. #undef LOG
  4005. #undef VLOG
  4006. #undef LOG_IF
  4007. #undef VLOG_IF
  4008. #undef LOG_EVERY_N
  4009. #undef VLOG_EVERY_N
  4010. #undef LOG_AFTER_N
  4011. #undef VLOG_AFTER_N
  4012. #undef LOG_N_TIMES
  4013. #undef VLOG_N_TIMES
  4014. #undef ELPP_CURR_FILE_LOGGER_ID
  4015. #if defined(ELPP_DEFAULT_LOGGER)
  4016. # define ELPP_CURR_FILE_LOGGER_ID ELPP_DEFAULT_LOGGER
  4017. #else
  4018. # define ELPP_CURR_FILE_LOGGER_ID el::base::consts::kDefaultLoggerId
  4019. #endif
  4020. #undef ELPP_TRACE
  4021. #define ELPP_TRACE CLOG(TRACE, ELPP_CURR_FILE_LOGGER_ID)
  4022. // Normal logs
  4023. #define LOG(LEVEL) CLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4024. #define VLOG(vlevel) CVLOG(vlevel, ELPP_CURR_FILE_LOGGER_ID)
  4025. // Conditional logs
  4026. #define LOG_IF(condition, LEVEL) CLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4027. #define VLOG_IF(condition, vlevel) CVLOG_IF(condition, vlevel, ELPP_CURR_FILE_LOGGER_ID)
  4028. // Hit counts based logs
  4029. #define LOG_EVERY_N(n, LEVEL) CLOG_EVERY_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4030. #define VLOG_EVERY_N(n, vlevel) CVLOG_EVERY_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID)
  4031. #define LOG_AFTER_N(n, LEVEL) CLOG_AFTER_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4032. #define VLOG_AFTER_N(n, vlevel) CVLOG_AFTER_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID)
  4033. #define LOG_N_TIMES(n, LEVEL) CLOG_N_TIMES(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4034. #define VLOG_N_TIMES(n, vlevel) CVLOG_N_TIMES(n, vlevel, ELPP_CURR_FILE_LOGGER_ID)
  4035. // Generic PLOG()
  4036. #undef CPLOG
  4037. #undef CPLOG_IF
  4038. #undef PLOG
  4039. #undef PLOG_IF
  4040. #undef DCPLOG
  4041. #undef DCPLOG_IF
  4042. #undef DPLOG
  4043. #undef DPLOG_IF
  4044. #define CPLOG(LEVEL, ...)\
  4045. C##LEVEL(el::base::PErrorWriter, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  4046. #define CPLOG_IF(condition, LEVEL, ...)\
  4047. C##LEVEL##_IF(el::base::PErrorWriter, condition, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  4048. #define DCPLOG(LEVEL, ...)\
  4049. if (ELPP_DEBUG_LOG) C##LEVEL(el::base::PErrorWriter, el::base::DispatchAction::NormalLog, __VA_ARGS__)
  4050. #define DCPLOG_IF(condition, LEVEL, ...)\
  4051. C##LEVEL##_IF(el::base::PErrorWriter, (ELPP_DEBUG_LOG) && (condition), el::base::DispatchAction::NormalLog, __VA_ARGS__)
  4052. #define PLOG(LEVEL) CPLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4053. #define PLOG_IF(condition, LEVEL) CPLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4054. #define DPLOG(LEVEL) DCPLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4055. #define DPLOG_IF(condition, LEVEL) DCPLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4056. // Generic SYSLOG()
  4057. #undef CSYSLOG
  4058. #undef CSYSLOG_IF
  4059. #undef CSYSLOG_EVERY_N
  4060. #undef CSYSLOG_AFTER_N
  4061. #undef CSYSLOG_N_TIMES
  4062. #undef SYSLOG
  4063. #undef SYSLOG_IF
  4064. #undef SYSLOG_EVERY_N
  4065. #undef SYSLOG_AFTER_N
  4066. #undef SYSLOG_N_TIMES
  4067. #undef DCSYSLOG
  4068. #undef DCSYSLOG_IF
  4069. #undef DCSYSLOG_EVERY_N
  4070. #undef DCSYSLOG_AFTER_N
  4071. #undef DCSYSLOG_N_TIMES
  4072. #undef DSYSLOG
  4073. #undef DSYSLOG_IF
  4074. #undef DSYSLOG_EVERY_N
  4075. #undef DSYSLOG_AFTER_N
  4076. #undef DSYSLOG_N_TIMES
  4077. #if defined(ELPP_SYSLOG)
  4078. # define CSYSLOG(LEVEL, ...)\
  4079. C##LEVEL(el::base::Writer, el::base::DispatchAction::SysLog, __VA_ARGS__)
  4080. # define CSYSLOG_IF(condition, LEVEL, ...)\
  4081. C##LEVEL##_IF(el::base::Writer, condition, el::base::DispatchAction::SysLog, __VA_ARGS__)
  4082. # define CSYSLOG_EVERY_N(n, LEVEL, ...) C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__)
  4083. # define CSYSLOG_AFTER_N(n, LEVEL, ...) C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__)
  4084. # define CSYSLOG_N_TIMES(n, LEVEL, ...) C##LEVEL##_N_TIMES(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__)
  4085. # define SYSLOG(LEVEL) CSYSLOG(LEVEL, el::base::consts::kSysLogLoggerId)
  4086. # define SYSLOG_IF(condition, LEVEL) CSYSLOG_IF(condition, LEVEL, el::base::consts::kSysLogLoggerId)
  4087. # define SYSLOG_EVERY_N(n, LEVEL) CSYSLOG_EVERY_N(n, LEVEL, el::base::consts::kSysLogLoggerId)
  4088. # define SYSLOG_AFTER_N(n, LEVEL) CSYSLOG_AFTER_N(n, LEVEL, el::base::consts::kSysLogLoggerId)
  4089. # define SYSLOG_N_TIMES(n, LEVEL) CSYSLOG_N_TIMES(n, LEVEL, el::base::consts::kSysLogLoggerId)
  4090. # define DCSYSLOG(LEVEL, ...) if (ELPP_DEBUG_LOG) C##LEVEL(el::base::Writer, el::base::DispatchAction::SysLog, __VA_ARGS__)
  4091. # define DCSYSLOG_IF(condition, LEVEL, ...)\
  4092. C##LEVEL##_IF(el::base::Writer, (ELPP_DEBUG_LOG) && (condition), el::base::DispatchAction::SysLog, __VA_ARGS__)
  4093. # define DCSYSLOG_EVERY_N(n, LEVEL, ...)\
  4094. if (ELPP_DEBUG_LOG) C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__)
  4095. # define DCSYSLOG_AFTER_N(n, LEVEL, ...)\
  4096. if (ELPP_DEBUG_LOG) C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__)
  4097. # define DCSYSLOG_N_TIMES(n, LEVEL, ...)\
  4098. if (ELPP_DEBUG_LOG) C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__)
  4099. # define DSYSLOG(LEVEL) DCSYSLOG(LEVEL, el::base::consts::kSysLogLoggerId)
  4100. # define DSYSLOG_IF(condition, LEVEL) DCSYSLOG_IF(condition, LEVEL, el::base::consts::kSysLogLoggerId)
  4101. # define DSYSLOG_EVERY_N(n, LEVEL) DCSYSLOG_EVERY_N(n, LEVEL, el::base::consts::kSysLogLoggerId)
  4102. # define DSYSLOG_AFTER_N(n, LEVEL) DCSYSLOG_AFTER_N(n, LEVEL, el::base::consts::kSysLogLoggerId)
  4103. # define DSYSLOG_N_TIMES(n, LEVEL) DCSYSLOG_N_TIMES(n, LEVEL, el::base::consts::kSysLogLoggerId)
  4104. #else
  4105. # define CSYSLOG(LEVEL, ...) el::base::NullWriter()
  4106. # define CSYSLOG_IF(condition, LEVEL, ...) el::base::NullWriter()
  4107. # define CSYSLOG_EVERY_N(n, LEVEL, ...) el::base::NullWriter()
  4108. # define CSYSLOG_AFTER_N(n, LEVEL, ...) el::base::NullWriter()
  4109. # define CSYSLOG_N_TIMES(n, LEVEL, ...) el::base::NullWriter()
  4110. # define SYSLOG(LEVEL) el::base::NullWriter()
  4111. # define SYSLOG_IF(condition, LEVEL) el::base::NullWriter()
  4112. # define SYSLOG_EVERY_N(n, LEVEL) el::base::NullWriter()
  4113. # define SYSLOG_AFTER_N(n, LEVEL) el::base::NullWriter()
  4114. # define SYSLOG_N_TIMES(n, LEVEL) el::base::NullWriter()
  4115. # define DCSYSLOG(LEVEL, ...) el::base::NullWriter()
  4116. # define DCSYSLOG_IF(condition, LEVEL, ...) el::base::NullWriter()
  4117. # define DCSYSLOG_EVERY_N(n, LEVEL, ...) el::base::NullWriter()
  4118. # define DCSYSLOG_AFTER_N(n, LEVEL, ...) el::base::NullWriter()
  4119. # define DCSYSLOG_N_TIMES(n, LEVEL, ...) el::base::NullWriter()
  4120. # define DSYSLOG(LEVEL) el::base::NullWriter()
  4121. # define DSYSLOG_IF(condition, LEVEL) el::base::NullWriter()
  4122. # define DSYSLOG_EVERY_N(n, LEVEL) el::base::NullWriter()
  4123. # define DSYSLOG_AFTER_N(n, LEVEL) el::base::NullWriter()
  4124. # define DSYSLOG_N_TIMES(n, LEVEL) el::base::NullWriter()
  4125. #endif // defined(ELPP_SYSLOG)
  4126. //
  4127. // Custom Debug Only Loggers - Requires (level, loggerId/s)
  4128. //
  4129. // undef existing
  4130. #undef DCLOG
  4131. #undef DCVLOG
  4132. #undef DCLOG_IF
  4133. #undef DCVLOG_IF
  4134. #undef DCLOG_EVERY_N
  4135. #undef DCVLOG_EVERY_N
  4136. #undef DCLOG_AFTER_N
  4137. #undef DCVLOG_AFTER_N
  4138. #undef DCLOG_N_TIMES
  4139. #undef DCVLOG_N_TIMES
  4140. // Normal logs
  4141. #define DCLOG(LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG(LEVEL, __VA_ARGS__)
  4142. #define DCLOG_VERBOSE(vlevel, ...) if (ELPP_DEBUG_LOG) CLOG_VERBOSE(vlevel, __VA_ARGS__)
  4143. #define DCVLOG(vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG(vlevel, __VA_ARGS__)
  4144. // Conditional logs
  4145. #define DCLOG_IF(condition, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_IF(condition, LEVEL, __VA_ARGS__)
  4146. #define DCVLOG_IF(condition, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_IF(condition, vlevel, __VA_ARGS__)
  4147. // Hit counts based logs
  4148. #define DCLOG_EVERY_N(n, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_EVERY_N(n, LEVEL, __VA_ARGS__)
  4149. #define DCVLOG_EVERY_N(n, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_EVERY_N(n, vlevel, __VA_ARGS__)
  4150. #define DCLOG_AFTER_N(n, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_AFTER_N(n, LEVEL, __VA_ARGS__)
  4151. #define DCVLOG_AFTER_N(n, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_AFTER_N(n, vlevel, __VA_ARGS__)
  4152. #define DCLOG_N_TIMES(n, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_N_TIMES(n, LEVEL, __VA_ARGS__)
  4153. #define DCVLOG_N_TIMES(n, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_N_TIMES(n, vlevel, __VA_ARGS__)
  4154. //
  4155. // Default Debug Only Loggers macro using CLOG(), CLOG_VERBOSE() and CVLOG() macros
  4156. //
  4157. #if !defined(ELPP_NO_DEBUG_MACROS)
  4158. // undef existing
  4159. #undef DLOG
  4160. #undef DVLOG
  4161. #undef DLOG_IF
  4162. #undef DVLOG_IF
  4163. #undef DLOG_EVERY_N
  4164. #undef DVLOG_EVERY_N
  4165. #undef DLOG_AFTER_N
  4166. #undef DVLOG_AFTER_N
  4167. #undef DLOG_N_TIMES
  4168. #undef DVLOG_N_TIMES
  4169. // Normal logs
  4170. #define DLOG(LEVEL) DCLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4171. #define DVLOG(vlevel) DCVLOG(vlevel, ELPP_CURR_FILE_LOGGER_ID)
  4172. // Conditional logs
  4173. #define DLOG_IF(condition, LEVEL) DCLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4174. #define DVLOG_IF(condition, vlevel) DCVLOG_IF(condition, vlevel, ELPP_CURR_FILE_LOGGER_ID)
  4175. // Hit counts based logs
  4176. #define DLOG_EVERY_N(n, LEVEL) DCLOG_EVERY_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4177. #define DVLOG_EVERY_N(n, vlevel) DCVLOG_EVERY_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID)
  4178. #define DLOG_AFTER_N(n, LEVEL) DCLOG_AFTER_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4179. #define DVLOG_AFTER_N(n, vlevel) DCVLOG_AFTER_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID)
  4180. #define DLOG_N_TIMES(n, LEVEL) DCLOG_N_TIMES(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
  4181. #define DVLOG_N_TIMES(n, vlevel) DCVLOG_N_TIMES(n, vlevel, ELPP_CURR_FILE_LOGGER_ID)
  4182. #endif // defined(ELPP_NO_DEBUG_MACROS)
  4183. #if !defined(ELPP_NO_CHECK_MACROS)
  4184. // Check macros
  4185. #undef CCHECK
  4186. #undef CPCHECK
  4187. #undef CCHECK_EQ
  4188. #undef CCHECK_NE
  4189. #undef CCHECK_LT
  4190. #undef CCHECK_GT
  4191. #undef CCHECK_LE
  4192. #undef CCHECK_GE
  4193. #undef CCHECK_BOUNDS
  4194. #undef CCHECK_NOTNULL
  4195. #undef CCHECK_STRCASEEQ
  4196. #undef CCHECK_STRCASENE
  4197. #undef CHECK
  4198. #undef PCHECK
  4199. #undef CHECK_EQ
  4200. #undef CHECK_NE
  4201. #undef CHECK_LT
  4202. #undef CHECK_GT
  4203. #undef CHECK_LE
  4204. #undef CHECK_GE
  4205. #undef CHECK_BOUNDS
  4206. #undef CHECK_NOTNULL
  4207. #undef CHECK_STRCASEEQ
  4208. #undef CHECK_STRCASENE
  4209. #define CCHECK(condition, ...) CLOG_IF(!(condition), FATAL, __VA_ARGS__) << "Check failed: [" << #condition << "] "
  4210. #define CPCHECK(condition, ...) CPLOG_IF(!(condition), FATAL, __VA_ARGS__) << "Check failed: [" << #condition << "] "
  4211. #define CHECK(condition) CCHECK(condition, ELPP_CURR_FILE_LOGGER_ID)
  4212. #define PCHECK(condition) CPCHECK(condition, ELPP_CURR_FILE_LOGGER_ID)
  4213. #define CCHECK_EQ(a, b, ...) CCHECK(a == b, __VA_ARGS__)
  4214. #define CCHECK_NE(a, b, ...) CCHECK(a != b, __VA_ARGS__)
  4215. #define CCHECK_LT(a, b, ...) CCHECK(a < b, __VA_ARGS__)
  4216. #define CCHECK_GT(a, b, ...) CCHECK(a > b, __VA_ARGS__)
  4217. #define CCHECK_LE(a, b, ...) CCHECK(a <= b, __VA_ARGS__)
  4218. #define CCHECK_GE(a, b, ...) CCHECK(a >= b, __VA_ARGS__)
  4219. #define CCHECK_BOUNDS(val, min, max, ...) CCHECK(val >= min && val <= max, __VA_ARGS__)
  4220. #define CHECK_EQ(a, b) CCHECK_EQ(a, b, ELPP_CURR_FILE_LOGGER_ID)
  4221. #define CHECK_NE(a, b) CCHECK_NE(a, b, ELPP_CURR_FILE_LOGGER_ID)
  4222. #define CHECK_LT(a, b) CCHECK_LT(a, b, ELPP_CURR_FILE_LOGGER_ID)
  4223. #define CHECK_GT(a, b) CCHECK_GT(a, b, ELPP_CURR_FILE_LOGGER_ID)
  4224. #define CHECK_LE(a, b) CCHECK_LE(a, b, ELPP_CURR_FILE_LOGGER_ID)
  4225. #define CHECK_GE(a, b) CCHECK_GE(a, b, ELPP_CURR_FILE_LOGGER_ID)
  4226. #define CHECK_BOUNDS(val, min, max) CCHECK_BOUNDS(val, min, max, ELPP_CURR_FILE_LOGGER_ID)
  4227. #define CCHECK_NOTNULL(ptr, ...) CCHECK((ptr) != nullptr, __VA_ARGS__)
  4228. #define CCHECK_STREQ(str1, str2, ...) CLOG_IF(!el::base::utils::Str::cStringEq(str1, str2), FATAL, __VA_ARGS__) \
  4229. << "Check failed: [" << #str1 << " == " << #str2 << "] "
  4230. #define CCHECK_STRNE(str1, str2, ...) CLOG_IF(el::base::utils::Str::cStringEq(str1, str2), FATAL, __VA_ARGS__) \
  4231. << "Check failed: [" << #str1 << " != " << #str2 << "] "
  4232. #define CCHECK_STRCASEEQ(str1, str2, ...) CLOG_IF(!el::base::utils::Str::cStringCaseEq(str1, str2), FATAL, __VA_ARGS__) \
  4233. << "Check failed: [" << #str1 << " == " << #str2 << "] "
  4234. #define CCHECK_STRCASENE(str1, str2, ...) CLOG_IF(el::base::utils::Str::cStringCaseEq(str1, str2), FATAL, __VA_ARGS__) \
  4235. << "Check failed: [" << #str1 << " != " << #str2 << "] "
  4236. #define CHECK_NOTNULL(ptr) CCHECK_NOTNULL((ptr), ELPP_CURR_FILE_LOGGER_ID)
  4237. #define CHECK_STREQ(str1, str2) CCHECK_STREQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
  4238. #define CHECK_STRNE(str1, str2) CCHECK_STRNE(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
  4239. #define CHECK_STRCASEEQ(str1, str2) CCHECK_STRCASEEQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
  4240. #define CHECK_STRCASENE(str1, str2) CCHECK_STRCASENE(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
  4241. #undef DCCHECK
  4242. #undef DCCHECK_EQ
  4243. #undef DCCHECK_NE
  4244. #undef DCCHECK_LT
  4245. #undef DCCHECK_GT
  4246. #undef DCCHECK_LE
  4247. #undef DCCHECK_GE
  4248. #undef DCCHECK_BOUNDS
  4249. #undef DCCHECK_NOTNULL
  4250. #undef DCCHECK_STRCASEEQ
  4251. #undef DCCHECK_STRCASENE
  4252. #undef DCPCHECK
  4253. #undef DCHECK
  4254. #undef DCHECK_EQ
  4255. #undef DCHECK_NE
  4256. #undef DCHECK_LT
  4257. #undef DCHECK_GT
  4258. #undef DCHECK_LE
  4259. #undef DCHECK_GE
  4260. #undef DCHECK_BOUNDS_
  4261. #undef DCHECK_NOTNULL
  4262. #undef DCHECK_STRCASEEQ
  4263. #undef DCHECK_STRCASENE
  4264. #undef DPCHECK
  4265. #define DCCHECK(condition, ...) if (ELPP_DEBUG_LOG) CCHECK(condition, __VA_ARGS__)
  4266. #define DCCHECK_EQ(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_EQ(a, b, __VA_ARGS__)
  4267. #define DCCHECK_NE(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_NE(a, b, __VA_ARGS__)
  4268. #define DCCHECK_LT(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_LT(a, b, __VA_ARGS__)
  4269. #define DCCHECK_GT(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_GT(a, b, __VA_ARGS__)
  4270. #define DCCHECK_LE(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_LE(a, b, __VA_ARGS__)
  4271. #define DCCHECK_GE(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_GE(a, b, __VA_ARGS__)
  4272. #define DCCHECK_BOUNDS(val, min, max, ...) if (ELPP_DEBUG_LOG) CCHECK_BOUNDS(val, min, max, __VA_ARGS__)
  4273. #define DCCHECK_NOTNULL(ptr, ...) if (ELPP_DEBUG_LOG) CCHECK_NOTNULL((ptr), __VA_ARGS__)
  4274. #define DCCHECK_STREQ(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STREQ(str1, str2, __VA_ARGS__)
  4275. #define DCCHECK_STRNE(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STRNE(str1, str2, __VA_ARGS__)
  4276. #define DCCHECK_STRCASEEQ(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STRCASEEQ(str1, str2, __VA_ARGS__)
  4277. #define DCCHECK_STRCASENE(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STRCASENE(str1, str2, __VA_ARGS__)
  4278. #define DCPCHECK(condition, ...) if (ELPP_DEBUG_LOG) CPCHECK(condition, __VA_ARGS__)
  4279. #define DCHECK(condition) DCCHECK(condition, ELPP_CURR_FILE_LOGGER_ID)
  4280. #define DCHECK_EQ(a, b) DCCHECK_EQ(a, b, ELPP_CURR_FILE_LOGGER_ID)
  4281. #define DCHECK_NE(a, b) DCCHECK_NE(a, b, ELPP_CURR_FILE_LOGGER_ID)
  4282. #define DCHECK_LT(a, b) DCCHECK_LT(a, b, ELPP_CURR_FILE_LOGGER_ID)
  4283. #define DCHECK_GT(a, b) DCCHECK_GT(a, b, ELPP_CURR_FILE_LOGGER_ID)
  4284. #define DCHECK_LE(a, b) DCCHECK_LE(a, b, ELPP_CURR_FILE_LOGGER_ID)
  4285. #define DCHECK_GE(a, b) DCCHECK_GE(a, b, ELPP_CURR_FILE_LOGGER_ID)
  4286. #define DCHECK_BOUNDS(val, min, max) DCCHECK_BOUNDS(val, min, max, ELPP_CURR_FILE_LOGGER_ID)
  4287. #define DCHECK_NOTNULL(ptr) DCCHECK_NOTNULL((ptr), ELPP_CURR_FILE_LOGGER_ID)
  4288. #define DCHECK_STREQ(str1, str2) DCCHECK_STREQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
  4289. #define DCHECK_STRNE(str1, str2) DCCHECK_STRNE(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
  4290. #define DCHECK_STRCASEEQ(str1, str2) DCCHECK_STRCASEEQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
  4291. #define DCHECK_STRCASENE(str1, str2) DCCHECK_STRCASENE(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
  4292. #define DPCHECK(condition) DCPCHECK(condition, ELPP_CURR_FILE_LOGGER_ID)
  4293. #endif // defined(ELPP_NO_CHECK_MACROS)
  4294. #if defined(ELPP_DISABLE_DEFAULT_CRASH_HANDLING)
  4295. # define ELPP_USE_DEF_CRASH_HANDLER false
  4296. #else
  4297. # define ELPP_USE_DEF_CRASH_HANDLER true
  4298. #endif // defined(ELPP_DISABLE_DEFAULT_CRASH_HANDLING)
  4299. #define ELPP_CRASH_HANDLER_INIT
  4300. #define ELPP_INIT_EASYLOGGINGPP(val) \
  4301. namespace el { \
  4302. namespace base { \
  4303. el::base::type::StoragePointer elStorage(val); \
  4304. } \
  4305. el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER); \
  4306. }
  4307. #if ELPP_ASYNC_LOGGING
  4308. # define INITIALIZE_EASYLOGGINGPP ELPP_INIT_EASYLOGGINGPP(new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder()),\
  4309. new el::base::AsyncDispatchWorker()))
  4310. #else
  4311. # define INITIALIZE_EASYLOGGINGPP ELPP_INIT_EASYLOGGINGPP(new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder())))
  4312. #endif // ELPP_ASYNC_LOGGING
  4313. #define INITIALIZE_NULL_EASYLOGGINGPP \
  4314. namespace el {\
  4315. namespace base {\
  4316. el::base::type::StoragePointer elStorage;\
  4317. }\
  4318. el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER);\
  4319. }
  4320. #define SHARE_EASYLOGGINGPP(initializedStorage)\
  4321. namespace el {\
  4322. namespace base {\
  4323. el::base::type::StoragePointer elStorage(initializedStorage);\
  4324. }\
  4325. el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER);\
  4326. }
  4327. #if defined(ELPP_UNICODE)
  4328. # define START_EASYLOGGINGPP(argc, argv) el::Helpers::setArgs(argc, argv); std::locale::global(std::locale(""))
  4329. #else
  4330. # define START_EASYLOGGINGPP(argc, argv) el::Helpers::setArgs(argc, argv)
  4331. #endif // defined(ELPP_UNICODE)
  4332. #endif // EASYLOGGINGPP_H