easylogging++.h 180 KB

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