easylogging++.h 180 KB

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