i@~dZddlZddlZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z m Z mZddlmZmZddlmZddlmZmZddlmZd d lmZmZmZmZd d lmZd d lm Z d d l!m"Z"d dl#m$Z$d dl%m&Z&d dl'm(Z(d dl)m*Z*d dl+m,Z,d dl-m.Z.d dl/m0Z0m1Z1m2Z2m3Z3m4Z4d dl5m6Z6m7Z7m8Z8m9Z9ej:dkrddl;mZ<e dgdZ?e$Z@e"diZAGddZBGdd ZCdS)!aCore logging functionalities of the `Loguru` library. .. References and links rendered by Sphinx are kept here as "module documentation" so that they can be used in the ``Logger`` docstrings but do not pollute ``help(logger)`` output. .. |Logger| replace:: :class:`~Logger` .. |add| replace:: :meth:`~Logger.add()` .. |remove| replace:: :meth:`~Logger.remove()` .. |complete| replace:: :meth:`~Logger.complete()` .. |catch| replace:: :meth:`~Logger.catch()` .. |bind| replace:: :meth:`~Logger.bind()` .. |contextualize| replace:: :meth:`~Logger.contextualize()` .. |patch| replace:: :meth:`~Logger.patch()` .. |opt| replace:: :meth:`~Logger.opt()` .. |log| replace:: :meth:`~Logger.log()` .. |level| replace:: :meth:`~Logger.level()` .. |enable| replace:: :meth:`~Logger.enable()` .. |disable| replace:: :meth:`~Logger.disable()` .. |Any| replace:: :obj:`~typing.Any` .. |str| replace:: :class:`str` .. |int| replace:: :class:`int` .. |bool| replace:: :class:`bool` .. |tuple| replace:: :class:`tuple` .. |namedtuple| replace:: :func:`namedtuple` .. |list| replace:: :class:`list` .. |dict| replace:: :class:`dict` .. |str.format| replace:: :meth:`str.format()` .. |Path| replace:: :class:`pathlib.Path` .. |match.groupdict| replace:: :meth:`re.Match.groupdict()` .. |Handler| replace:: :class:`logging.Handler` .. |sys.stderr| replace:: :data:`sys.stderr` .. |sys.exc_info| replace:: :func:`sys.exc_info()` .. |time| replace:: :class:`datetime.time` .. |datetime| replace:: :class:`datetime.datetime` .. |timedelta| replace:: :class:`datetime.timedelta` .. |open| replace:: :func:`open()` .. |logging| replace:: :mod:`logging` .. |signal| replace:: :mod:`signal` .. |contextvars| replace:: :mod:`contextvars` .. |multiprocessing| replace:: :mod:`multiprocessing` .. |Thread.run| replace:: :meth:`Thread.run()` .. |Exception| replace:: :class:`Exception` .. |AbstractEventLoop| replace:: :class:`AbstractEventLoop` .. |asyncio.get_running_loop| replace:: :func:`asyncio.get_running_loop()` .. |asyncio.run| replace:: :func:`asyncio.run()` .. |loop.run_until_complete| replace:: :meth:`loop.run_until_complete()` .. |loop.create_task| replace:: :meth:`loop.create_task()` .. |logger.trace| replace:: :meth:`logger.trace()` .. |logger.debug| replace:: :meth:`logger.debug()` .. |logger.info| replace:: :meth:`logger.info()` .. |logger.success| replace:: :meth:`logger.success()` .. |logger.warning| replace:: :meth:`logger.warning()` .. |logger.error| replace:: :meth:`logger.error()` .. |logger.critical| replace:: :meth:`logger.critical()` .. |file-like object| replace:: ``file-like object`` .. _file-like object: https://docs.python.org/3/glossary.html#term-file-object .. |callable| replace:: ``callable`` .. _callable: https://docs.python.org/3/library/functions.html#callable .. |coroutine function| replace:: ``coroutine function`` .. _coroutine function: https://docs.python.org/3/glossary.html#term-coroutine-function .. |re.Pattern| replace:: ``re.Pattern`` .. _re.Pattern: https://docs.python.org/3/library/re.html#re-objects .. |multiprocessing.Context| replace:: ``multiprocessing.Context`` .. _multiprocessing.Context: https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods .. |better_exceptions| replace:: ``better_exceptions`` .. _better_exceptions: https://github.com/Qix-/better-exceptions .. |loguru-config| replace:: ``loguru-config`` .. _loguru-config: https://github.com/erezinman/loguru-config .. _Pendulum: https://pendulum.eustace.io/docs/#tokens .. _@Qix-: https://github.com/Qix- .. _@erezinman: https://github.com/erezinman .. _@sdispater: https://github.com/sdispater .. _formatting directives: https://docs.python.org/3/library/string.html#format-string-syntax .. _reentrant: https://en.wikipedia.org/wiki/Reentrancy_(computing) N) namedtuple)isclassiscoroutinefunctionisgeneratorfunction)current_process get_context) BaseContext)basenamesplitext)current_thread) _asyncio_loop _colorama _defaults_filters)ExceptionFormatter) Colorizer) ContextVar) aware_now)ErrorInterceptor)FileSink) get_frame)Handler)create_logger_lock)RecordException RecordFile RecordLevel RecordProcess RecordThread) AsyncSink CallableSink StandardSink StreamSink))PathLike)PurePathLevel)namenocoloriconloguru_contextdefaultc eZdZdZdZdZdS)Corec Jtdtjtjtjtdtjtjtjtdtjtj tj tdtj tj tj tdtjtjtjtdtjtjtjtdtjtjtjg}d|D|_id |jDdd i|_d |jD|_d |_i|_i|_d|_t?d |_ i|_!g|_"d|_#tIj%|_&tO|_(dS)NTRACEDEBUGINFOSUCCESSWARNINGERRORCRITICALci|] }|j| S)r)).0levels z!Core.__init__..s===Uuz5===cHi|]\}}|tj|j Sr;)ransifyr+r<r)r=s r>r?z!Core.__init__..s+ZZZ{tUtY%ek22ZZZr@c6i|]\}}||||j|jfSr;)r*r,rCs r>r?z!Core.__init__..s8   9DuD4ux4   r@rinfT))r(rLOGURU_TRACE_NOLOGURU_TRACE_COLORLOGURU_TRACE_ICONLOGURU_DEBUG_NOLOGURU_DEBUG_COLORLOGURU_DEBUG_ICONLOGURU_INFO_NOLOGURU_INFO_COLORLOGURU_INFO_ICONLOGURU_SUCCESS_NOLOGURU_SUCCESS_COLORLOGURU_SUCCESS_ICONLOGURU_WARNING_NOLOGURU_WARNING_COLORLOGURU_WARNING_ICONLOGURU_ERROR_NOLOGURU_ERROR_COLORLOGURU_ERROR_ICONLOGURU_CRITICAL_NOLOGURU_CRITICAL_COLORLOGURU_CRITICAL_ICONlevelsitemslevels_ansi_codes levels_lookuphandlers_counthandlersextrapatcherfloat min_levelenabledactivation_listactivation_none threadinglocal thread_localsrlock)selfr\s r>__init__z Core.__init__s ),+    ),+    (+*    +.-    +.-    ),+    ,/.   K+ X>=f=== " ZZdkFWFWFYFYZZZ" "" "   HL HYHYH[H[       u !#&_..&(( r@cL|j}d|d<d|d<|S)Nrkrl)__dict__copyrmstates r> __getstate__zCore.__getstate__s- ""$$!%of  r@c|j|tj|_t |_dSN)rpupdaterirjrkrrlrrs r> __setstate__zCore.__setstate__s9 U###&_..&(( r@N)__name__ __module__ __qualname__rnrtrxr;r@r>r1r1sEF)F)F)P )))))r@r1c eZdZdZdZdZejejej ej ej ej ej ejejejd dZd+dZdZefd d dddd d d Zdd d d d ddd ddZdZejdZdZd,dZdZdZdddddddZdZ e!idddZ"e!dZ#dZ$d Z%d!Z&d"Z'd#Z(d$Z)d%Z*d&Z+d'Z,d(Z-d)Z.d*Z/dS)-Loggera#An object to dispatch logging messages to configured handlers. The |Logger| is the core object of ``loguru``, every logging configuration and usage pass through a call to one of its methods. There is only one logger, so there is no need to retrieve one before usage. Once the ``logger`` is imported, it can be used to write messages about events happening in your code. By reading the output logs of your application, you gain a better understanding of the flow of your program and you more easily track and debug unexpected behaviors. Handlers to which the logger sends log messages are added using the |add| method. Note that you can use the |Logger| right after import as it comes pre-configured (logs are emitted to |sys.stderr| by default). Messages can be logged with different severity levels and they can be formatted using curly braces (it uses |str.format| under the hood). When a message is logged, a "record" is associated with it. This record is a dict which contains information about the logging context: time, function, file, line, thread, level... It also contains the ``__name__`` of the module, this is why you don't need named loggers. You should not instantiate a |Logger| by yourself, use ``from loguru import logger`` instead. c 4||_|||||||| | f |_dSrv)_core_options) rmcore exceptiondepthrecordlazycolorsrawcapturepatchersrbs r>rnzLogger.__init__s( "E64gxY^_ r@c^dt|jjzS)Nz)listrravaluesrms r>__repr__zLogger.__repr__s&,tDJ4G4N4N4P4P/Q/QQQr@) r=formatfiltercolorize serialize backtracediagnoseenqueuecontextcatchc  |jj5|jj} |jxjdz c_dddn #1swxYwYt| | }||rd}t |t t fr'|}d|z}|d}t|fi| }i} |j}d}d}nAt|drt|j rt|ddpt|}|tj|}|d ur)tj|rtj|}n|}t%|}t|d d}d}d}nt |t&jr9t|}|d}t+|}t|d d}d}d}n?t-|st-t|d drt|d dpt|}|d}| d d}| r9|7 t1j}n"#t4$r}t7d|d}~wwxYwt-|r|n|j}t;|||}d}d}d}nmt|r:t|d dpt|}|d}t=|}d}d}d}n$t?dtA|j!z| r,t?dtEtG| z|d}n|dkrtHj%}nt |t r7|dz}tM|}tOj(tHj)||}nt |tTr=i}|+D]\}}|9t |t s$t?dtA|j!z|durd}n|d urd}nt |t rA |,|j-}ne#t6$rt7d|d|ddwxYwt |t\r|}n(t?d|dtA|j!d|dkrt7d||fz|||<tOj(tHj/|}nUt|r"|t`j1krt7d|}n$t?dtA|j!zt |t r|,|j-} n3}"`` will right-align and pad to a width of 3 characters). This is particularly useful for time formatting (see below). +------------+---------------------------------+----------------------------+ | Key | Description | Attributes | +============+=================================+============================+ | elapsed | The time elapsed since the | See |timedelta| | | | start of the program | | +------------+---------------------------------+----------------------------+ | exception | The formatted exception if any, | ``type``, ``value``, | | | ``None`` otherwise | ``traceback`` | +------------+---------------------------------+----------------------------+ | extra | The dict of attributes | None | | | bound by the user (see |bind|) | | +------------+---------------------------------+----------------------------+ | file | The file where the logging call | ``name`` (default), | | | was made | ``path`` | +------------+---------------------------------+----------------------------+ | function | The function from which the | None | | | logging call was made | | +------------+---------------------------------+----------------------------+ | level | The severity used to log the | ``name`` (default), | | | message | ``no``, ``icon`` | +------------+---------------------------------+----------------------------+ | line | The line number in the source | None | | | code | | +------------+---------------------------------+----------------------------+ | message | The logged message (not yet | None | | | formatted) | | +------------+---------------------------------+----------------------------+ | module | The module where the logging | None | | | call was made | | +------------+---------------------------------+----------------------------+ | name | The ``__name__`` where the | None | | | logging call was made | | +------------+---------------------------------+----------------------------+ | process | The process in which the | ``name``, ``id`` (default) | | | logging call was made | | +------------+---------------------------------+----------------------------+ | thread | The thread in which the | ``name``, ``id`` (default) | | | logging call was made | | +------------+---------------------------------+----------------------------+ | time | The aware local time when the | See |datetime| | | | logging call was made | | +------------+---------------------------------+----------------------------+ .. _time: .. rubric:: The time formatting To use your favorite time representation, you can set it directly in the time formatter specifier of your handler format, like for example ``format="{time:HH:mm:ss} {message}"``. Note that this datetime represents your local time, and it is also made timezone-aware, so you can display the UTC offset to avoid ambiguities. The time field can be formatted using more human-friendly tokens. These constitute a subset of the one used by the `Pendulum`_ library of `@sdispater`_. To escape a token, just add square brackets around it, for example ``"[YY]"`` would display literally ``"YY"``. If you prefer to display UTC rather than local time, you can add ``"!UTC"`` at the very end of the time format, like ``{time:HH:mm:ss!UTC}``. Doing so will convert the ``datetime`` to UTC before formatting. If no time formatter specifier is used, like for example if ``format="{time} {message}"``, the default one will use ISO 8601. +------------------------+---------+----------------------------------------+ | | Token | Output | +========================+=========+========================================+ | Year | YYYY | 2000, 2001, 2002 ... 2012, 2013 | | +---------+----------------------------------------+ | | YY | 00, 01, 02 ... 12, 13 | +------------------------+---------+----------------------------------------+ | Quarter | Q | 1 2 3 4 | +------------------------+---------+----------------------------------------+ | Month | MMMM | January, February, March ... | | +---------+----------------------------------------+ | | MMM | Jan, Feb, Mar ... | | +---------+----------------------------------------+ | | MM | 01, 02, 03 ... 11, 12 | | +---------+----------------------------------------+ | | M | 1, 2, 3 ... 11, 12 | +------------------------+---------+----------------------------------------+ | Day of Year | DDDD | 001, 002, 003 ... 364, 365 | | +---------+----------------------------------------+ | | DDD | 1, 2, 3 ... 364, 365 | +------------------------+---------+----------------------------------------+ | Day of Month | DD | 01, 02, 03 ... 30, 31 | | +---------+----------------------------------------+ | | D | 1, 2, 3 ... 30, 31 | +------------------------+---------+----------------------------------------+ | Day of Week | dddd | Monday, Tuesday, Wednesday ... | | +---------+----------------------------------------+ | | ddd | Mon, Tue, Wed ... | | +---------+----------------------------------------+ | | d | 0, 1, 2 ... 6 | +------------------------+---------+----------------------------------------+ | Days of ISO Week | E | 1, 2, 3 ... 7 | +------------------------+---------+----------------------------------------+ | Hour | HH | 00, 01, 02 ... 23, 24 | | +---------+----------------------------------------+ | | H | 0, 1, 2 ... 23, 24 | | +---------+----------------------------------------+ | | hh | 01, 02, 03 ... 11, 12 | | +---------+----------------------------------------+ | | h | 1, 2, 3 ... 11, 12 | +------------------------+---------+----------------------------------------+ | Minute | mm | 00, 01, 02 ... 58, 59 | | +---------+----------------------------------------+ | | m | 0, 1, 2 ... 58, 59 | +------------------------+---------+----------------------------------------+ | Second | ss | 00, 01, 02 ... 58, 59 | | +---------+----------------------------------------+ | | s | 0, 1, 2 ... 58, 59 | +------------------------+---------+----------------------------------------+ | Fractional Second | S | 0 1 ... 8 9 | | +---------+----------------------------------------+ | | SS | 00, 01, 02 ... 98, 99 | | +---------+----------------------------------------+ | | SSS | 000 001 ... 998 999 | | +---------+----------------------------------------+ | | SSSS... | 000[0..] 001[0..] ... 998[0..] 999[0..]| | +---------+----------------------------------------+ | | SSSSSS | 000000 000001 ... 999998 999999 | +------------------------+---------+----------------------------------------+ | AM / PM | A | AM, PM | +------------------------+---------+----------------------------------------+ | Timezone | Z | -07:00, -06:00 ... +06:00, +07:00 | | +---------+----------------------------------------+ | | ZZ | -0700, -0600 ... +0600, +0700 | | +---------+----------------------------------------+ | | zz | EST CST ... MST PST | +------------------------+---------+----------------------------------------+ | Seconds timestamp | X | 1381685817, 1234567890.123 | +------------------------+---------+----------------------------------------+ | Microseconds timestamp | x | 1234567890123 | +------------------------+---------+----------------------------------------+ .. _file: .. rubric:: The file sinks If the sink is a |str| or a |Path|, the corresponding file will be opened for writing logs. The path can also contain a special ``"{time}"`` field that will be formatted with the current date at file creation. The file is closed at sink stop, i.e. when the application ends or the handler is removed. The ``rotation`` check is made before logging each message. If there is already an existing file with the same name that the file to be created, then the existing file is renamed by appending the date to its basename to prevent file overwriting. This parameter accepts: - an |int| which corresponds to the maximum file size in bytes before that the current logged file is closed and a new one started over. - a |timedelta| which indicates the frequency of each new rotation. - a |time| which specifies the hour when the daily rotation should occur. - a |str| for human-friendly parametrization of one of the previously enumerated types. Examples: ``"100 MB"``, ``"0.5 GB"``, ``"1 month 2 weeks"``, ``"4 days"``, ``"10h"``, ``"monthly"``, ``"18:00"``, ``"sunday"``, ``"w0"``, ``"monday at 12:00"``, ... - a |callable|_ which will be invoked before logging. It should accept two arguments: the logged message and the file object, and it should return ``True`` if the rotation should happen now, ``False`` otherwise. The ``retention`` occurs at rotation or at sink stop if rotation is ``None``. Files resulting from previous sessions or rotations are automatically collected from disk. A file is selected if it matches the pattern ``"basename(.*).ext(.*)"`` (possible time fields are beforehand replaced with ``.*``) based on the configured sink. Afterwards, the list is processed to determine files to be retained. This parameter accepts: - an |int| which indicates the number of log files to keep, while older files are deleted. - a |timedelta| which specifies the maximum age of files to keep. - a |str| for human-friendly parametrization of the maximum age of files to keep. Examples: ``"1 week, 3 days"``, ``"2 months"``, ... - a |callable|_ which will be invoked before the retention process. It should accept the list of log files as argument and process to whatever it wants (moving files, removing them, etc.). The ``compression`` happens at rotation or at sink stop if rotation is ``None``. This parameter accepts: - a |str| which corresponds to the compressed or archived file extension. This can be one of: ``"gz"``, ``"bz2"``, ``"xz"``, ``"lzma"``, ``"tar"``, ``"tar.gz"``, ``"tar.bz2"``, ``"tar.xz"``, ``"zip"``. - a |callable|_ which will be invoked before file termination. It should accept the path of the log file as argument and process to whatever it wants (custom compression, network sending, removing it, etc.). Either way, if you use a custom function designed according to your preferences, you must be very careful not to use the ``logger`` within your function. Otherwise, there is a risk that your program hang because of a deadlock. .. _color: .. rubric:: The color markups To add colors to your logs, you just have to enclose your format string with the appropriate tags (e.g. ``some message``). These tags are automatically removed if the sink doesn't support ansi codes. For convenience, you can use ```` to close the last opening tag without repeating its name (e.g. ``another message``). The special tag ```` (abbreviated with ````) is transformed according to the configured color of the logged message level. Tags which are not recognized will raise an exception during parsing, to inform you about possible misuse. If you wish to display a markup tag literally, you can escape it by prepending a ``\`` like for example ``\``. To prevent the escaping to occur, you can simply double the ``\`` (e.g. ``\\`` will print a literal ``\`` before colored text). If, for some reason, you need to escape a string programmatically, note that the regex used internally to parse markup tags is ``r"(\\*)(\s]*>)"``. Note that when logging a message with ``opt(colors=True)``, color tags present in the formatting arguments (``args`` and ``kwargs``) are completely ignored. This is important if you need to log strings containing markups that might interfere with the color tags (in this case, do not use f-string). Here are the available tags (note that compatibility may vary depending on terminal): +------------------------------------+--------------------------------------+ | Color (abbr) | Styles (abbr) | +====================================+======================================+ | Black (k) | Bold (b) | +------------------------------------+--------------------------------------+ | Blue (e) | Dim (d) | +------------------------------------+--------------------------------------+ | Cyan (c) | Normal (n) | +------------------------------------+--------------------------------------+ | Green (g) | Italic (i) | +------------------------------------+--------------------------------------+ | Magenta (m) | Underline (u) | +------------------------------------+--------------------------------------+ | Red (r) | Strike (s) | +------------------------------------+--------------------------------------+ | White (w) | Reverse (v) | +------------------------------------+--------------------------------------+ | Yellow (y) | Blink (l) | +------------------------------------+--------------------------------------+ | | Hide (h) | +------------------------------------+--------------------------------------+ Usage: +-----------------+-------------------------------------------------------------------+ | Description | Examples | | +---------------------------------+---------------------------------+ | | Foreground | Background | +=================+=================================+=================================+ | Basic colors | ````, ```` | ````, ```` | +-----------------+---------------------------------+---------------------------------+ | Light colors | ````, ```` | ````, ```` | +-----------------+---------------------------------+---------------------------------+ | 8-bit colors | ````, ```` | ````, ```` | +-----------------+---------------------------------+---------------------------------+ | Hex colors | ````, ```` | ````, ```` | +-----------------+---------------------------------+---------------------------------+ | RGB colors | ```` | ```` | +-----------------+---------------------------------+---------------------------------+ | Stylizing | ````, ````, ````, ```` | +-----------------+-------------------------------------------------------------------+ .. _env: .. rubric:: The environment variables The default values of sink parameters can be entirely customized. This is particularly useful if you don't like the log format of the pre-configured sink. Each of the |add| default parameter can be modified by setting the ``LOGURU_[PARAM]`` environment variable. For example on Linux: ``export LOGURU_FORMAT="{time} - {message}"`` or ``export LOGURU_DIAGNOSE=NO``. The default levels' attributes can also be modified by setting the ``LOGURU_[LEVEL]_[ATTR]`` environment variable. For example, on Windows: ``setx LOGURU_DEBUG_COLOR ""`` or ``setx LOGURU_TRACE_ICON "🚀"``. If you use the ``set`` command, do not include quotes but escape special symbol as needed, e.g. ``set LOGURU_DEBUG_COLOR=^``. If you want to disable the pre-configured sink, you can set the ``LOGURU_AUTOINIT`` variable to ``False``. On Linux, you will probably need to edit the ``~/.profile`` file to make this persistent. On Windows, don't forget to restart your terminal for the change to be taken into account. Examples -------- >>> logger.add(sys.stdout, format="{time} - {level} - {message}", filter="sub.module") >>> logger.add("file_{time}.log", level="TRACE", rotation="100 MB") >>> def debug_only(record): ... return record["level"].name == "DEBUG" ... >>> logger.add("debug.log", filter=debug_only) # Other levels are filtered out >>> def my_sink(message): ... record = message.record ... update_db(message, time=record["time"], level=record["level"]) ... >>> logger.add(my_sink) >>> level_per_module = { ... "": "DEBUG", ... "third.lib": "WARNING", ... "anotherlib": False ... } >>> logger.add(lambda m: print(m, end=""), filter=level_per_module, level=0) >>> async def publish(message): ... await api.post(message) ... >>> logger.add(publish, serialize=True) >>> from logging import StreamHandler >>> logger.add(StreamHandler(sys.stderr), format="{message}") >>> class RandomStream: ... def __init__(self, seed, threshold): ... self.threshold = threshold ... random.seed(seed) ... def write(self, message): ... if random.random() > self.threshold: ... print(message) ... >>> stream_object = RandomStream(seed=12345, threshold=0.25) >>> logger.add(stream_object, level="INFO") r NFz'%s' rDwriter)Tencoding__call__ryloopzAn event loop is required to add a coroutine sink with `enqueue=True`, but none has been passed as argument and none is currently running.utf8z"Cannot log to objects of type '%s'z-add() got an unexpected keyword argument '%s'.)parentlengthzVThe filter dict contains an invalid module, it should be a string (or None), not: '%s'rz#The filter dict contains a module 'z4' associated to a level name which does not exist: ''zX' associated to an invalid level, it should be an integer, a string or a boolean, not: 'zqThe filter dict contains a module '%s' associated to an invalid level, it should be a positive integer, not: '%d')level_per_modulezThe built-in 'filter()' function cannot be used as a 'filter' parameter, this is most likely a mistake (please double-check the arguments passed to 'logger.add()').zFInvalid filter, it should be a function, a string or a dict, not: '%s'=Invalid level, it should be an integer or a string, not: '%s'=Invalid level value, it should be a positive integer, not: %dz {exception}z;Invalid format, color markups could not be parsed correctlyzThe built-in 'format()' function cannot be used as a 'format' parameter, this is most likely a mistake (please double-check the arguments passed to 'logger.add()').z>Invalid format, it should be a string or a function, not: '%s'asciizNInvalid context, it should be a string or a multiprocessing context, not: '%s')rrrrhidden_frames_filenameprefix)r)sinklevelno formatteris_formatter_dynamicfilter_rrrmultiprocessing_contextid_error_interceptorexception_formatterr^)@rrlr`r isinstancestrr&rrhasattrcallablergetattrreprrshould_colorize should_wrapwrapr#loggingrr"rpoprget_running_loop RuntimeError ValueErrorrr r! TypeErrortyperynextiterr filter_nonelen functoolspartialfilter_by_namedictr]r=r*intfilter_by_levelbuiltinsrrprepare_formatrrr rr__code__ co_filenamer^rarqminre)&rmrr=rrrrrrrrrkwargs handler_idrpathr) wrapped_sinkr terminatorexception_prefixstreamrecoro filter_funcrrrmodulelevel_levelno_rrrrhandlerras& r>addz Logger.addsN ~Z_ + +2J J % % * % % + + + + + + + + + + + + + + +-UJ??   H dS(O , ,M XDD=D #D33F33LF#,HJ!   T7 # #A X(<(<A X4..<$t**D$4T::4I$9$$?$?"--%f--LtZ66HJ!   go . .2 X::D '--LtZ66HJ#    & &( X*= D*d + ++ + ( X4T22@d4jjD ::fd++D 4<(9;;DD#$^ /t44G44$-D$T41BCCLHJ!   d^^ X4T22@d4jjD '--LHJ!  @4::CVVWW W  bKdSWX^S_S_N`N``aa a >KK r\\".KK  $ $5 c\F[[F#+H,CF[abbbKK  % %1 ! "(,,.. 4 4%j.E.E%#EGKF||G\]U??$HHt^^ HH,,$#'::f#5#5#8%$$$(jG"z*//11H#*HZ #&tz';W#E#EDJ "*DJ ? + + + + + + + + + + + + + + +Bs\";?? H!! I+H;;IP  "Q6W W0W++W0B];;]?]?Nc|9t|ts$tdt|jz|jj5|!||jjvrtd|zd|t|jj}n|g}|D]}|jj }| |}d| D}t|td|j_||j_| ddddS#1swxYwYdS)aRemove a previously added handler and stop sending logs to its sink. Parameters ---------- handler_id : |int| or ``None`` The id of the sink to remove, as it was returned by the |add| method. If ``None``, all handlers are removed. The pre-configured handler is guaranteed to have the index ``0``. Raises ------ ValueError If ``handler_id`` is not ``None`` but there is no active handler with such id. Examples -------- >>> i = logger.add(sys.stderr, format="{message}") >>> logger.info("Logging") Logging >>> logger.remove(i) >>> logger.info("No longer logging") NzbInvalid handler id, it should be an integer as returned by the 'add()' method (or None), not: '%s'z'There is no existing handler with id %dc3$K|] }|jV dSrv)r)r<hs r> z Logger.remove..&s$AA!AIAAAAAAr@rFr.)rrrrryrrlrarrrqrrrrdrestop)rmr handler_idsrarlevelnoss r>removez Logger.removes,"jS&A&A"=?CJ?O?O?XY  Z_  %*DJD;cdg|jj5|jj}|D]=}||> dddn #1swxYwYGfdd}|S)aWait for the end of enqueued messages and asynchronous tasks scheduled by handlers. This method proceeds in two steps: first it waits for all logging messages added to handlers with ``enqueue=True`` to be processed, then it returns an object that can be awaited to finalize all logging tasks added to the event loop by coroutine sinks. It can be called from non-asynchronous code. This is especially recommended when the ``logger`` is utilized with ``multiprocessing`` to ensure messages put to the internal queue have been properly transmitted before leaving a child process. The returned object should be awaited before the end of a coroutine executed by |asyncio.run| or |loop.run_until_complete| to ensure all asynchronous logging messages are processed. The function |asyncio.get_running_loop| is called beforehand, only tasks scheduled in the same loop that the current one will be awaited by the method. Returns ------- :term:`awaitable` An awaitable object which ensures all asynchronous logging calls are completed when awaited. Examples -------- >>> async def sink(message): ... await asyncio.sleep(0.1) # IO processing... ... print(message, end="") ... >>> async def work(): ... logger.info("Start") ... logger.info("End") ... await logger.complete() ... >>> logger.add(sink) 1 >>> asyncio.run(work()) Start End >>> def process(): ... logger.info("Message sent from the child") ... logger.complete() ... >>> logger.add(sys.stderr, enqueue=True) 1 >>> process = multiprocessing.Process(target=process) >>> process.start() >>> process.join() Message sent from the child NceZdZfdZdS)+Logger.complete..AwaitableCompleterc3JKD]}|Ed{VdSrv) __await__)rmtasktaskss r>rz5Logger.complete..AwaitableCompleter.__await__gsE!00D#~~//////////00r@N)ryrzr{r)rsr>AwaitableCompleterrfs. 0 0 0 0 0 0 0r@r)rrlrarqrcomplete_queueextendtasks_to_complete)rmrarrrs @r>completezLogger.complete,sd Z_ : :z*//11H#??,, : :&&((( W66889999 : : : : : : : : : : : : : : : :  0 0 0 0 0 0 0 0 0 0 "!###sA1BBBr8FzAn error has been caught in function '{record[function]}', process '{record[process].name}' ({record[process].id}), thread '{record[thread].name}' ({record[thread].id}):)r=reraiseonerrorexcluder/messagec  trAtrtts|S| G f dddS)uL Return a decorator to automatically log possibly caught error in wrapped function. This is useful to ensure unexpected exceptions are logged, the entire program can be wrapped by this method. This is also very useful to decorate |Thread.run| methods while using threads to propagate errors to the main logger thread. Note that the visibility of variables values (which uses the great |better_exceptions|_ library from `@Qix-`_) depends on the ``diagnose`` option of each configured sink. The returned object can also be used as a context manager. Parameters ---------- exception : |Exception|, optional The type of exception to intercept. If several types should be caught, a tuple of exceptions can be used too. level : |str| or |int|, optional The level name or severity with which the message should be logged. reraise : |bool|, optional Whether the exception should be raised again and hence propagated to the caller. onerror : |callable|_, optional A function that will be called if an error occurs, once the message has been logged. It should accept the exception instance as it sole argument. exclude : |Exception|, optional A type of exception (or a tuple of types) that will be purposely ignored and hence propagated to the caller without being logged. default : |Any|, optional The value to be returned by the decorated function if an error occurred without being re-raised. message : |str|, optional The message that will be automatically logged if an exception occurs. Note that it will be formatted with the ``record`` attribute. Returns ------- :term:`decorator` / :term:`context manager` An object that can be used to decorate a function or as a context manager to log exceptions possibly caught. Examples -------- >>> @logger.catch ... def f(x): ... 100 / x ... >>> def g(): ... f(10) ... f(0) ... >>> g() ERROR - An error has been caught in function 'g', process 'Main' (367), thread 'ch1' (1398): Traceback (most recent call last): File "program.py", line 12, in g() └ > File "program.py", line 10, in g f(0) └ File "program.py", line 6, in f 100 / x └ 0 ZeroDivisionError: division by zero >>> with logger.catch(message="Because we never know..."): ... main() # No exception, no logs >>> # Use 'onerror' to prevent the program exit code to be 0 (if 'reraise=False') while >>> # also avoiding the stacktrace to be duplicated on stderr (if 'reraise=True'). >>> @logger.catch(onerror=lambda _: sys.exit(1)) ... def main(): ... 1 / 0 c> eZdZdZdZfdZfdZdS)Logger.catch..Catcherc||_dSrv)_from_decorator)rmfrom_decorators r>rnz&Logger.catch..Catcher.__init__s'5$$$r@cdSrvr;rs r> __enter__z'Logger.catch..Catcher.__enter__str@c|dSt jjddrdSt| sdS t| rdS|j} j^}}}}|r|dz }|||f|dg|}d jj_  || did jj_n#d jj_wxYw | S)Nalready_logging_exceptionFr Tr;)rrrk issubclassrrr_log)rmtype_value traceback_r_roptions catch_optionsrrr=loggerrrrs r>__exit__z&Logger.catch..Catcher.__exit__s=46<57RTYZZ! 5!%33! 5&:eW+E+E& 5!%!5(.%5!g!QJE"' !;UD S7 S GK *DQKK~}grSUVVVKPFL.HH5FL.HPPPP&GENNN"{"s >B**B=ctrtdjzdtrfd}nt rfd}nfd}t j||S)Nz`Invalid object decorated with 'catch()', it must be a function, not a class (tried to wrap '%s')Tc\K5|i|d{VcdddS#1swxYwYSrvr;argsrcatcherr/functions r> catch_wrapperz=Logger.catch..Catcher.__call__..catch_wrappers$CC)14)B6)B)B#B#B#B#B#B#BCCCCCCCCCCCCCCCC& !%%c?\K5|i|Ed{VcdddS#1swxYwYSrvr;rs r>rz=Logger.catch..Catcher.__call__..catch_wrappers$JJ/7x/H/H/H$H$H$H$H$H$HJJJJJJJJJJJJJJJJ&rcL5|i|cdddS#1swxYwYSrvr;rs r>rz=Logger.catch..Catcher.__call__..catch_wrappersz$==#+8T#rz&Logger.catch..Catcher.__call__s8$$#;=E=NO "'$--&x00''''''''' )22 '''''''''''''''' (AAA$$r@N)ryrzr{rnrr r) rr/rrr=r rrrs r>rrs 6 6 6   $ #$ #$ #$ #$ #$ #$ #$ #$ #$ #$ #L % % % % % % % %r@rF)rrr BaseExceptionr) rmrr=rrrr/rrr s ```````@@r>rz Logger.catchmsj I   + "" +*4Y *N*N + 4::<< ** *L %L %L %L %L %L %L %L %L %L %L %L %L %L %L %L %L %L %\wu~~r@Tr)rrrrrrransic |rd}tjdtd|jdd} t |j|||||||g| RS)a!Parametrize a logging call to slightly change generated log message. Note that it's not possible to chain |opt| calls, the last one takes precedence over the others as it will "reset" the options to their default values. Parameters ---------- exception : |bool|, |tuple| or |Exception|, optional If it does not evaluate as ``False``, the passed exception is formatted and added to the log message. It could be an |Exception| object or a ``(type, value, traceback)`` tuple, otherwise the exception information is retrieved from |sys.exc_info|. record : |bool|, optional If ``True``, the record dict contextualizing the logging call can be used to format the message by using ``{record[key]}`` in the log message. lazy : |bool|, optional If ``True``, the logging call attribute to format the message should be functions which will be called only if the level is high enough. This can be used to avoid expensive functions if not necessary. colors : |bool|, optional If ``True``, logged message will be colorized according to the markups it possibly contains. raw : |bool|, optional If ``True``, the formatting of each sink will be bypassed and the message will be sent as is. capture : |bool|, optional If ``False``, the ``**kwargs`` of logged message will not automatically populate the ``extra`` dict (although they are still used for formatting). depth : |int|, optional Specify which stacktrace should be used to contextualize the logged message. This is useful while using the logger from inside a wrapped function to retrieve worthwhile information. ansi : |bool|, optional Deprecated since version 0.4.1: the ``ansi`` parameter will be removed in Loguru 1.0.0, it is replaced by ``colors`` which is a more appropriate name. Returns ------- :class:`~Logger` A logger wrapping the core logger, but transforming logged message adequately before sending. Examples -------- >>> try: ... 1 / 0 ... except ZeroDivisionError: ... logger.opt(exception=True).debug("Exception logged with debug level:") ... [18:10:02] DEBUG in '' - Exception logged with debug level: Traceback (most recent call last, catch point marked): > File "", line 2, in ZeroDivisionError: division by zero >>> logger.opt(record=True).info("Current line is: {record[line]}") [18:10:33] INFO in '' - Current line is: 1 >>> logger.opt(lazy=True).debug("If sink <= DEBUG: {x}", x=lambda: math.factorial(2**5)) [18:11:19] DEBUG in '' - If sink <= DEBUG: 263130836933693530167218012160000000 >>> logger.opt(colors=True).warning("We got a BIG problem") [18:11:30] WARNING in '' - We got a BIG problem >>> logger.opt(raw=True).debug("No formatting\n") No formatting >>> logger.opt(capture=False).info("Displayed but not captured: {value}", value=123) [18:11:41] Displayed but not captured: 123 >>> def wrapped(): ... logger.opt(depth=1).info("Get parent context") ... >>> def func(): ... wrapped() ... >>> func() [18:11:54] DEBUG in 'func' - Get parent context Tz?The 'ansi' parameter is deprecated, please use 'colors' instead stacklevelN)warningswarnDeprecationWarningrr}r) rmrrrrrrrrrs r>optz Logger.optsmr  F MQ"     }RSS!dj)UFD&#w^Y]^^^^r@c F|j^}}t|jg|i||RS)a6Bind attributes to the ``extra`` dict of each logged message record. This is used to add custom context to each logging call. Parameters ---------- **kwargs Mapping between keys and values that will be added to the ``extra`` dict. Returns ------- :class:`~Logger` A logger wrapping the core logger, but which sends record with the customized ``extra`` dict. Examples -------- >>> logger.add(sys.stderr, format="{extra[ip]} - {message}") >>> class Server: ... def __init__(self, ip): ... self.ip = ip ... self.logger = logger.bind(ip=ip) ... def call(self, message): ... self.logger.info(message) ... >>> instance_1 = Server("192.168.0.200") >>> instance_2 = Server("127.0.0.1") >>> instance_1.call("First instance") 192.168.0.200 - First instance >>> instance_2.call("Second instance") 127.0.0.1 - Second instance rr}r) _Logger__selfrrrbs r>bindz Logger.bind}s8B!/%flBWB.A.A&.ABBBBr@c+K|jj5it|}t|}dddn #1swxYwY dV|jj5t|ddddS#1swxYwYdS#|jj5t|dddw#1swxYwYwxYw)aBind attributes to the context-local ``extra`` dict while inside the ``with`` block. Contrary to |bind| there is no ``logger`` returned, the ``extra`` dict is modified in-place and updated globally. Most importantly, it uses |contextvars| which means that contextualized values are unique to each threads and asynchronous tasks. The ``extra`` dict will retrieve its initial state once the context manager is exited. Parameters ---------- **kwargs Mapping between keys and values that will be added to the context-local ``extra`` dict. Returns ------- :term:`context manager` / :term:`decorator` A context manager (usable as a decorator too) that will bind the attributes once entered and restore the initial state of the ``extra`` dict while exited. Examples -------- >>> logger.add(sys.stderr, format="{message} | {extra}") 1 >>> def task(): ... logger.info("Processing!") ... >>> with logger.contextualize(task_id=123): ... task() ... Processing! | {'task_id': 123} >>> logger.info("Done.") Done. | {} N)rrlrgetsetreset)r%r new_contexttokens r> contextualizezLogger.contextualizesF\  - -5W[[]]5f5KKK ,,E - - - - - - - - - - - - - - - % EEE" % % e$$$ % % % % % % % % % % % % % % % % % %" % % e$$$ % % % % % % % % % % % % % % % %sS8AAAB$/BBB$ C$1C C$C C$C C$cL|j^}}}t|jg|g|||RS)aAttach a function to modify the record dict created by each logging call. The ``patcher`` may be used to update the record on-the-fly before it's propagated to the handlers. This allows the "extra" dict to be populated with dynamic values and also permits advanced modifications of the record emitted while logging a message. The function is called once before sending the log message to the different handlers. It is recommended to apply modification on the ``record["extra"]`` dict rather than on the ``record`` dict itself, as some values are used internally by `Loguru`, and modify them may produce unexpected results. The logger can be patched multiple times. In this case, the functions are called in the same order as they are added. Parameters ---------- patcher: |callable|_ The function to which the record dict will be passed as the sole argument. This function is in charge of updating the record in-place, the function does not need to return any value, the modified record object will be re-used. Returns ------- :class:`~Logger` A logger wrapping the core logger, but which records are passed through the ``patcher`` function before being sent to the added handlers. Examples -------- >>> logger.add(sys.stderr, format="{extra[utc]} {message}") >>> logger = logger.patch(lambda record: record["extra"].update(utc=datetime.utcnow()) >>> logger.info("That's way, you can log messages with time displayed in UTC") >>> def wrapper(func): ... @functools.wraps(func) ... def wrapped(*args, **kwargs): ... logger.patch(lambda r: r.update(function=func.__name__)).info("Wrapped!") ... return func(*args, **kwargs) ... return wrapped >>> def recv_record_from_network(pipe): ... record = pickle.loads(pipe.read()) ... level, message = record["level"], record["message"] ... logger.patch(lambda r: r.update(record)).log(level, message) r$)rmrcrrrbs r>patchz Logger.patchs@\%)M!(EdjH7H,@h,@,@H%HHHHr@ct|ts$tdt|jz||cxur|cxur7nn4 |jj|S#t$rtd|zdwxYw||jjvr|td|zd\}}n.|td|z| |\}}}}||}||}t|ts$tdt|jz|dkrtd |ztj |}t||||} |jj5| |jj|<||jj|<||||f|jj|<|jjD]} | | dddn #1swxYwY| S) unAdd, update or retrieve a logging level. Logging levels are defined by their ``name`` to which a severity ``no``, an ansi ``color`` tag and an ``icon`` are associated and possibly modified at run-time. To |log| to a custom level, you should necessarily use its name, the severity number is not linked back to levels name (this implies that several levels can share the same severity). To add a new level, its ``name`` and its ``no`` are required. A ``color`` and an ``icon`` can also be specified or will be empty by default. To update an existing level, pass its ``name`` with the parameters to be changed. It is not possible to modify the ``no`` of a level once it has been added. To retrieve level information, the ``name`` solely suffices. Parameters ---------- name : |str| The name of the logging level. no : |int| The severity of the level to be added or updated. color : |str| The color markup of the level to be added or updated. icon : |str| The icon of the level to be added or updated. Returns ------- ``Level`` A |namedtuple| containing information about the level. Raises ------ ValueError If attempting to access a level with a ``name`` that is not registered, or if trying to change the severity ``no`` of an existing level. Examples -------- >>> level = logger.level("ERROR") >>> print(level) Level(name='ERROR', no=40, color='', icon='❌') >>> logger.add(sys.stderr, format="{level.no} {level.icon} {message}") 1 >>> logger.level("CUSTOM", no=15, color="", icon="@") Level(name='CUSTOM', no=15, color='', icon='@') >>> logger.log("CUSTOM", "Logging...") 15 @ Logging... >>> logger.level("WARNING", icon=r"/!\\") Level(name='WARNING', no=30, color='', icon='/!\\\\') >>> logger.warning("Updated!") 30 /!\\ Updated! z4Invalid level name, it should be a string, not: '%s'NLevel '%s' does not existzILevel '%s' does not exist, you have to create it by specifying a level no)rD z;Level '%s' already exists, you can't update its severity noz4Invalid level no, it should be an integer, not: '%s'rz:Invalid level no, it should be a positive integer, not: %d)rrrrryrr\KeyErrorrr=rrrBr(rlr^r_rar update_format) rmr)r*r+r, old_colorold_iconrrr=rs r>r=z Logger.levelsl$$$ FdI\\   & & & &$ & & & & & & & & Oz(.. O O O !>> logger.info("Allowed message by default") [22:21:55] Allowed message by default >>> logger.disable("my_library") >>> logger.info("While publishing a library, don't forget to disable logging") FN_change_activationrmr)s r>disablezLogger.disablefs , e,,,,,r@c2||ddS)aEnable logging of messages coming from ``name`` module and its children. Logging is generally disabled by imported library using `Loguru`, hence this function allows users to receive these messages anyway. To enable all logs regardless of the module they are coming from, an empty string ``""`` can be passed. Parameters ---------- name : |str| or ``None`` The name of the parent module to re-allow. Examples -------- >>> logger.disable("__main__") >>> logger.info("Disabled, so nothing is logged.") >>> logger.enable("__main__") >>> logger.info("Re-enabled, messages are logged.") [22:46:12] Re-enabled, messages are logged. TNr8r:s r>enablez Logger.enable~s , d+++++r@)rar\rbrc activationc|ng}||D]}jdi||0jj5|j_dddn #1swxYwY|ajj5jjjj|dddn #1swxYwY|5|D]2\}}|r| |3fd|DS)u Configure the core logger. It should be noted that ``extra`` values set using this function are available across all modules, so this is the best way to set overall default values. To load the configuration directly from a file, such as JSON or YAML, it is also possible to use the |loguru-config|_ library developed by `@erezinman`_. Parameters ---------- handlers : |list| of |dict|, optional A list of each handler to be added. The list should contain dicts of params passed to the |add| function as keyword arguments. If not ``None``, all previously added handlers are first removed. levels : |list| of |dict|, optional A list of each level to be added or updated. The list should contain dicts of params passed to the |level| function as keyword arguments. This will never remove previously created levels. extra : |dict|, optional A dict containing additional parameters bound to the core logger, useful to share common properties if you call |bind| in several of your files modules. If not ``None``, this will remove previously configured ``extra`` dict. patcher : |callable|_, optional A function that will be applied to the record dict of each logged messages across all modules using the logger. It should modify the dict in-place without returning anything. The function is executed prior to the one possibly added by the |patch| method. If not ``None``, this will replace previously configured ``patcher`` function. activation : |list| of |tuple|, optional A list of ``(name, state)`` tuples which denotes which loggers should be enabled (if ``state`` is ``True``) or disabled (if ``state`` is ``False``). The calls to |enable| and |disable| are made accordingly to the list order. This will not modify previously activated loggers, so if you need a fresh start prepend your list with ``("", False)`` or ``("", True)``. Returns ------- :class:`list` of :class:`int` A list containing the identifiers of added sinks (if any). Examples -------- >>> logger.configure( ... handlers=[ ... dict(sink=sys.stderr, format="[{time}] {message}"), ... dict(sink="file.log", enqueue=True, serialize=True), ... ], ... levels=[dict(name="NEW", no=13, icon="¤", color="")], ... extra={"common_to_all": "default"}, ... patcher=lambda record: record["extra"].update(some_value=42), ... activation=[("my_module.secret", False), ("another_library.module", True)], ... ) [1, 2] >>> # Set a default "extra" dict to logger across all modules, without "bind()" >>> extra = {"context": "foo"} >>> logger.configure(extra=extra) >>> logger.add(sys.stderr, format="{extra[context]} - {message}") >>> logger.info("Context without bind") >>> # => "foo - Context without bind" >>> logger.bind(context="bar").info("Suppress global context") >>> # => "bar - Suppress global context" Nc*g|]}jdi|S)r;)r)r<paramsrms r> z$Logger.configure..s+:::v""6"":::r@r;) rr=rrlrcrbclearrwr=r;) rmrar\rbrcr>rAr)rss ` r> configurezLogger.configures~   KKMMMMH    % % $$V$$$$   - -%, " - - - - - - - - - - - - - - -   / /  &&(((  ''... / / / / / / / / / / / / / / /  !) ' ' e'KK%%%%LL&&&&::::::::s# AAA/>B99B=B=c9tts$tdtjz|jj5|jj}2|D] }||||< ||j_ ||j_ ddddSdkrdz fd|jj D}tfd|Dd}||kr;dkr|dus1| |fd}| |d|D]'}|#|dzdtkr|||<(||j_ ||j_ddddS#1swxYwYdS) Nz8Invalid name, it should be a string (or None), not: '%s'rDrcTg|]$\}}|dtk ||f%Srvrr<nsr)s r>rBz-Logger._change_activation..sA1a;SYY;SWAWAWAAWAWAWr@c3XK|]$\}}dt||k |V%dSrvrGrHs r>rz,Logger._change_activation..s@!W!W14#a&&>UVCVCV!CVCVCVCV!W!Wr@Tc8|ddS)Nrr)count)xs r> modules_depthz0Logger._change_activation..modules_depth sQ4::c??*r@)keyreverse)rrrrryrrlrfrqrhrgrappendsortr)rmr)statusrfrIrg parent_statusrOs ` r>r9zLogger._change_activations7 4 5 5 JTRVZZM`` Z_ ) )j(--//G| ,,Ay%+ -3 *%, " ) ) ) ) ) ) ) )rzz #':#=O!!W!W!W!W!W!W!WY]^^M&& v~~&&f~666+++ $$$EEE ( (=a#g{T{%;t%C%C!'GAJ)8DJ &!(DJ A ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )s AE+CE++E/2E/i)castchunkc#:Ktttfrtjfd}n`t dr,t jrtjfd}n$tdtj zttrfd}n6t r}n$tdtj z tj |}n3#t$r&tdt|j zdwxYw|5}t|||}|D]%} | } || | V& ddddS#1swxYwYdS) aParse raw logs and extract each entry as a |dict|. The logging format has to be specified as the regex ``pattern``, it will then be used to parse the ``file`` and retrieve each entry based on the named groups present in the regex. Parameters ---------- file : |str|, |Path| or |file-like object|_ The path of the log file to be parsed, or an already opened file object. pattern : |str| or |re.Pattern|_ The regex to use for logs parsing, it should contain named groups which will be included in the returned dict. cast : |callable|_ or |dict|, optional A function that should convert in-place the regex groups parsed (a dict of string values) to more appropriate types. If a dict is passed, it should be a mapping between keys of parsed log dict and the function that should be used to convert the associated value. chunk : |int|, optional The number of bytes read while iterating through the logs, this avoids having to load the whole file in memory. Yields ------ :class:`dict` The dict mapping regex named groups to matched values, as returned by |match.groupdict| and optionally converted according to ``cast`` argument. Examples -------- >>> reg = r"(?P[0-9]+): (?P.*)" # If log format is "{level.no} - {message}" >>> for e in logger.parse("file.log", reg): # A file line could be "10 - A debug message" ... print(e) # => {'lvl': '10', 'msg': 'A debug message'} >>> caster = dict(lvl=int) # Parse 'lvl' key as an integer >>> for e in logger.parse("file.log", reg, cast=caster): ... print(e) # => {'lvl': 10, 'msg': 'A debug message'} >>> def cast(groups): ... if "date" in groups: ... groups["date"] = datetime.strptime(groups["date"], "%Y-%m-%d %H:%M:%S") ... >>> with open("file.log") as file: ... for log in logger.parse(file, reg, cast=cast): ... print(log["date"], log["something_else"]) c3~Ktt5}|VddddS#1swxYwYdSrv)openr)fileobjfiles r>openerzLogger.parse..openerJs#d))__"!MMM""""""""""""""""""s 266readc3KVdSrvr;)r\sr>r]zLogger.parse..openerQs r@zDInvalid file, it should be a string path or a file object, not: '%s'clD]\}}||vr|||||<dSrv)r])groupsrP converterrVs r> cast_functionz#Logger.parse..cast_function]sI&*jjll==NCf}}&/is &<&<s ==r@z:Invalid cast, it should be a function or a dict, not: '%s'zEInvalid pattern, it should be a string or a compiled regex, not: '%s'N)rrr& contextlibcontextmanagerrrr^rrryrrecompiler} _find_iter groupdict) r\patternrVrWr]rcregexr[matchesmatchras ` ` r>parsez Logger.parsesS` dS(O , ,   & " " " "' & " "T6 " " x ':':   &    ' &  Vt**%&  dD ! !  = = = = = = d^^  MMLtTXzzObb  Jw''EE   Ww--()   VXX ''>>G   ** f%%%                    s+D0D0=AFFFc#RK|d} ||}||z }t||}|s |Ed{VdSt|dkr4|d}||d}|ddEd{V)NrTr r)r^rfinditerrend)r[rkrWbuffertextrlrrs r>rhzLogger._find_iterysa (<<&&D dNF5>>&1122G """"""""7||abkoo''"3B3<''''''' (r@c|j}|jsdS |j|\}} } } n#ttf$rt |t rtd|zdt |ts%t dt|j zd|dkrtd|zddd|z|df} | \}} } } | |j|<YnwxYw| |j krdS|\ } }}}}}}}} t|dz}|j }|j}|jj}|jj}n#t$r i}d}d}d}YnwxYw |d }n#t$rd}YnwxYw |j|sdSnj#t$r]|j}||j}|||<|sYdSn?|d z}|jD]-\}}|dt+||kr |rn d ||<YdS.d ||<YnwxYwt-} t/|}!t1}"t3}#| t4z }$| rst | t6rt| | | j}'}&}%n3t | t:r| \}%}&}'nt=j\}%}&}'tA|%|&|'} nd} |$| i|j!tD#|tI|!||tK| | | |t |tM|!d|tO|#j(|#j)tU|"j(|"j)| d }(|r*d|D}d|+D}|r|r|(d,||r)d|vrt d|,|(|rG|s|rt[j.|||})n!t[j/t |})|)j0|(d<n|s|rd})|j1|i||(d<nd})|j2r|2|(|D] }*|*|(|j3D]}+|+4|(||||)dS)Nr1rrrzLevel %dr2rz ryrFT) elapsedrrbr\rr=linerrr)processthreadtimec"g|] }| Sr;r;)r<args r>rBzLogger._log..s***cCCEE***r@c*i|]\}}||Sr;r;)r<rPrs r>r?zLogger._log..s$DDDzsEc5577DDDr@rbrzThe message can't be formatted: 'record' shall not be used as a keyword argument while logger has been configured with '.opt(record=True)')rr)5rrar_r3rrrrrrryrer f_globalsf_linenof_codeco_namerrfrhrgrrr r r start_timer __traceback__tuplesysexc_inforrbrr(rrr ridentr)rr]rwrprepare_messageprepare_simple_messagestrippedrrcremit),rmr=rrrrrrlevel_id level_namelevel_no level_iconcacherrrrrrrrrbframer~rrrr)rfrT dotted_namedotted_module_namecurrent_datetime file_nameryrxrvrr traceback log_recordcolored_messagercrs, r>rz Logger._logsz}  F .9=9KE9R 6Hj(JJ)$ . . .%%% P ! 6Hj(J(-D u % % % . dn $ $ FRYOE64gx 3eai((EI~Hl*G,2KK & & &IH!G%KKK  & Z(DD   DDD  %<%   % % %lG|- & FF#Sj 262F.&"#tracez Logger.trace& GUFOYfMMMMMr@cD|dd|j|||dS)zBLog ``message.format(*args, **kwargs)`` with severity ``'DEBUG'``.r4FNrrs r>debugz Logger.debugrr@cD|dd|j|||dS)zALog ``message.format(*args, **kwargs)`` with severity ``'INFO'``.r5FNrrs r>infoz Logger.infos& FE6?ItVLLLLLr@cD|dd|j|||dS)zDLog ``message.format(*args, **kwargs)`` with severity ``'SUCCESS'``.r6FNrrs r>successzLogger.success & Iufoy$OOOOOr@cD|dd|j|||dS)zDLog ``message.format(*args, **kwargs)`` with severity ``'WARNING'``.r7FNrrs r>warningzLogger.warning$rr@cD|dd|j|||dS)zBLog ``message.format(*args, **kwargs)`` with severity ``'ERROR'``.r8FNrrs r>errorz Logger.error(rr@cD|dd|j|||dS)zELog ``message.format(*args, **kwargs)`` with severity ``'CRITICAL'``.r9FNrrs r>criticalzLogger.critical,s& Jv 4PPPPPr@c^d|jddz}|dd||||dS)zRLog an ``'ERROR'```` message while also capturing the currently handled exception.)Tr Nr8F)rr)r%rrrrs r>rzLogger.exception0s9FOABB// GUGYfEEEEEr@cD||d|j|||dS)z@Log ``message.format(*args, **kwargs)`` with severity ``level``.FNr)r%_Logger__levelrrrs r>logz Logger.log5rr@cTtjdtd|j|i|S)a;Add a handler sending log messages to a sink adequately configured. Deprecated function, use |add| instead. Warnings -------- .. deprecated:: 0.2.2 ``start()`` will be removed in Loguru 1.0.0, it is replaced by ``add()`` which is a less confusing name. z>The 'start()' method is deprecated, please use 'add()' insteadrr)rr r!rrmrrs r>startz Logger.start9s?  L     tx((((r@cTtjdtd|j|i|S)aARemove a previously added handler and stop sending logs to its sink. Deprecated function, use |remove| instead. Warnings -------- .. deprecated:: 0.2.2 ``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less confusing name. z@The 'stop()' method is deprecated, please use 'remove()' insteadrr)rr r!rrs r>rz Logger.stopKs?  N     t{D+F+++r@rv)NNN)0ryrzr{__doc__rnrr LOGURU_LEVEL LOGURU_FORMAT LOGURU_FILTERLOGURU_COLORIZELOGURU_SERIALIZELOGURU_BACKTRACELOGURU_DIAGNOSELOGURU_ENQUEUELOGURU_CONTEXT LOGURU_CATCHrrr Exceptionrr"r&rdrer-r/r=r;r=rDr9 staticmethodrnrhrrrrrrrrrrrrr;r@r>r}r}s,```RRR$&&*,,*(($G G G G G R....`?$?$?$Fj@jjjjj^   b_b_b_b_b_H"C"C"CH*%*%*%X/I/I/IbeeeeN---0,,,0%)T4\`X;X;X;X;X;t&)&)&)P%'u^^^^\^@((\("GUGUGURNNNNNNMMMPPPPPPNNNQQQFFF NNN)))$,,,,,r@r})Drrrdrrrfrrir collectionsrinspectrrrmultiprocessingrrmultiprocessing.contextr os.pathr r r rDrrrr_better_exceptionsr _colorizerr _contextvarsr _datetimer_error_interceptorr _file_sinkr _get_framer_handlerr_locks_machineryr _recattrsrrrrr _simple_sinksr r!r"r# version_infoosr&pathlibr'r(rrr1r}r;r@r>rsTTl """"""EEEEEEEEEE88888888//////&&&&&&&&$$$$$$;;;;;;;;;;;;222222!!!!!!$$$$$$ 000000 !!!!!!000000\\\\\\\\\\\\\\LLLLLLLLLLLLv,,,,,,  7;;;<< Y[[ *%r 2 2 2R)R)R)R)R)R)R)R)jF,F,F,F,F,F,F,F,F,F,r@