_logger.py 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139
  1. """Core logging functionalities of the `Loguru` library.
  2. .. References and links rendered by Sphinx are kept here as "module documentation" so that they can
  3. be used in the ``Logger`` docstrings but do not pollute ``help(logger)`` output.
  4. .. |Logger| replace:: :class:`~Logger`
  5. .. |add| replace:: :meth:`~Logger.add()`
  6. .. |remove| replace:: :meth:`~Logger.remove()`
  7. .. |complete| replace:: :meth:`~Logger.complete()`
  8. .. |catch| replace:: :meth:`~Logger.catch()`
  9. .. |bind| replace:: :meth:`~Logger.bind()`
  10. .. |contextualize| replace:: :meth:`~Logger.contextualize()`
  11. .. |patch| replace:: :meth:`~Logger.patch()`
  12. .. |opt| replace:: :meth:`~Logger.opt()`
  13. .. |log| replace:: :meth:`~Logger.log()`
  14. .. |level| replace:: :meth:`~Logger.level()`
  15. .. |enable| replace:: :meth:`~Logger.enable()`
  16. .. |disable| replace:: :meth:`~Logger.disable()`
  17. .. |Any| replace:: :obj:`~typing.Any`
  18. .. |str| replace:: :class:`str`
  19. .. |int| replace:: :class:`int`
  20. .. |bool| replace:: :class:`bool`
  21. .. |tuple| replace:: :class:`tuple`
  22. .. |namedtuple| replace:: :func:`namedtuple<collections.namedtuple>`
  23. .. |list| replace:: :class:`list`
  24. .. |dict| replace:: :class:`dict`
  25. .. |str.format| replace:: :meth:`str.format()`
  26. .. |Path| replace:: :class:`pathlib.Path`
  27. .. |match.groupdict| replace:: :meth:`re.Match.groupdict()`
  28. .. |Handler| replace:: :class:`logging.Handler`
  29. .. |sys.stderr| replace:: :data:`sys.stderr`
  30. .. |sys.exc_info| replace:: :func:`sys.exc_info()`
  31. .. |time| replace:: :class:`datetime.time`
  32. .. |datetime| replace:: :class:`datetime.datetime`
  33. .. |timedelta| replace:: :class:`datetime.timedelta`
  34. .. |open| replace:: :func:`open()`
  35. .. |logging| replace:: :mod:`logging`
  36. .. |signal| replace:: :mod:`signal`
  37. .. |contextvars| replace:: :mod:`contextvars`
  38. .. |multiprocessing| replace:: :mod:`multiprocessing`
  39. .. |Thread.run| replace:: :meth:`Thread.run()<threading.Thread.run()>`
  40. .. |Exception| replace:: :class:`Exception`
  41. .. |AbstractEventLoop| replace:: :class:`AbstractEventLoop<asyncio.AbstractEventLoop>`
  42. .. |asyncio.get_running_loop| replace:: :func:`asyncio.get_running_loop()`
  43. .. |asyncio.run| replace:: :func:`asyncio.run()`
  44. .. |loop.run_until_complete| replace::
  45. :meth:`loop.run_until_complete()<asyncio.loop.run_until_complete()>`
  46. .. |loop.create_task| replace:: :meth:`loop.create_task()<asyncio.loop.create_task()>`
  47. .. |logger.trace| replace:: :meth:`logger.trace()<Logger.trace()>`
  48. .. |logger.debug| replace:: :meth:`logger.debug()<Logger.debug()>`
  49. .. |logger.info| replace:: :meth:`logger.info()<Logger.info()>`
  50. .. |logger.success| replace:: :meth:`logger.success()<Logger.success()>`
  51. .. |logger.warning| replace:: :meth:`logger.warning()<Logger.warning()>`
  52. .. |logger.error| replace:: :meth:`logger.error()<Logger.error()>`
  53. .. |logger.critical| replace:: :meth:`logger.critical()<Logger.critical()>`
  54. .. |file-like object| replace:: ``file-like object``
  55. .. _file-like object: https://docs.python.org/3/glossary.html#term-file-object
  56. .. |callable| replace:: ``callable``
  57. .. _callable: https://docs.python.org/3/library/functions.html#callable
  58. .. |coroutine function| replace:: ``coroutine function``
  59. .. _coroutine function: https://docs.python.org/3/glossary.html#term-coroutine-function
  60. .. |re.Pattern| replace:: ``re.Pattern``
  61. .. _re.Pattern: https://docs.python.org/3/library/re.html#re-objects
  62. .. |multiprocessing.Context| replace:: ``multiprocessing.Context``
  63. .. _multiprocessing.Context:
  64. https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods
  65. .. |better_exceptions| replace:: ``better_exceptions``
  66. .. _better_exceptions: https://github.com/Qix-/better-exceptions
  67. .. |loguru-config| replace:: ``loguru-config``
  68. .. _loguru-config: https://github.com/erezinman/loguru-config
  69. .. _Pendulum: https://pendulum.eustace.io/docs/#tokens
  70. .. _@Qix-: https://github.com/Qix-
  71. .. _@erezinman: https://github.com/erezinman
  72. .. _@sdispater: https://github.com/sdispater
  73. .. _formatting directives: https://docs.python.org/3/library/string.html#format-string-syntax
  74. .. _reentrant: https://en.wikipedia.org/wiki/Reentrancy_(computing)
  75. """
  76. import builtins
  77. import contextlib
  78. import functools
  79. import logging
  80. import re
  81. import sys
  82. import threading
  83. import warnings
  84. from collections import namedtuple
  85. from inspect import isclass, iscoroutinefunction, isgeneratorfunction
  86. from multiprocessing import current_process, get_context
  87. from multiprocessing.context import BaseContext
  88. from os.path import basename, splitext
  89. from threading import current_thread
  90. from . import _asyncio_loop, _colorama, _defaults, _filters
  91. from ._better_exceptions import ExceptionFormatter
  92. from ._colorizer import Colorizer
  93. from ._contextvars import ContextVar
  94. from ._datetime import aware_now
  95. from ._error_interceptor import ErrorInterceptor
  96. from ._file_sink import FileSink
  97. from ._get_frame import get_frame
  98. from ._handler import Handler
  99. from ._locks_machinery import create_logger_lock
  100. from ._recattrs import RecordException, RecordFile, RecordLevel, RecordProcess, RecordThread
  101. from ._simple_sinks import AsyncSink, CallableSink, StandardSink, StreamSink
  102. if sys.version_info >= (3, 6):
  103. from os import PathLike
  104. else:
  105. from pathlib import PurePath as PathLike
  106. Level = namedtuple("Level", ["name", "no", "color", "icon"]) # noqa: PYI024
  107. start_time = aware_now()
  108. context = ContextVar("loguru_context", default={})
  109. class Core:
  110. def __init__(self):
  111. levels = [
  112. Level(
  113. "TRACE",
  114. _defaults.LOGURU_TRACE_NO,
  115. _defaults.LOGURU_TRACE_COLOR,
  116. _defaults.LOGURU_TRACE_ICON,
  117. ),
  118. Level(
  119. "DEBUG",
  120. _defaults.LOGURU_DEBUG_NO,
  121. _defaults.LOGURU_DEBUG_COLOR,
  122. _defaults.LOGURU_DEBUG_ICON,
  123. ),
  124. Level(
  125. "INFO",
  126. _defaults.LOGURU_INFO_NO,
  127. _defaults.LOGURU_INFO_COLOR,
  128. _defaults.LOGURU_INFO_ICON,
  129. ),
  130. Level(
  131. "SUCCESS",
  132. _defaults.LOGURU_SUCCESS_NO,
  133. _defaults.LOGURU_SUCCESS_COLOR,
  134. _defaults.LOGURU_SUCCESS_ICON,
  135. ),
  136. Level(
  137. "WARNING",
  138. _defaults.LOGURU_WARNING_NO,
  139. _defaults.LOGURU_WARNING_COLOR,
  140. _defaults.LOGURU_WARNING_ICON,
  141. ),
  142. Level(
  143. "ERROR",
  144. _defaults.LOGURU_ERROR_NO,
  145. _defaults.LOGURU_ERROR_COLOR,
  146. _defaults.LOGURU_ERROR_ICON,
  147. ),
  148. Level(
  149. "CRITICAL",
  150. _defaults.LOGURU_CRITICAL_NO,
  151. _defaults.LOGURU_CRITICAL_COLOR,
  152. _defaults.LOGURU_CRITICAL_ICON,
  153. ),
  154. ]
  155. self.levels = {level.name: level for level in levels}
  156. self.levels_ansi_codes = {
  157. **{name: Colorizer.ansify(level.color) for name, level in self.levels.items()},
  158. None: "",
  159. }
  160. # Cache used internally to quickly access level attributes based on their name or severity.
  161. # It can also contain integers as keys, it serves to avoid calling "isinstance()" repeatedly
  162. # when "logger.log()" is used.
  163. self.levels_lookup = {
  164. name: (name, name, level.no, level.icon) for name, level in self.levels.items()
  165. }
  166. self.handlers_count = 0
  167. self.handlers = {}
  168. self.extra = {}
  169. self.patcher = None
  170. self.min_level = float("inf")
  171. self.enabled = {}
  172. self.activation_list = []
  173. self.activation_none = True
  174. self.thread_locals = threading.local()
  175. self.lock = create_logger_lock()
  176. def __getstate__(self):
  177. state = self.__dict__.copy()
  178. state["thread_locals"] = None
  179. state["lock"] = None
  180. return state
  181. def __setstate__(self, state):
  182. self.__dict__.update(state)
  183. self.thread_locals = threading.local()
  184. self.lock = create_logger_lock()
  185. class Logger:
  186. """An object to dispatch logging messages to configured handlers.
  187. The |Logger| is the core object of ``loguru``, every logging configuration and usage pass
  188. through a call to one of its methods. There is only one logger, so there is no need to retrieve
  189. one before usage.
  190. Once the ``logger`` is imported, it can be used to write messages about events happening in your
  191. code. By reading the output logs of your application, you gain a better understanding of the
  192. flow of your program and you more easily track and debug unexpected behaviors.
  193. Handlers to which the logger sends log messages are added using the |add| method. Note that you
  194. can use the |Logger| right after import as it comes pre-configured (logs are emitted to
  195. |sys.stderr| by default). Messages can be logged with different severity levels and they can be
  196. formatted using curly braces (it uses |str.format| under the hood).
  197. When a message is logged, a "record" is associated with it. This record is a dict which contains
  198. information about the logging context: time, function, file, line, thread, level... It also
  199. contains the ``__name__`` of the module, this is why you don't need named loggers.
  200. You should not instantiate a |Logger| by yourself, use ``from loguru import logger`` instead.
  201. """
  202. def __init__(self, core, exception, depth, record, lazy, colors, raw, capture, patchers, extra):
  203. self._core = core
  204. self._options = (exception, depth, record, lazy, colors, raw, capture, patchers, extra)
  205. def __repr__(self):
  206. return "<loguru.logger handlers=%r>" % list(self._core.handlers.values())
  207. def add(
  208. self,
  209. sink,
  210. *,
  211. level=_defaults.LOGURU_LEVEL,
  212. format=_defaults.LOGURU_FORMAT,
  213. filter=_defaults.LOGURU_FILTER,
  214. colorize=_defaults.LOGURU_COLORIZE,
  215. serialize=_defaults.LOGURU_SERIALIZE,
  216. backtrace=_defaults.LOGURU_BACKTRACE,
  217. diagnose=_defaults.LOGURU_DIAGNOSE,
  218. enqueue=_defaults.LOGURU_ENQUEUE,
  219. context=_defaults.LOGURU_CONTEXT,
  220. catch=_defaults.LOGURU_CATCH,
  221. **kwargs
  222. ):
  223. r"""Add a handler sending log messages to a sink adequately configured.
  224. Parameters
  225. ----------
  226. sink : |file-like object|_, |str|, |Path|, |callable|_, |coroutine function|_ or |Handler|
  227. An object in charge of receiving formatted logging messages and propagating them to an
  228. appropriate endpoint.
  229. level : |int| or |str|, optional
  230. The minimum severity level from which logged messages should be sent to the sink.
  231. format : |str| or |callable|_, optional
  232. The template used to format logged messages before being sent to the sink.
  233. filter : |callable|_, |str| or |dict|, optional
  234. A directive optionally used to decide for each logged message whether it should be sent
  235. to the sink or not.
  236. colorize : |bool|, optional
  237. Whether the color markups contained in the formatted message should be converted to ansi
  238. codes for terminal coloration, or stripped otherwise. If ``None``, the choice is
  239. automatically made based on the sink being a tty or not.
  240. serialize : |bool|, optional
  241. Whether the logged message and its records should be first converted to a JSON string
  242. before being sent to the sink.
  243. backtrace : |bool|, optional
  244. Whether the exception trace formatted should be extended upward, beyond the catching
  245. point, to show the full stacktrace which generated the error.
  246. diagnose : |bool|, optional
  247. Whether the exception trace should display the variables values to eases the debugging.
  248. This should be set to ``False`` in production to avoid leaking sensitive data.
  249. enqueue : |bool|, optional
  250. Whether the messages to be logged should first pass through a multiprocessing-safe queue
  251. before reaching the sink. This is useful while logging to a file through multiple
  252. processes. This also has the advantage of making logging calls non-blocking.
  253. context : |multiprocessing.Context| or |str|, optional
  254. A context object or name that will be used for all tasks involving internally the
  255. |multiprocessing| module, in particular when ``enqueue=True``. If ``None``, the default
  256. context is used.
  257. catch : |bool|, optional
  258. Whether errors occurring while sink handles logs messages should be automatically
  259. caught. If ``True``, an exception message is displayed on |sys.stderr| but the exception
  260. is not propagated to the caller, preventing your app to crash.
  261. **kwargs
  262. Additional parameters that are only valid to configure a coroutine or file sink (see
  263. below).
  264. If and only if the sink is a coroutine function, the following parameter applies:
  265. Parameters
  266. ----------
  267. loop : |AbstractEventLoop|, optional
  268. The event loop in which the asynchronous logging task will be scheduled and executed. If
  269. ``None``, the loop used is the one returned by |asyncio.get_running_loop| at the time of
  270. the logging call (task is discarded if there is no loop currently running).
  271. If and only if the sink is a file path, the following parameters apply:
  272. Parameters
  273. ----------
  274. rotation : |str|, |int|, |time|, |timedelta| or |callable|_, optional
  275. A condition indicating whenever the current logged file should be closed and a new one
  276. started.
  277. retention : |str|, |int|, |timedelta| or |callable|_, optional
  278. A directive filtering old files that should be removed during rotation or end of
  279. program.
  280. compression : |str| or |callable|_, optional
  281. A compression or archive format to which log files should be converted at closure.
  282. delay : |bool|, optional
  283. Whether the file should be created as soon as the sink is configured, or delayed until
  284. first logged message. It defaults to ``False``.
  285. watch : |bool|, optional
  286. Whether or not the file should be watched and re-opened when deleted or changed (based
  287. on its device and inode properties) by an external program. It defaults to ``False``.
  288. mode : |str|, optional
  289. The opening mode as for built-in |open| function. It defaults to ``"a"`` (open the
  290. file in appending mode).
  291. buffering : |int|, optional
  292. The buffering policy as for built-in |open| function. It defaults to ``1`` (line
  293. buffered file).
  294. encoding : |str|, optional
  295. The file encoding as for built-in |open| function. It defaults to ``"utf8"``.
  296. **kwargs
  297. Others parameters are passed to the built-in |open| function.
  298. Returns
  299. -------
  300. :class:`int`
  301. An identifier associated with the added sink and which should be used to
  302. |remove| it.
  303. Raises
  304. ------
  305. ValueError
  306. If any of the arguments passed to configure the sink is invalid.
  307. Notes
  308. -----
  309. Extended summary follows.
  310. .. _sink:
  311. .. rubric:: The sink parameter
  312. The ``sink`` handles incoming log messages and proceed to their writing somewhere and
  313. somehow. A sink can take many forms:
  314. - A |file-like object|_ like ``sys.stderr`` or ``open("file.log", "w")``. Anything with
  315. a ``.write()`` method is considered as a file-like object. Custom handlers may also
  316. implement ``flush()`` (called after each logged message), ``stop()`` (called at sink
  317. termination) and ``complete()`` (awaited by the eponymous method).
  318. - A file path as |str| or |Path|. It can be parametrized with some additional parameters,
  319. see below.
  320. - A |callable|_ (such as a simple function) like ``lambda msg: print(msg)``. This
  321. allows for logging procedure entirely defined by user preferences and needs.
  322. - A asynchronous |coroutine function|_ defined with the ``async def`` statement. The
  323. coroutine object returned by such function will be added to the event loop using
  324. |loop.create_task|. The tasks should be awaited before ending the loop by using
  325. |complete|.
  326. - A built-in |Handler| like ``logging.StreamHandler``. In such a case, the `Loguru` records
  327. are automatically converted to the structure expected by the |logging| module.
  328. Note that the logging functions are not `reentrant`_. This means you should avoid using
  329. the ``logger`` inside any of your sinks or from within |signal| handlers. Otherwise, you
  330. may face deadlock if the module's sink was not explicitly disabled.
  331. .. _message:
  332. .. rubric:: The logged message
  333. The logged message passed to all added sinks is nothing more than a string of the
  334. formatted log, to which a special attribute is associated: the ``.record`` which is a dict
  335. containing all contextual information possibly needed (see below).
  336. Logged messages are formatted according to the ``format`` of the added sink. This format
  337. is usually a string containing braces fields to display attributes from the record dict.
  338. If fine-grained control is needed, the ``format`` can also be a function which takes the
  339. record as parameter and return the format template string. However, note that in such a
  340. case, you should take care of appending the line ending and exception field to the returned
  341. format, while ``"\n{exception}"`` is automatically appended for convenience if ``format`` is
  342. a string.
  343. The ``filter`` attribute can be used to control which messages are effectively passed to the
  344. sink and which one are ignored. A function can be used, accepting the record as an
  345. argument, and returning ``True`` if the message should be logged, ``False`` otherwise. If
  346. a string is used, only the records with the same ``name`` and its children will be allowed.
  347. One can also pass a ``dict`` mapping module names to minimum required level. In such case,
  348. each log record will search for it's closest parent in the ``dict`` and use the associated
  349. level as the filter. The ``dict`` values can be ``int`` severity, ``str`` level name or
  350. ``True`` and ``False`` to respectively authorize and discard all module logs
  351. unconditionally. In order to set a default level, the ``""`` module name should be used as
  352. it is the parent of all modules (it does not suppress global ``level`` threshold, though).
  353. Note that while calling a logging method, the keyword arguments (if any) are automatically
  354. added to the ``extra`` dict for convenient contextualization (in addition to being used for
  355. formatting).
  356. .. _levels:
  357. .. rubric:: The severity levels
  358. Each logged message is associated with a severity level. These levels make it possible to
  359. prioritize messages and to choose the verbosity of the logs according to usages. For
  360. example, it allows to display some debugging information to a developer, while hiding it to
  361. the end user running the application.
  362. The ``level`` attribute of every added sink controls the minimum threshold from which log
  363. messages are allowed to be emitted. While using the ``logger``, you are in charge of
  364. configuring the appropriate granularity of your logs. It is possible to add even more custom
  365. levels by using the |level| method.
  366. Here are the standard levels with their default severity value, each one is associated with
  367. a logging method of the same name:
  368. +----------------------+------------------------+------------------------+
  369. | Level name | Severity value | Logger method |
  370. +======================+========================+========================+
  371. | ``TRACE`` | 5 | |logger.trace| |
  372. +----------------------+------------------------+------------------------+
  373. | ``DEBUG`` | 10 | |logger.debug| |
  374. +----------------------+------------------------+------------------------+
  375. | ``INFO`` | 20 | |logger.info| |
  376. +----------------------+------------------------+------------------------+
  377. | ``SUCCESS`` | 25 | |logger.success| |
  378. +----------------------+------------------------+------------------------+
  379. | ``WARNING`` | 30 | |logger.warning| |
  380. +----------------------+------------------------+------------------------+
  381. | ``ERROR`` | 40 | |logger.error| |
  382. +----------------------+------------------------+------------------------+
  383. | ``CRITICAL`` | 50 | |logger.critical| |
  384. +----------------------+------------------------+------------------------+
  385. .. _record:
  386. .. rubric:: The record dict
  387. The record is just a Python dict, accessible from sinks by ``message.record``. It contains
  388. all contextual information of the logging call (time, function, file, line, level, etc.).
  389. Each of the record keys can be used in the handler's ``format`` so the corresponding value
  390. is properly displayed in the logged message (e.g. ``"{level}"`` will return ``"INFO"``).
  391. Some records' values are objects with two or more attributes. These can be formatted with
  392. ``"{key.attr}"`` (``"{key}"`` would display one by default).
  393. Note that you can use any `formatting directives`_ available in Python's ``str.format()``
  394. method (e.g. ``"{key: >3}"`` will right-align and pad to a width of 3 characters). This is
  395. particularly useful for time formatting (see below).
  396. +------------+---------------------------------+----------------------------+
  397. | Key | Description | Attributes |
  398. +============+=================================+============================+
  399. | elapsed | The time elapsed since the | See |timedelta| |
  400. | | start of the program | |
  401. +------------+---------------------------------+----------------------------+
  402. | exception | The formatted exception if any, | ``type``, ``value``, |
  403. | | ``None`` otherwise | ``traceback`` |
  404. +------------+---------------------------------+----------------------------+
  405. | extra | The dict of attributes | None |
  406. | | bound by the user (see |bind|) | |
  407. +------------+---------------------------------+----------------------------+
  408. | file | The file where the logging call | ``name`` (default), |
  409. | | was made | ``path`` |
  410. +------------+---------------------------------+----------------------------+
  411. | function | The function from which the | None |
  412. | | logging call was made | |
  413. +------------+---------------------------------+----------------------------+
  414. | level | The severity used to log the | ``name`` (default), |
  415. | | message | ``no``, ``icon`` |
  416. +------------+---------------------------------+----------------------------+
  417. | line | The line number in the source | None |
  418. | | code | |
  419. +------------+---------------------------------+----------------------------+
  420. | message | The logged message (not yet | None |
  421. | | formatted) | |
  422. +------------+---------------------------------+----------------------------+
  423. | module | The module where the logging | None |
  424. | | call was made | |
  425. +------------+---------------------------------+----------------------------+
  426. | name | The ``__name__`` where the | None |
  427. | | logging call was made | |
  428. +------------+---------------------------------+----------------------------+
  429. | process | The process in which the | ``name``, ``id`` (default) |
  430. | | logging call was made | |
  431. +------------+---------------------------------+----------------------------+
  432. | thread | The thread in which the | ``name``, ``id`` (default) |
  433. | | logging call was made | |
  434. +------------+---------------------------------+----------------------------+
  435. | time | The aware local time when the | See |datetime| |
  436. | | logging call was made | |
  437. +------------+---------------------------------+----------------------------+
  438. .. _time:
  439. .. rubric:: The time formatting
  440. To use your favorite time representation, you can set it directly in the time formatter
  441. specifier of your handler format, like for example ``format="{time:HH:mm:ss} {message}"``.
  442. Note that this datetime represents your local time, and it is also made timezone-aware,
  443. so you can display the UTC offset to avoid ambiguities.
  444. The time field can be formatted using more human-friendly tokens. These constitute a subset
  445. of the one used by the `Pendulum`_ library of `@sdispater`_. To escape a token, just add
  446. square brackets around it, for example ``"[YY]"`` would display literally ``"YY"``.
  447. If you prefer to display UTC rather than local time, you can add ``"!UTC"`` at the very end
  448. of the time format, like ``{time:HH:mm:ss!UTC}``. Doing so will convert the ``datetime``
  449. to UTC before formatting.
  450. If no time formatter specifier is used, like for example if ``format="{time} {message}"``,
  451. the default one will use ISO 8601.
  452. +------------------------+---------+----------------------------------------+
  453. | | Token | Output |
  454. +========================+=========+========================================+
  455. | Year | YYYY | 2000, 2001, 2002 ... 2012, 2013 |
  456. | +---------+----------------------------------------+
  457. | | YY | 00, 01, 02 ... 12, 13 |
  458. +------------------------+---------+----------------------------------------+
  459. | Quarter | Q | 1 2 3 4 |
  460. +------------------------+---------+----------------------------------------+
  461. | Month | MMMM | January, February, March ... |
  462. | +---------+----------------------------------------+
  463. | | MMM | Jan, Feb, Mar ... |
  464. | +---------+----------------------------------------+
  465. | | MM | 01, 02, 03 ... 11, 12 |
  466. | +---------+----------------------------------------+
  467. | | M | 1, 2, 3 ... 11, 12 |
  468. +------------------------+---------+----------------------------------------+
  469. | Day of Year | DDDD | 001, 002, 003 ... 364, 365 |
  470. | +---------+----------------------------------------+
  471. | | DDD | 1, 2, 3 ... 364, 365 |
  472. +------------------------+---------+----------------------------------------+
  473. | Day of Month | DD | 01, 02, 03 ... 30, 31 |
  474. | +---------+----------------------------------------+
  475. | | D | 1, 2, 3 ... 30, 31 |
  476. +------------------------+---------+----------------------------------------+
  477. | Day of Week | dddd | Monday, Tuesday, Wednesday ... |
  478. | +---------+----------------------------------------+
  479. | | ddd | Mon, Tue, Wed ... |
  480. | +---------+----------------------------------------+
  481. | | d | 0, 1, 2 ... 6 |
  482. +------------------------+---------+----------------------------------------+
  483. | Days of ISO Week | E | 1, 2, 3 ... 7 |
  484. +------------------------+---------+----------------------------------------+
  485. | Hour | HH | 00, 01, 02 ... 23, 24 |
  486. | +---------+----------------------------------------+
  487. | | H | 0, 1, 2 ... 23, 24 |
  488. | +---------+----------------------------------------+
  489. | | hh | 01, 02, 03 ... 11, 12 |
  490. | +---------+----------------------------------------+
  491. | | h | 1, 2, 3 ... 11, 12 |
  492. +------------------------+---------+----------------------------------------+
  493. | Minute | mm | 00, 01, 02 ... 58, 59 |
  494. | +---------+----------------------------------------+
  495. | | m | 0, 1, 2 ... 58, 59 |
  496. +------------------------+---------+----------------------------------------+
  497. | Second | ss | 00, 01, 02 ... 58, 59 |
  498. | +---------+----------------------------------------+
  499. | | s | 0, 1, 2 ... 58, 59 |
  500. +------------------------+---------+----------------------------------------+
  501. | Fractional Second | S | 0 1 ... 8 9 |
  502. | +---------+----------------------------------------+
  503. | | SS | 00, 01, 02 ... 98, 99 |
  504. | +---------+----------------------------------------+
  505. | | SSS | 000 001 ... 998 999 |
  506. | +---------+----------------------------------------+
  507. | | SSSS... | 000[0..] 001[0..] ... 998[0..] 999[0..]|
  508. | +---------+----------------------------------------+
  509. | | SSSSSS | 000000 000001 ... 999998 999999 |
  510. +------------------------+---------+----------------------------------------+
  511. | AM / PM | A | AM, PM |
  512. +------------------------+---------+----------------------------------------+
  513. | Timezone | Z | -07:00, -06:00 ... +06:00, +07:00 |
  514. | +---------+----------------------------------------+
  515. | | ZZ | -0700, -0600 ... +0600, +0700 |
  516. | +---------+----------------------------------------+
  517. | | zz | EST CST ... MST PST |
  518. +------------------------+---------+----------------------------------------+
  519. | Seconds timestamp | X | 1381685817, 1234567890.123 |
  520. +------------------------+---------+----------------------------------------+
  521. | Microseconds timestamp | x | 1234567890123 |
  522. +------------------------+---------+----------------------------------------+
  523. .. _file:
  524. .. rubric:: The file sinks
  525. If the sink is a |str| or a |Path|, the corresponding file will be opened for writing logs.
  526. The path can also contain a special ``"{time}"`` field that will be formatted with the
  527. current date at file creation. The file is closed at sink stop, i.e. when the application
  528. ends or the handler is removed.
  529. The ``rotation`` check is made before logging each message. If there is already an existing
  530. file with the same name that the file to be created, then the existing file is renamed by
  531. appending the date to its basename to prevent file overwriting. This parameter accepts:
  532. - an |int| which corresponds to the maximum file size in bytes before that the current
  533. logged file is closed and a new one started over.
  534. - a |timedelta| which indicates the frequency of each new rotation.
  535. - a |time| which specifies the hour when the daily rotation should occur.
  536. - a |str| for human-friendly parametrization of one of the previously enumerated types.
  537. Examples: ``"100 MB"``, ``"0.5 GB"``, ``"1 month 2 weeks"``, ``"4 days"``, ``"10h"``,
  538. ``"monthly"``, ``"18:00"``, ``"sunday"``, ``"w0"``, ``"monday at 12:00"``, ...
  539. - a |callable|_ which will be invoked before logging. It should accept two arguments: the
  540. logged message and the file object, and it should return ``True`` if the rotation should
  541. happen now, ``False`` otherwise.
  542. The ``retention`` occurs at rotation or at sink stop if rotation is ``None``. Files
  543. resulting from previous sessions or rotations are automatically collected from disk. A file
  544. is selected if it matches the pattern ``"basename(.*).ext(.*)"`` (possible time fields are
  545. beforehand replaced with ``.*``) based on the configured sink. Afterwards, the list is
  546. processed to determine files to be retained. This parameter accepts:
  547. - an |int| which indicates the number of log files to keep, while older files are deleted.
  548. - a |timedelta| which specifies the maximum age of files to keep.
  549. - a |str| for human-friendly parametrization of the maximum age of files to keep.
  550. Examples: ``"1 week, 3 days"``, ``"2 months"``, ...
  551. - a |callable|_ which will be invoked before the retention process. It should accept the
  552. list of log files as argument and process to whatever it wants (moving files, removing
  553. them, etc.).
  554. The ``compression`` happens at rotation or at sink stop if rotation is ``None``. This
  555. parameter accepts:
  556. - a |str| which corresponds to the compressed or archived file extension. This can be one
  557. of: ``"gz"``, ``"bz2"``, ``"xz"``, ``"lzma"``, ``"tar"``, ``"tar.gz"``, ``"tar.bz2"``,
  558. ``"tar.xz"``, ``"zip"``.
  559. - a |callable|_ which will be invoked before file termination. It should accept the path of
  560. the log file as argument and process to whatever it wants (custom compression, network
  561. sending, removing it, etc.).
  562. Either way, if you use a custom function designed according to your preferences, you must be
  563. very careful not to use the ``logger`` within your function. Otherwise, there is a risk that
  564. your program hang because of a deadlock.
  565. .. _color:
  566. .. rubric:: The color markups
  567. To add colors to your logs, you just have to enclose your format string with the appropriate
  568. tags (e.g. ``<red>some message</red>``). These tags are automatically removed if the sink
  569. doesn't support ansi codes. For convenience, you can use ``</>`` to close the last opening
  570. tag without repeating its name (e.g. ``<red>another message</>``).
  571. The special tag ``<level>`` (abbreviated with ``<lvl>``) is transformed according to
  572. the configured color of the logged message level.
  573. Tags which are not recognized will raise an exception during parsing, to inform you about
  574. possible misuse. If you wish to display a markup tag literally, you can escape it by
  575. prepending a ``\`` like for example ``\<blue>``. To prevent the escaping to occur, you can
  576. simply double the ``\`` (e.g. ``\\<blue>`` will print a literal ``\`` before colored text).
  577. If, for some reason, you need to escape a string programmatically, note that the regex used
  578. internally to parse markup tags is ``r"(\\*)(</?(?:[fb]g\s)?[^<>\s]*>)"``.
  579. Note that when logging a message with ``opt(colors=True)``, color tags present in the
  580. formatting arguments (``args`` and ``kwargs``) are completely ignored. This is important if
  581. you need to log strings containing markups that might interfere with the color tags (in this
  582. case, do not use f-string).
  583. Here are the available tags (note that compatibility may vary depending on terminal):
  584. +------------------------------------+--------------------------------------+
  585. | Color (abbr) | Styles (abbr) |
  586. +====================================+======================================+
  587. | Black (k) | Bold (b) |
  588. +------------------------------------+--------------------------------------+
  589. | Blue (e) | Dim (d) |
  590. +------------------------------------+--------------------------------------+
  591. | Cyan (c) | Normal (n) |
  592. +------------------------------------+--------------------------------------+
  593. | Green (g) | Italic (i) |
  594. +------------------------------------+--------------------------------------+
  595. | Magenta (m) | Underline (u) |
  596. +------------------------------------+--------------------------------------+
  597. | Red (r) | Strike (s) |
  598. +------------------------------------+--------------------------------------+
  599. | White (w) | Reverse (v) |
  600. +------------------------------------+--------------------------------------+
  601. | Yellow (y) | Blink (l) |
  602. +------------------------------------+--------------------------------------+
  603. | | Hide (h) |
  604. +------------------------------------+--------------------------------------+
  605. Usage:
  606. +-----------------+-------------------------------------------------------------------+
  607. | Description | Examples |
  608. | +---------------------------------+---------------------------------+
  609. | | Foreground | Background |
  610. +=================+=================================+=================================+
  611. | Basic colors | ``<red>``, ``<r>`` | ``<GREEN>``, ``<G>`` |
  612. +-----------------+---------------------------------+---------------------------------+
  613. | Light colors | ``<light-blue>``, ``<le>`` | ``<LIGHT-CYAN>``, ``<LC>`` |
  614. +-----------------+---------------------------------+---------------------------------+
  615. | 8-bit colors | ``<fg 86>``, ``<fg 255>`` | ``<bg 42>``, ``<bg 9>`` |
  616. +-----------------+---------------------------------+---------------------------------+
  617. | Hex colors | ``<fg #00005f>``, ``<fg #EE1>`` | ``<bg #AF5FD7>``, ``<bg #fff>`` |
  618. +-----------------+---------------------------------+---------------------------------+
  619. | RGB colors | ``<fg 0,95,0>`` | ``<bg 72,119,65>`` |
  620. +-----------------+---------------------------------+---------------------------------+
  621. | Stylizing | ``<bold>``, ``<b>``, ``<underline>``, ``<u>`` |
  622. +-----------------+-------------------------------------------------------------------+
  623. .. _env:
  624. .. rubric:: The environment variables
  625. The default values of sink parameters can be entirely customized. This is particularly
  626. useful if you don't like the log format of the pre-configured sink.
  627. Each of the |add| default parameter can be modified by setting the ``LOGURU_[PARAM]``
  628. environment variable. For example on Linux: ``export LOGURU_FORMAT="{time} - {message}"``
  629. or ``export LOGURU_DIAGNOSE=NO``.
  630. The default levels' attributes can also be modified by setting the ``LOGURU_[LEVEL]_[ATTR]``
  631. environment variable. For example, on Windows: ``setx LOGURU_DEBUG_COLOR "<blue>"``
  632. or ``setx LOGURU_TRACE_ICON "🚀"``. If you use the ``set`` command, do not include quotes
  633. but escape special symbol as needed, e.g. ``set LOGURU_DEBUG_COLOR=^<blue^>``.
  634. If you want to disable the pre-configured sink, you can set the ``LOGURU_AUTOINIT``
  635. variable to ``False``.
  636. On Linux, you will probably need to edit the ``~/.profile`` file to make this persistent. On
  637. Windows, don't forget to restart your terminal for the change to be taken into account.
  638. Examples
  639. --------
  640. >>> logger.add(sys.stdout, format="{time} - {level} - {message}", filter="sub.module")
  641. >>> logger.add("file_{time}.log", level="TRACE", rotation="100 MB")
  642. >>> def debug_only(record):
  643. ... return record["level"].name == "DEBUG"
  644. ...
  645. >>> logger.add("debug.log", filter=debug_only) # Other levels are filtered out
  646. >>> def my_sink(message):
  647. ... record = message.record
  648. ... update_db(message, time=record["time"], level=record["level"])
  649. ...
  650. >>> logger.add(my_sink)
  651. >>> level_per_module = {
  652. ... "": "DEBUG",
  653. ... "third.lib": "WARNING",
  654. ... "anotherlib": False
  655. ... }
  656. >>> logger.add(lambda m: print(m, end=""), filter=level_per_module, level=0)
  657. >>> async def publish(message):
  658. ... await api.post(message)
  659. ...
  660. >>> logger.add(publish, serialize=True)
  661. >>> from logging import StreamHandler
  662. >>> logger.add(StreamHandler(sys.stderr), format="{message}")
  663. >>> class RandomStream:
  664. ... def __init__(self, seed, threshold):
  665. ... self.threshold = threshold
  666. ... random.seed(seed)
  667. ... def write(self, message):
  668. ... if random.random() > self.threshold:
  669. ... print(message)
  670. ...
  671. >>> stream_object = RandomStream(seed=12345, threshold=0.25)
  672. >>> logger.add(stream_object, level="INFO")
  673. """
  674. with self._core.lock:
  675. handler_id = self._core.handlers_count
  676. self._core.handlers_count += 1
  677. error_interceptor = ErrorInterceptor(catch, handler_id)
  678. if colorize is None and serialize:
  679. colorize = False
  680. if isinstance(sink, (str, PathLike)):
  681. path = sink
  682. name = "'%s'" % path
  683. if colorize is None:
  684. colorize = False
  685. wrapped_sink = FileSink(path, **kwargs)
  686. kwargs = {}
  687. encoding = wrapped_sink.encoding
  688. terminator = "\n"
  689. exception_prefix = ""
  690. elif hasattr(sink, "write") and callable(sink.write):
  691. name = getattr(sink, "name", None) or repr(sink)
  692. if colorize is None:
  693. colorize = _colorama.should_colorize(sink)
  694. if colorize is True and _colorama.should_wrap(sink):
  695. stream = _colorama.wrap(sink)
  696. else:
  697. stream = sink
  698. wrapped_sink = StreamSink(stream)
  699. encoding = getattr(sink, "encoding", None)
  700. terminator = "\n"
  701. exception_prefix = ""
  702. elif isinstance(sink, logging.Handler):
  703. name = repr(sink)
  704. if colorize is None:
  705. colorize = False
  706. wrapped_sink = StandardSink(sink)
  707. encoding = getattr(sink, "encoding", None)
  708. terminator = ""
  709. exception_prefix = "\n"
  710. elif iscoroutinefunction(sink) or iscoroutinefunction(
  711. getattr(sink, "__call__", None) # noqa: B004
  712. ):
  713. name = getattr(sink, "__name__", None) or repr(sink)
  714. if colorize is None:
  715. colorize = False
  716. loop = kwargs.pop("loop", None)
  717. # The worker thread needs an event loop, it can't create a new one internally because it
  718. # has to be accessible by the user while calling "complete()", instead we use the global
  719. # one when the sink is added. If "enqueue=False" the event loop is dynamically retrieved
  720. # at each logging call, which is much more convenient. However, coroutine can't access
  721. # running loop in Python 3.5.2 and earlier versions, see python/asyncio#452.
  722. if enqueue and loop is None:
  723. try:
  724. loop = _asyncio_loop.get_running_loop()
  725. except RuntimeError as e:
  726. raise ValueError(
  727. "An event loop is required to add a coroutine sink with `enqueue=True`, "
  728. "but none has been passed as argument and none is currently running."
  729. ) from e
  730. coro = sink if iscoroutinefunction(sink) else sink.__call__
  731. wrapped_sink = AsyncSink(coro, loop, error_interceptor)
  732. encoding = "utf8"
  733. terminator = "\n"
  734. exception_prefix = ""
  735. elif callable(sink):
  736. name = getattr(sink, "__name__", None) or repr(sink)
  737. if colorize is None:
  738. colorize = False
  739. wrapped_sink = CallableSink(sink)
  740. encoding = "utf8"
  741. terminator = "\n"
  742. exception_prefix = ""
  743. else:
  744. raise TypeError("Cannot log to objects of type '%s'" % type(sink).__name__)
  745. if kwargs:
  746. raise TypeError("add() got an unexpected keyword argument '%s'" % next(iter(kwargs)))
  747. if filter is None:
  748. filter_func = None
  749. elif filter == "":
  750. filter_func = _filters.filter_none
  751. elif isinstance(filter, str):
  752. parent = filter + "."
  753. length = len(parent)
  754. filter_func = functools.partial(_filters.filter_by_name, parent=parent, length=length)
  755. elif isinstance(filter, dict):
  756. level_per_module = {}
  757. for module, level_ in filter.items():
  758. if module is not None and not isinstance(module, str):
  759. raise TypeError(
  760. "The filter dict contains an invalid module, "
  761. "it should be a string (or None), not: '%s'" % type(module).__name__
  762. )
  763. if level_ is False:
  764. levelno_ = False
  765. elif level_ is True:
  766. levelno_ = 0
  767. elif isinstance(level_, str):
  768. try:
  769. levelno_ = self.level(level_).no
  770. except ValueError:
  771. raise ValueError(
  772. "The filter dict contains a module '%s' associated to a level name "
  773. "which does not exist: '%s'" % (module, level_)
  774. ) from None
  775. elif isinstance(level_, int):
  776. levelno_ = level_
  777. else:
  778. raise TypeError(
  779. "The filter dict contains a module '%s' associated to an invalid level, "
  780. "it should be an integer, a string or a boolean, not: '%s'"
  781. % (module, type(level_).__name__)
  782. )
  783. if levelno_ < 0:
  784. raise ValueError(
  785. "The filter dict contains a module '%s' associated to an invalid level, "
  786. "it should be a positive integer, not: '%d'" % (module, levelno_)
  787. )
  788. level_per_module[module] = levelno_
  789. filter_func = functools.partial(
  790. _filters.filter_by_level, level_per_module=level_per_module
  791. )
  792. elif callable(filter):
  793. if filter == builtins.filter:
  794. raise ValueError(
  795. "The built-in 'filter()' function cannot be used as a 'filter' parameter, "
  796. "this is most likely a mistake (please double-check the arguments passed "
  797. "to 'logger.add()')."
  798. )
  799. filter_func = filter
  800. else:
  801. raise TypeError(
  802. "Invalid filter, it should be a function, a string or a dict, not: '%s'"
  803. % type(filter).__name__
  804. )
  805. if isinstance(level, str):
  806. levelno = self.level(level).no
  807. elif isinstance(level, int):
  808. levelno = level
  809. else:
  810. raise TypeError(
  811. "Invalid level, it should be an integer or a string, not: '%s'"
  812. % type(level).__name__
  813. )
  814. if levelno < 0:
  815. raise ValueError(
  816. "Invalid level value, it should be a positive integer, not: %d" % levelno
  817. )
  818. if isinstance(format, str):
  819. try:
  820. formatter = Colorizer.prepare_format(format + terminator + "{exception}")
  821. except ValueError as e:
  822. raise ValueError(
  823. "Invalid format, color markups could not be parsed correctly"
  824. ) from e
  825. is_formatter_dynamic = False
  826. elif callable(format):
  827. if format == builtins.format:
  828. raise ValueError(
  829. "The built-in 'format()' function cannot be used as a 'format' parameter, "
  830. "this is most likely a mistake (please double-check the arguments passed "
  831. "to 'logger.add()')."
  832. )
  833. formatter = format
  834. is_formatter_dynamic = True
  835. else:
  836. raise TypeError(
  837. "Invalid format, it should be a string or a function, not: '%s'"
  838. % type(format).__name__
  839. )
  840. if not isinstance(encoding, str):
  841. encoding = "ascii"
  842. if isinstance(context, str):
  843. context = get_context(context)
  844. elif context is not None and not isinstance(context, BaseContext):
  845. raise TypeError(
  846. "Invalid context, it should be a string or a multiprocessing context, "
  847. "not: '%s'" % type(context).__name__
  848. )
  849. with self._core.lock:
  850. exception_formatter = ExceptionFormatter(
  851. colorize=colorize,
  852. encoding=encoding,
  853. diagnose=diagnose,
  854. backtrace=backtrace,
  855. hidden_frames_filename=self.catch.__code__.co_filename,
  856. prefix=exception_prefix,
  857. )
  858. handler = Handler(
  859. name=name,
  860. sink=wrapped_sink,
  861. levelno=levelno,
  862. formatter=formatter,
  863. is_formatter_dynamic=is_formatter_dynamic,
  864. filter_=filter_func,
  865. colorize=colorize,
  866. serialize=serialize,
  867. enqueue=enqueue,
  868. multiprocessing_context=context,
  869. id_=handler_id,
  870. error_interceptor=error_interceptor,
  871. exception_formatter=exception_formatter,
  872. levels_ansi_codes=self._core.levels_ansi_codes,
  873. )
  874. handlers = self._core.handlers.copy()
  875. handlers[handler_id] = handler
  876. self._core.min_level = min(self._core.min_level, levelno)
  877. self._core.handlers = handlers
  878. return handler_id
  879. def remove(self, handler_id=None):
  880. """Remove a previously added handler and stop sending logs to its sink.
  881. Parameters
  882. ----------
  883. handler_id : |int| or ``None``
  884. The id of the sink to remove, as it was returned by the |add| method. If ``None``, all
  885. handlers are removed. The pre-configured handler is guaranteed to have the index ``0``.
  886. Raises
  887. ------
  888. ValueError
  889. If ``handler_id`` is not ``None`` but there is no active handler with such id.
  890. Examples
  891. --------
  892. >>> i = logger.add(sys.stderr, format="{message}")
  893. >>> logger.info("Logging")
  894. Logging
  895. >>> logger.remove(i)
  896. >>> logger.info("No longer logging")
  897. """
  898. if not (handler_id is None or isinstance(handler_id, int)):
  899. raise TypeError(
  900. "Invalid handler id, it should be an integer as returned "
  901. "by the 'add()' method (or None), not: '%s'" % type(handler_id).__name__
  902. )
  903. with self._core.lock:
  904. if handler_id is not None and handler_id not in self._core.handlers:
  905. raise ValueError("There is no existing handler with id %d" % handler_id) from None
  906. if handler_id is None:
  907. handler_ids = list(self._core.handlers)
  908. else:
  909. handler_ids = [handler_id]
  910. for handler_id in handler_ids:
  911. handlers = self._core.handlers.copy()
  912. handler = handlers.pop(handler_id)
  913. # This needs to be done first in case "stop()" raises an exception
  914. levelnos = (h.levelno for h in handlers.values())
  915. self._core.min_level = min(levelnos, default=float("inf"))
  916. self._core.handlers = handlers
  917. handler.stop()
  918. def complete(self):
  919. """Wait for the end of enqueued messages and asynchronous tasks scheduled by handlers.
  920. This method proceeds in two steps: first it waits for all logging messages added to handlers
  921. with ``enqueue=True`` to be processed, then it returns an object that can be awaited to
  922. finalize all logging tasks added to the event loop by coroutine sinks.
  923. It can be called from non-asynchronous code. This is especially recommended when the
  924. ``logger`` is utilized with ``multiprocessing`` to ensure messages put to the internal
  925. queue have been properly transmitted before leaving a child process.
  926. The returned object should be awaited before the end of a coroutine executed by
  927. |asyncio.run| or |loop.run_until_complete| to ensure all asynchronous logging messages are
  928. processed. The function |asyncio.get_running_loop| is called beforehand, only tasks
  929. scheduled in the same loop that the current one will be awaited by the method.
  930. Returns
  931. -------
  932. :term:`awaitable`
  933. An awaitable object which ensures all asynchronous logging calls are completed when
  934. awaited.
  935. Examples
  936. --------
  937. >>> async def sink(message):
  938. ... await asyncio.sleep(0.1) # IO processing...
  939. ... print(message, end="")
  940. ...
  941. >>> async def work():
  942. ... logger.info("Start")
  943. ... logger.info("End")
  944. ... await logger.complete()
  945. ...
  946. >>> logger.add(sink)
  947. 1
  948. >>> asyncio.run(work())
  949. Start
  950. End
  951. >>> def process():
  952. ... logger.info("Message sent from the child")
  953. ... logger.complete()
  954. ...
  955. >>> logger.add(sys.stderr, enqueue=True)
  956. 1
  957. >>> process = multiprocessing.Process(target=process)
  958. >>> process.start()
  959. >>> process.join()
  960. Message sent from the child
  961. """
  962. tasks = []
  963. with self._core.lock:
  964. handlers = self._core.handlers.copy()
  965. for handler in handlers.values():
  966. handler.complete_queue()
  967. tasks.extend(handler.tasks_to_complete())
  968. class AwaitableCompleter:
  969. def __await__(self):
  970. for task in tasks:
  971. yield from task.__await__()
  972. return AwaitableCompleter()
  973. def catch(
  974. self,
  975. exception=Exception,
  976. *,
  977. level="ERROR",
  978. reraise=False,
  979. onerror=None,
  980. exclude=None,
  981. default=None,
  982. message="An error has been caught in function '{record[function]}', "
  983. "process '{record[process].name}' ({record[process].id}), "
  984. "thread '{record[thread].name}' ({record[thread].id}):"
  985. ):
  986. """Return a decorator to automatically log possibly caught error in wrapped function.
  987. This is useful to ensure unexpected exceptions are logged, the entire program can be
  988. wrapped by this method. This is also very useful to decorate |Thread.run| methods while
  989. using threads to propagate errors to the main logger thread.
  990. Note that the visibility of variables values (which uses the great |better_exceptions|_
  991. library from `@Qix-`_) depends on the ``diagnose`` option of each configured sink.
  992. The returned object can also be used as a context manager.
  993. Parameters
  994. ----------
  995. exception : |Exception|, optional
  996. The type of exception to intercept. If several types should be caught, a tuple of
  997. exceptions can be used too.
  998. level : |str| or |int|, optional
  999. The level name or severity with which the message should be logged.
  1000. reraise : |bool|, optional
  1001. Whether the exception should be raised again and hence propagated to the caller.
  1002. onerror : |callable|_, optional
  1003. A function that will be called if an error occurs, once the message has been logged.
  1004. It should accept the exception instance as it sole argument.
  1005. exclude : |Exception|, optional
  1006. A type of exception (or a tuple of types) that will be purposely ignored and hence
  1007. propagated to the caller without being logged.
  1008. default : |Any|, optional
  1009. The value to be returned by the decorated function if an error occurred without being
  1010. re-raised.
  1011. message : |str|, optional
  1012. The message that will be automatically logged if an exception occurs. Note that it will
  1013. be formatted with the ``record`` attribute.
  1014. Returns
  1015. -------
  1016. :term:`decorator` / :term:`context manager`
  1017. An object that can be used to decorate a function or as a context manager to log
  1018. exceptions possibly caught.
  1019. Examples
  1020. --------
  1021. >>> @logger.catch
  1022. ... def f(x):
  1023. ... 100 / x
  1024. ...
  1025. >>> def g():
  1026. ... f(10)
  1027. ... f(0)
  1028. ...
  1029. >>> g()
  1030. ERROR - An error has been caught in function 'g', process 'Main' (367), thread 'ch1' (1398):
  1031. Traceback (most recent call last):
  1032. File "program.py", line 12, in <module>
  1033. g()
  1034. └ <function g at 0x7f225fe2bc80>
  1035. > File "program.py", line 10, in g
  1036. f(0)
  1037. └ <function f at 0x7f225fe2b9d8>
  1038. File "program.py", line 6, in f
  1039. 100 / x
  1040. └ 0
  1041. ZeroDivisionError: division by zero
  1042. >>> with logger.catch(message="Because we never know..."):
  1043. ... main() # No exception, no logs
  1044. >>> # Use 'onerror' to prevent the program exit code to be 0 (if 'reraise=False') while
  1045. >>> # also avoiding the stacktrace to be duplicated on stderr (if 'reraise=True').
  1046. >>> @logger.catch(onerror=lambda _: sys.exit(1))
  1047. ... def main():
  1048. ... 1 / 0
  1049. """
  1050. if callable(exception) and (
  1051. not isclass(exception) or not issubclass(exception, BaseException)
  1052. ):
  1053. return self.catch()(exception)
  1054. logger = self
  1055. class Catcher:
  1056. def __init__(self, from_decorator):
  1057. self._from_decorator = from_decorator
  1058. def __enter__(self):
  1059. return None
  1060. def __exit__(self, type_, value, traceback_):
  1061. if type_ is None:
  1062. return None
  1063. # We must prevent infinite recursion in case "logger.catch()" handles an exception
  1064. # that occurs while logging another exception. This can happen for example when
  1065. # the exception formatter calls "repr(obj)" while the "__repr__" method is broken
  1066. # but decorated with "logger.catch()". In such a case, we ignore the catching
  1067. # mechanism and just let the exception be thrown (that way, the formatter will
  1068. # rightly assume the object is unprintable).
  1069. if getattr(logger._core.thread_locals, "already_logging_exception", False):
  1070. return False
  1071. if not issubclass(type_, exception):
  1072. return False
  1073. if exclude is not None and issubclass(type_, exclude):
  1074. return False
  1075. from_decorator = self._from_decorator
  1076. _, depth, _, *options = logger._options
  1077. if from_decorator:
  1078. depth += 1
  1079. catch_options = [(type_, value, traceback_), depth, True, *options]
  1080. logger._core.thread_locals.already_logging_exception = True
  1081. try:
  1082. logger._log(level, from_decorator, catch_options, message, (), {})
  1083. finally:
  1084. logger._core.thread_locals.already_logging_exception = False
  1085. if onerror is not None:
  1086. onerror(value)
  1087. return not reraise
  1088. def __call__(self, function):
  1089. if isclass(function):
  1090. raise TypeError(
  1091. "Invalid object decorated with 'catch()', it must be a function, "
  1092. "not a class (tried to wrap '%s')" % function.__name__
  1093. )
  1094. catcher = Catcher(True)
  1095. if iscoroutinefunction(function):
  1096. async def catch_wrapper(*args, **kwargs):
  1097. with catcher:
  1098. return await function(*args, **kwargs)
  1099. return default
  1100. elif isgeneratorfunction(function):
  1101. def catch_wrapper(*args, **kwargs):
  1102. with catcher:
  1103. return (yield from function(*args, **kwargs))
  1104. return default
  1105. else:
  1106. def catch_wrapper(*args, **kwargs):
  1107. with catcher:
  1108. return function(*args, **kwargs)
  1109. return default
  1110. functools.update_wrapper(catch_wrapper, function)
  1111. return catch_wrapper
  1112. return Catcher(False)
  1113. def opt(
  1114. self,
  1115. *,
  1116. exception=None,
  1117. record=False,
  1118. lazy=False,
  1119. colors=False,
  1120. raw=False,
  1121. capture=True,
  1122. depth=0,
  1123. ansi=False
  1124. ):
  1125. r"""Parametrize a logging call to slightly change generated log message.
  1126. Note that it's not possible to chain |opt| calls, the last one takes precedence over the
  1127. others as it will "reset" the options to their default values.
  1128. Parameters
  1129. ----------
  1130. exception : |bool|, |tuple| or |Exception|, optional
  1131. If it does not evaluate as ``False``, the passed exception is formatted and added to the
  1132. log message. It could be an |Exception| object or a ``(type, value, traceback)`` tuple,
  1133. otherwise the exception information is retrieved from |sys.exc_info|.
  1134. record : |bool|, optional
  1135. If ``True``, the record dict contextualizing the logging call can be used to format the
  1136. message by using ``{record[key]}`` in the log message.
  1137. lazy : |bool|, optional
  1138. If ``True``, the logging call attribute to format the message should be functions which
  1139. will be called only if the level is high enough. This can be used to avoid expensive
  1140. functions if not necessary.
  1141. colors : |bool|, optional
  1142. If ``True``, logged message will be colorized according to the markups it possibly
  1143. contains.
  1144. raw : |bool|, optional
  1145. If ``True``, the formatting of each sink will be bypassed and the message will be sent
  1146. as is.
  1147. capture : |bool|, optional
  1148. If ``False``, the ``**kwargs`` of logged message will not automatically populate
  1149. the ``extra`` dict (although they are still used for formatting).
  1150. depth : |int|, optional
  1151. Specify which stacktrace should be used to contextualize the logged message. This is
  1152. useful while using the logger from inside a wrapped function to retrieve worthwhile
  1153. information.
  1154. ansi : |bool|, optional
  1155. Deprecated since version 0.4.1: the ``ansi`` parameter will be removed in Loguru 1.0.0,
  1156. it is replaced by ``colors`` which is a more appropriate name.
  1157. Returns
  1158. -------
  1159. :class:`~Logger`
  1160. A logger wrapping the core logger, but transforming logged message adequately before
  1161. sending.
  1162. Examples
  1163. --------
  1164. >>> try:
  1165. ... 1 / 0
  1166. ... except ZeroDivisionError:
  1167. ... logger.opt(exception=True).debug("Exception logged with debug level:")
  1168. ...
  1169. [18:10:02] DEBUG in '<module>' - Exception logged with debug level:
  1170. Traceback (most recent call last, catch point marked):
  1171. > File "<stdin>", line 2, in <module>
  1172. ZeroDivisionError: division by zero
  1173. >>> logger.opt(record=True).info("Current line is: {record[line]}")
  1174. [18:10:33] INFO in '<module>' - Current line is: 1
  1175. >>> logger.opt(lazy=True).debug("If sink <= DEBUG: {x}", x=lambda: math.factorial(2**5))
  1176. [18:11:19] DEBUG in '<module>' - If sink <= DEBUG: 263130836933693530167218012160000000
  1177. >>> logger.opt(colors=True).warning("We got a <red>BIG</red> problem")
  1178. [18:11:30] WARNING in '<module>' - We got a BIG problem
  1179. >>> logger.opt(raw=True).debug("No formatting\n")
  1180. No formatting
  1181. >>> logger.opt(capture=False).info("Displayed but not captured: {value}", value=123)
  1182. [18:11:41] Displayed but not captured: 123
  1183. >>> def wrapped():
  1184. ... logger.opt(depth=1).info("Get parent context")
  1185. ...
  1186. >>> def func():
  1187. ... wrapped()
  1188. ...
  1189. >>> func()
  1190. [18:11:54] DEBUG in 'func' - Get parent context
  1191. """
  1192. if ansi:
  1193. colors = True
  1194. warnings.warn(
  1195. "The 'ansi' parameter is deprecated, please use 'colors' instead",
  1196. DeprecationWarning,
  1197. stacklevel=2,
  1198. )
  1199. args = self._options[-2:]
  1200. return Logger(self._core, exception, depth, record, lazy, colors, raw, capture, *args)
  1201. def bind(__self, **kwargs): # noqa: N805
  1202. """Bind attributes to the ``extra`` dict of each logged message record.
  1203. This is used to add custom context to each logging call.
  1204. Parameters
  1205. ----------
  1206. **kwargs
  1207. Mapping between keys and values that will be added to the ``extra`` dict.
  1208. Returns
  1209. -------
  1210. :class:`~Logger`
  1211. A logger wrapping the core logger, but which sends record with the customized ``extra``
  1212. dict.
  1213. Examples
  1214. --------
  1215. >>> logger.add(sys.stderr, format="{extra[ip]} - {message}")
  1216. >>> class Server:
  1217. ... def __init__(self, ip):
  1218. ... self.ip = ip
  1219. ... self.logger = logger.bind(ip=ip)
  1220. ... def call(self, message):
  1221. ... self.logger.info(message)
  1222. ...
  1223. >>> instance_1 = Server("192.168.0.200")
  1224. >>> instance_2 = Server("127.0.0.1")
  1225. >>> instance_1.call("First instance")
  1226. 192.168.0.200 - First instance
  1227. >>> instance_2.call("Second instance")
  1228. 127.0.0.1 - Second instance
  1229. """
  1230. *options, extra = __self._options
  1231. return Logger(__self._core, *options, {**extra, **kwargs})
  1232. @contextlib.contextmanager
  1233. def contextualize(__self, **kwargs): # noqa: N805
  1234. """Bind attributes to the context-local ``extra`` dict while inside the ``with`` block.
  1235. Contrary to |bind| there is no ``logger`` returned, the ``extra`` dict is modified in-place
  1236. and updated globally. Most importantly, it uses |contextvars| which means that
  1237. contextualized values are unique to each threads and asynchronous tasks.
  1238. The ``extra`` dict will retrieve its initial state once the context manager is exited.
  1239. Parameters
  1240. ----------
  1241. **kwargs
  1242. Mapping between keys and values that will be added to the context-local ``extra`` dict.
  1243. Returns
  1244. -------
  1245. :term:`context manager` / :term:`decorator`
  1246. A context manager (usable as a decorator too) that will bind the attributes once entered
  1247. and restore the initial state of the ``extra`` dict while exited.
  1248. Examples
  1249. --------
  1250. >>> logger.add(sys.stderr, format="{message} | {extra}")
  1251. 1
  1252. >>> def task():
  1253. ... logger.info("Processing!")
  1254. ...
  1255. >>> with logger.contextualize(task_id=123):
  1256. ... task()
  1257. ...
  1258. Processing! | {'task_id': 123}
  1259. >>> logger.info("Done.")
  1260. Done. | {}
  1261. """
  1262. with __self._core.lock:
  1263. new_context = {**context.get(), **kwargs}
  1264. token = context.set(new_context)
  1265. try:
  1266. yield
  1267. finally:
  1268. with __self._core.lock:
  1269. context.reset(token)
  1270. def patch(self, patcher):
  1271. """Attach a function to modify the record dict created by each logging call.
  1272. The ``patcher`` may be used to update the record on-the-fly before it's propagated to the
  1273. handlers. This allows the "extra" dict to be populated with dynamic values and also permits
  1274. advanced modifications of the record emitted while logging a message. The function is called
  1275. once before sending the log message to the different handlers.
  1276. It is recommended to apply modification on the ``record["extra"]`` dict rather than on the
  1277. ``record`` dict itself, as some values are used internally by `Loguru`, and modify them may
  1278. produce unexpected results.
  1279. The logger can be patched multiple times. In this case, the functions are called in the
  1280. same order as they are added.
  1281. Parameters
  1282. ----------
  1283. patcher: |callable|_
  1284. The function to which the record dict will be passed as the sole argument. This function
  1285. is in charge of updating the record in-place, the function does not need to return any
  1286. value, the modified record object will be re-used.
  1287. Returns
  1288. -------
  1289. :class:`~Logger`
  1290. A logger wrapping the core logger, but which records are passed through the ``patcher``
  1291. function before being sent to the added handlers.
  1292. Examples
  1293. --------
  1294. >>> logger.add(sys.stderr, format="{extra[utc]} {message}")
  1295. >>> logger = logger.patch(lambda record: record["extra"].update(utc=datetime.utcnow())
  1296. >>> logger.info("That's way, you can log messages with time displayed in UTC")
  1297. >>> def wrapper(func):
  1298. ... @functools.wraps(func)
  1299. ... def wrapped(*args, **kwargs):
  1300. ... logger.patch(lambda r: r.update(function=func.__name__)).info("Wrapped!")
  1301. ... return func(*args, **kwargs)
  1302. ... return wrapped
  1303. >>> def recv_record_from_network(pipe):
  1304. ... record = pickle.loads(pipe.read())
  1305. ... level, message = record["level"], record["message"]
  1306. ... logger.patch(lambda r: r.update(record)).log(level, message)
  1307. """
  1308. *options, patchers, extra = self._options
  1309. return Logger(self._core, *options, [*patchers, patcher], extra)
  1310. def level(self, name, no=None, color=None, icon=None):
  1311. r"""Add, update or retrieve a logging level.
  1312. Logging levels are defined by their ``name`` to which a severity ``no``, an ansi ``color``
  1313. tag and an ``icon`` are associated and possibly modified at run-time. To |log| to a custom
  1314. level, you should necessarily use its name, the severity number is not linked back to levels
  1315. name (this implies that several levels can share the same severity).
  1316. To add a new level, its ``name`` and its ``no`` are required. A ``color`` and an ``icon``
  1317. can also be specified or will be empty by default.
  1318. To update an existing level, pass its ``name`` with the parameters to be changed. It is not
  1319. possible to modify the ``no`` of a level once it has been added.
  1320. To retrieve level information, the ``name`` solely suffices.
  1321. Parameters
  1322. ----------
  1323. name : |str|
  1324. The name of the logging level.
  1325. no : |int|
  1326. The severity of the level to be added or updated.
  1327. color : |str|
  1328. The color markup of the level to be added or updated.
  1329. icon : |str|
  1330. The icon of the level to be added or updated.
  1331. Returns
  1332. -------
  1333. ``Level``
  1334. A |namedtuple| containing information about the level.
  1335. Raises
  1336. ------
  1337. ValueError
  1338. If attempting to access a level with a ``name`` that is not registered, or if trying to
  1339. change the severity ``no`` of an existing level.
  1340. Examples
  1341. --------
  1342. >>> level = logger.level("ERROR")
  1343. >>> print(level)
  1344. Level(name='ERROR', no=40, color='<red><bold>', icon='❌')
  1345. >>> logger.add(sys.stderr, format="{level.no} {level.icon} {message}")
  1346. 1
  1347. >>> logger.level("CUSTOM", no=15, color="<blue>", icon="@")
  1348. Level(name='CUSTOM', no=15, color='<blue>', icon='@')
  1349. >>> logger.log("CUSTOM", "Logging...")
  1350. 15 @ Logging...
  1351. >>> logger.level("WARNING", icon=r"/!\\")
  1352. Level(name='WARNING', no=30, color='<yellow><bold>', icon='/!\\\\')
  1353. >>> logger.warning("Updated!")
  1354. 30 /!\\ Updated!
  1355. """
  1356. if not isinstance(name, str):
  1357. raise TypeError(
  1358. "Invalid level name, it should be a string, not: '%s'" % type(name).__name__
  1359. )
  1360. if no is color is icon is None:
  1361. try:
  1362. return self._core.levels[name]
  1363. except KeyError:
  1364. raise ValueError("Level '%s' does not exist" % name) from None
  1365. if name not in self._core.levels:
  1366. if no is None:
  1367. raise ValueError(
  1368. "Level '%s' does not exist, you have to create it by specifying a level no"
  1369. % name
  1370. )
  1371. old_color, old_icon = "", " "
  1372. elif no is not None:
  1373. raise ValueError("Level '%s' already exists, you can't update its severity no" % name)
  1374. else:
  1375. _, no, old_color, old_icon = self.level(name)
  1376. if color is None:
  1377. color = old_color
  1378. if icon is None:
  1379. icon = old_icon
  1380. if not isinstance(no, int):
  1381. raise TypeError(
  1382. "Invalid level no, it should be an integer, not: '%s'" % type(no).__name__
  1383. )
  1384. if no < 0:
  1385. raise ValueError("Invalid level no, it should be a positive integer, not: %d" % no)
  1386. ansi = Colorizer.ansify(color)
  1387. level = Level(name, no, color, icon)
  1388. with self._core.lock:
  1389. self._core.levels[name] = level
  1390. self._core.levels_ansi_codes[name] = ansi
  1391. self._core.levels_lookup[name] = (name, name, no, icon)
  1392. for handler in self._core.handlers.values():
  1393. handler.update_format(name)
  1394. return level
  1395. def disable(self, name):
  1396. """Disable logging of messages coming from ``name`` module and its children.
  1397. Developers of library using `Loguru` should absolutely disable it to avoid disrupting
  1398. users with unrelated logs messages.
  1399. Note that in some rare circumstances, it is not possible for `Loguru` to
  1400. determine the module's ``__name__`` value. In such situation, ``record["name"]`` will be
  1401. equal to ``None``, this is why ``None`` is also a valid argument.
  1402. Parameters
  1403. ----------
  1404. name : |str| or ``None``
  1405. The name of the parent module to disable.
  1406. Examples
  1407. --------
  1408. >>> logger.info("Allowed message by default")
  1409. [22:21:55] Allowed message by default
  1410. >>> logger.disable("my_library")
  1411. >>> logger.info("While publishing a library, don't forget to disable logging")
  1412. """
  1413. self._change_activation(name, False)
  1414. def enable(self, name):
  1415. """Enable logging of messages coming from ``name`` module and its children.
  1416. Logging is generally disabled by imported library using `Loguru`, hence this function
  1417. allows users to receive these messages anyway.
  1418. To enable all logs regardless of the module they are coming from, an empty string ``""`` can
  1419. be passed.
  1420. Parameters
  1421. ----------
  1422. name : |str| or ``None``
  1423. The name of the parent module to re-allow.
  1424. Examples
  1425. --------
  1426. >>> logger.disable("__main__")
  1427. >>> logger.info("Disabled, so nothing is logged.")
  1428. >>> logger.enable("__main__")
  1429. >>> logger.info("Re-enabled, messages are logged.")
  1430. [22:46:12] Re-enabled, messages are logged.
  1431. """
  1432. self._change_activation(name, True)
  1433. def configure(self, *, handlers=None, levels=None, extra=None, patcher=None, activation=None):
  1434. """Configure the core logger.
  1435. It should be noted that ``extra`` values set using this function are available across all
  1436. modules, so this is the best way to set overall default values.
  1437. To load the configuration directly from a file, such as JSON or YAML, it is also possible to
  1438. use the |loguru-config|_ library developed by `@erezinman`_.
  1439. Parameters
  1440. ----------
  1441. handlers : |list| of |dict|, optional
  1442. A list of each handler to be added. The list should contain dicts of params passed to
  1443. the |add| function as keyword arguments. If not ``None``, all previously added
  1444. handlers are first removed.
  1445. levels : |list| of |dict|, optional
  1446. A list of each level to be added or updated. The list should contain dicts of params
  1447. passed to the |level| function as keyword arguments. This will never remove previously
  1448. created levels.
  1449. extra : |dict|, optional
  1450. A dict containing additional parameters bound to the core logger, useful to share
  1451. common properties if you call |bind| in several of your files modules. If not ``None``,
  1452. this will remove previously configured ``extra`` dict.
  1453. patcher : |callable|_, optional
  1454. A function that will be applied to the record dict of each logged messages across all
  1455. modules using the logger. It should modify the dict in-place without returning anything.
  1456. The function is executed prior to the one possibly added by the |patch| method. If not
  1457. ``None``, this will replace previously configured ``patcher`` function.
  1458. activation : |list| of |tuple|, optional
  1459. A list of ``(name, state)`` tuples which denotes which loggers should be enabled (if
  1460. ``state`` is ``True``) or disabled (if ``state`` is ``False``). The calls to |enable|
  1461. and |disable| are made accordingly to the list order. This will not modify previously
  1462. activated loggers, so if you need a fresh start prepend your list with ``("", False)``
  1463. or ``("", True)``.
  1464. Returns
  1465. -------
  1466. :class:`list` of :class:`int`
  1467. A list containing the identifiers of added sinks (if any).
  1468. Examples
  1469. --------
  1470. >>> logger.configure(
  1471. ... handlers=[
  1472. ... dict(sink=sys.stderr, format="[{time}] {message}"),
  1473. ... dict(sink="file.log", enqueue=True, serialize=True),
  1474. ... ],
  1475. ... levels=[dict(name="NEW", no=13, icon="¤", color="")],
  1476. ... extra={"common_to_all": "default"},
  1477. ... patcher=lambda record: record["extra"].update(some_value=42),
  1478. ... activation=[("my_module.secret", False), ("another_library.module", True)],
  1479. ... )
  1480. [1, 2]
  1481. >>> # Set a default "extra" dict to logger across all modules, without "bind()"
  1482. >>> extra = {"context": "foo"}
  1483. >>> logger.configure(extra=extra)
  1484. >>> logger.add(sys.stderr, format="{extra[context]} - {message}")
  1485. >>> logger.info("Context without bind")
  1486. >>> # => "foo - Context without bind"
  1487. >>> logger.bind(context="bar").info("Suppress global context")
  1488. >>> # => "bar - Suppress global context"
  1489. """
  1490. if handlers is not None:
  1491. self.remove()
  1492. else:
  1493. handlers = []
  1494. if levels is not None:
  1495. for params in levels:
  1496. self.level(**params)
  1497. if patcher is not None:
  1498. with self._core.lock:
  1499. self._core.patcher = patcher
  1500. if extra is not None:
  1501. with self._core.lock:
  1502. self._core.extra.clear()
  1503. self._core.extra.update(extra)
  1504. if activation is not None:
  1505. for name, state in activation:
  1506. if state:
  1507. self.enable(name)
  1508. else:
  1509. self.disable(name)
  1510. return [self.add(**params) for params in handlers]
  1511. def _change_activation(self, name, status):
  1512. if not (name is None or isinstance(name, str)):
  1513. raise TypeError(
  1514. "Invalid name, it should be a string (or None), not: '%s'" % type(name).__name__
  1515. )
  1516. with self._core.lock:
  1517. enabled = self._core.enabled.copy()
  1518. if name is None:
  1519. for n in enabled:
  1520. if n is None:
  1521. enabled[n] = status
  1522. self._core.activation_none = status
  1523. self._core.enabled = enabled
  1524. return
  1525. if name != "":
  1526. name += "."
  1527. activation_list = [
  1528. (n, s) for n, s in self._core.activation_list if n[: len(name)] != name
  1529. ]
  1530. parent_status = next((s for n, s in activation_list if name[: len(n)] == n), None)
  1531. if parent_status != status and not (name == "" and status is True):
  1532. activation_list.append((name, status))
  1533. def modules_depth(x):
  1534. return x[0].count(".")
  1535. activation_list.sort(key=modules_depth, reverse=True)
  1536. for n in enabled:
  1537. if n is not None and (n + ".")[: len(name)] == name:
  1538. enabled[n] = status
  1539. self._core.activation_list = activation_list
  1540. self._core.enabled = enabled
  1541. @staticmethod
  1542. def parse(file, pattern, *, cast={}, chunk=2**16): # noqa: B006
  1543. """Parse raw logs and extract each entry as a |dict|.
  1544. The logging format has to be specified as the regex ``pattern``, it will then be
  1545. used to parse the ``file`` and retrieve each entry based on the named groups present
  1546. in the regex.
  1547. Parameters
  1548. ----------
  1549. file : |str|, |Path| or |file-like object|_
  1550. The path of the log file to be parsed, or an already opened file object.
  1551. pattern : |str| or |re.Pattern|_
  1552. The regex to use for logs parsing, it should contain named groups which will be included
  1553. in the returned dict.
  1554. cast : |callable|_ or |dict|, optional
  1555. A function that should convert in-place the regex groups parsed (a dict of string
  1556. values) to more appropriate types. If a dict is passed, it should be a mapping between
  1557. keys of parsed log dict and the function that should be used to convert the associated
  1558. value.
  1559. chunk : |int|, optional
  1560. The number of bytes read while iterating through the logs, this avoids having to load
  1561. the whole file in memory.
  1562. Yields
  1563. ------
  1564. :class:`dict`
  1565. The dict mapping regex named groups to matched values, as returned by |match.groupdict|
  1566. and optionally converted according to ``cast`` argument.
  1567. Examples
  1568. --------
  1569. >>> reg = r"(?P<lvl>[0-9]+): (?P<msg>.*)" # If log format is "{level.no} - {message}"
  1570. >>> for e in logger.parse("file.log", reg): # A file line could be "10 - A debug message"
  1571. ... print(e) # => {'lvl': '10', 'msg': 'A debug message'}
  1572. >>> caster = dict(lvl=int) # Parse 'lvl' key as an integer
  1573. >>> for e in logger.parse("file.log", reg, cast=caster):
  1574. ... print(e) # => {'lvl': 10, 'msg': 'A debug message'}
  1575. >>> def cast(groups):
  1576. ... if "date" in groups:
  1577. ... groups["date"] = datetime.strptime(groups["date"], "%Y-%m-%d %H:%M:%S")
  1578. ...
  1579. >>> with open("file.log") as file:
  1580. ... for log in logger.parse(file, reg, cast=cast):
  1581. ... print(log["date"], log["something_else"])
  1582. """
  1583. if isinstance(file, (str, PathLike)):
  1584. @contextlib.contextmanager
  1585. def opener():
  1586. with open(str(file)) as fileobj:
  1587. yield fileobj
  1588. elif hasattr(file, "read") and callable(file.read):
  1589. @contextlib.contextmanager
  1590. def opener():
  1591. yield file
  1592. else:
  1593. raise TypeError(
  1594. "Invalid file, it should be a string path or a file object, not: '%s'"
  1595. % type(file).__name__
  1596. )
  1597. if isinstance(cast, dict):
  1598. def cast_function(groups):
  1599. for key, converter in cast.items():
  1600. if key in groups:
  1601. groups[key] = converter(groups[key])
  1602. elif callable(cast):
  1603. cast_function = cast
  1604. else:
  1605. raise TypeError(
  1606. "Invalid cast, it should be a function or a dict, not: '%s'" % type(cast).__name__
  1607. )
  1608. try:
  1609. regex = re.compile(pattern)
  1610. except TypeError:
  1611. raise TypeError(
  1612. "Invalid pattern, it should be a string or a compiled regex, not: '%s'"
  1613. % type(pattern).__name__
  1614. ) from None
  1615. with opener() as fileobj:
  1616. matches = Logger._find_iter(fileobj, regex, chunk)
  1617. for match in matches:
  1618. groups = match.groupdict()
  1619. cast_function(groups)
  1620. yield groups
  1621. @staticmethod
  1622. def _find_iter(fileobj, regex, chunk):
  1623. buffer = fileobj.read(0)
  1624. while True:
  1625. text = fileobj.read(chunk)
  1626. buffer += text
  1627. matches = list(regex.finditer(buffer))
  1628. if not text:
  1629. yield from matches
  1630. break
  1631. if len(matches) > 1:
  1632. end = matches[-2].end()
  1633. buffer = buffer[end:]
  1634. yield from matches[:-1]
  1635. def _log(self, level, from_decorator, options, message, args, kwargs):
  1636. core = self._core
  1637. if not core.handlers:
  1638. return
  1639. try:
  1640. level_id, level_name, level_no, level_icon = core.levels_lookup[level]
  1641. except (KeyError, TypeError):
  1642. if isinstance(level, str):
  1643. raise ValueError("Level '%s' does not exist" % level) from None
  1644. if not isinstance(level, int):
  1645. raise TypeError(
  1646. "Invalid level, it should be an integer or a string, not: '%s'"
  1647. % type(level).__name__
  1648. ) from None
  1649. if level < 0:
  1650. raise ValueError(
  1651. "Invalid level value, it should be a positive integer, not: %d" % level
  1652. ) from None
  1653. cache = (None, "Level %d" % level, level, " ")
  1654. level_id, level_name, level_no, level_icon = cache
  1655. core.levels_lookup[level] = cache
  1656. if level_no < core.min_level:
  1657. return
  1658. (exception, depth, record, lazy, colors, raw, capture, patchers, extra) = options
  1659. try:
  1660. frame = get_frame(depth + 2)
  1661. except ValueError:
  1662. f_globals = {}
  1663. f_lineno = 0
  1664. co_name = "<unknown>"
  1665. co_filename = "<unknown>"
  1666. else:
  1667. f_globals = frame.f_globals
  1668. f_lineno = frame.f_lineno
  1669. co_name = frame.f_code.co_name
  1670. co_filename = frame.f_code.co_filename
  1671. try:
  1672. name = f_globals["__name__"]
  1673. except KeyError:
  1674. name = None
  1675. try:
  1676. if not core.enabled[name]:
  1677. return
  1678. except KeyError:
  1679. enabled = core.enabled
  1680. if name is None:
  1681. status = core.activation_none
  1682. enabled[name] = status
  1683. if not status:
  1684. return
  1685. else:
  1686. dotted_name = name + "."
  1687. for dotted_module_name, status in core.activation_list:
  1688. if dotted_name[: len(dotted_module_name)] == dotted_module_name:
  1689. if status:
  1690. break
  1691. enabled[name] = False
  1692. return
  1693. enabled[name] = True
  1694. current_datetime = aware_now()
  1695. file_name = basename(co_filename)
  1696. thread = current_thread()
  1697. process = current_process()
  1698. elapsed = current_datetime - start_time
  1699. if exception:
  1700. if isinstance(exception, BaseException):
  1701. type_, value, traceback = (type(exception), exception, exception.__traceback__)
  1702. elif isinstance(exception, tuple):
  1703. type_, value, traceback = exception
  1704. else:
  1705. type_, value, traceback = sys.exc_info()
  1706. exception = RecordException(type_, value, traceback)
  1707. else:
  1708. exception = None
  1709. log_record = {
  1710. "elapsed": elapsed,
  1711. "exception": exception,
  1712. "extra": {**core.extra, **context.get(), **extra},
  1713. "file": RecordFile(file_name, co_filename),
  1714. "function": co_name,
  1715. "level": RecordLevel(level_name, level_no, level_icon),
  1716. "line": f_lineno,
  1717. "message": str(message),
  1718. "module": splitext(file_name)[0],
  1719. "name": name,
  1720. "process": RecordProcess(process.ident, process.name),
  1721. "thread": RecordThread(thread.ident, thread.name),
  1722. "time": current_datetime,
  1723. }
  1724. if lazy:
  1725. args = [arg() for arg in args]
  1726. kwargs = {key: value() for key, value in kwargs.items()}
  1727. if capture and kwargs:
  1728. log_record["extra"].update(kwargs)
  1729. if record:
  1730. if "record" in kwargs:
  1731. raise TypeError(
  1732. "The message can't be formatted: 'record' shall not be used as a keyword "
  1733. "argument while logger has been configured with '.opt(record=True)'"
  1734. )
  1735. kwargs.update(record=log_record)
  1736. if colors:
  1737. if args or kwargs:
  1738. colored_message = Colorizer.prepare_message(message, args, kwargs)
  1739. else:
  1740. colored_message = Colorizer.prepare_simple_message(str(message))
  1741. log_record["message"] = colored_message.stripped
  1742. elif args or kwargs:
  1743. colored_message = None
  1744. log_record["message"] = message.format(*args, **kwargs)
  1745. else:
  1746. colored_message = None
  1747. if core.patcher:
  1748. core.patcher(log_record)
  1749. for patcher in patchers:
  1750. patcher(log_record)
  1751. for handler in core.handlers.values():
  1752. handler.emit(log_record, level_id, from_decorator, raw, colored_message)
  1753. def trace(__self, __message, *args, **kwargs): # noqa: N805
  1754. r"""Log ``message.format(*args, **kwargs)`` with severity ``'TRACE'``."""
  1755. __self._log("TRACE", False, __self._options, __message, args, kwargs)
  1756. def debug(__self, __message, *args, **kwargs): # noqa: N805
  1757. r"""Log ``message.format(*args, **kwargs)`` with severity ``'DEBUG'``."""
  1758. __self._log("DEBUG", False, __self._options, __message, args, kwargs)
  1759. def info(__self, __message, *args, **kwargs): # noqa: N805
  1760. r"""Log ``message.format(*args, **kwargs)`` with severity ``'INFO'``."""
  1761. __self._log("INFO", False, __self._options, __message, args, kwargs)
  1762. def success(__self, __message, *args, **kwargs): # noqa: N805
  1763. r"""Log ``message.format(*args, **kwargs)`` with severity ``'SUCCESS'``."""
  1764. __self._log("SUCCESS", False, __self._options, __message, args, kwargs)
  1765. def warning(__self, __message, *args, **kwargs): # noqa: N805
  1766. r"""Log ``message.format(*args, **kwargs)`` with severity ``'WARNING'``."""
  1767. __self._log("WARNING", False, __self._options, __message, args, kwargs)
  1768. def error(__self, __message, *args, **kwargs): # noqa: N805
  1769. r"""Log ``message.format(*args, **kwargs)`` with severity ``'ERROR'``."""
  1770. __self._log("ERROR", False, __self._options, __message, args, kwargs)
  1771. def critical(__self, __message, *args, **kwargs): # noqa: N805
  1772. r"""Log ``message.format(*args, **kwargs)`` with severity ``'CRITICAL'``."""
  1773. __self._log("CRITICAL", False, __self._options, __message, args, kwargs)
  1774. def exception(__self, __message, *args, **kwargs): # noqa: N805
  1775. r"""Log an ``'ERROR'```` message while also capturing the currently handled exception."""
  1776. options = (True,) + __self._options[1:]
  1777. __self._log("ERROR", False, options, __message, args, kwargs)
  1778. def log(__self, __level, __message, *args, **kwargs): # noqa: N805
  1779. r"""Log ``message.format(*args, **kwargs)`` with severity ``level``."""
  1780. __self._log(__level, False, __self._options, __message, args, kwargs)
  1781. def start(self, *args, **kwargs):
  1782. """Add a handler sending log messages to a sink adequately configured.
  1783. Deprecated function, use |add| instead.
  1784. Warnings
  1785. --------
  1786. .. deprecated:: 0.2.2
  1787. ``start()`` will be removed in Loguru 1.0.0, it is replaced by ``add()`` which is a less
  1788. confusing name.
  1789. """
  1790. warnings.warn(
  1791. "The 'start()' method is deprecated, please use 'add()' instead",
  1792. DeprecationWarning,
  1793. stacklevel=2,
  1794. )
  1795. return self.add(*args, **kwargs)
  1796. def stop(self, *args, **kwargs):
  1797. """Remove a previously added handler and stop sending logs to its sink.
  1798. Deprecated function, use |remove| instead.
  1799. Warnings
  1800. --------
  1801. .. deprecated:: 0.2.2
  1802. ``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less
  1803. confusing name.
  1804. """
  1805. warnings.warn(
  1806. "The 'stop()' method is deprecated, please use 'remove()' instead",
  1807. DeprecationWarning,
  1808. stacklevel=2,
  1809. )
  1810. return self.remove(*args, **kwargs)