Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
_logger.cpython-313.pyc1355 linesDownload Raw Back to __pycache__
1�

2��j@~����SrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	J3r4 SSKJrJ
r
Jr SSKJrJr SSKJr SSKJrJr SSKJr S	S5KJrJrJrJr S	SKJr S	SKJ r  S	S
K!J"r" S	SK#J$r$ S	SK%J&r& S	SK'J(r( S	SK)J*r* S	SK+J,r, S	SK-J.r. S	SK/J0r0J1r1J2r2J3r3J4r4 S	SK5J6r6J7r7J8r8J9r9 \RtS:�aSSK;J<r< OSSK=J>r< \6"S/SQ5r?\$"5r@\""S0S9rA"SS5rB"SS 5rCg)!a�Core logging functionalities of the `Loguru` library.7 8.. References and links rendered by Sphinx are kept here as "module documentation" so that they can9   be used in the ``Logger`` docstrings but do not pollute ``help(logger)`` output.10 11.. |Logger| replace:: :class:`~Logger`12.. |add| replace:: :meth:`~Logger.add()`13.. |remove| replace:: :meth:`~Logger.remove()`14.. |complete| replace:: :meth:`~Logger.complete()`15.. |catch| replace:: :meth:`~Logger.catch()`16.. |bind| replace:: :meth:`~Logger.bind()`17.. |contextualize| replace:: :meth:`~Logger.contextualize()`18.. |patch| replace:: :meth:`~Logger.patch()`19.. |opt| replace:: :meth:`~Logger.opt()`20.. |log| replace:: :meth:`~Logger.log()`21.. |level| replace:: :meth:`~Logger.level()`22.. |enable| replace:: :meth:`~Logger.enable()`23.. |disable| replace:: :meth:`~Logger.disable()`24 25.. |Any| replace:: :obj:`~typing.Any`26.. |str| replace:: :class:`str`27.. |int| replace:: :class:`int`28.. |bool| replace:: :class:`bool`29.. |tuple| replace:: :class:`tuple`30.. |namedtuple| replace:: :func:`namedtuple<collections.namedtuple>`31.. |list| replace:: :class:`list`32.. |dict| replace:: :class:`dict`33.. |str.format| replace:: :meth:`str.format()`34.. |Path| replace:: :class:`pathlib.Path`35.. |match.groupdict| replace:: :meth:`re.Match.groupdict()`36.. |Handler| replace:: :class:`logging.Handler`37.. |sys.stderr| replace:: :data:`sys.stderr`38.. |sys.exc_info| replace:: :func:`sys.exc_info()`39.. |time| replace:: :class:`datetime.time`40.. |datetime| replace:: :class:`datetime.datetime`41.. |timedelta| replace:: :class:`datetime.timedelta`42.. |open| replace:: :func:`open()`43.. |logging| replace:: :mod:`logging`44.. |signal| replace:: :mod:`signal`45.. |contextvars| replace:: :mod:`contextvars`46.. |multiprocessing| replace:: :mod:`multiprocessing`47.. |Thread.run| replace:: :meth:`Thread.run()<threading.Thread.run()>`48.. |Exception| replace:: :class:`Exception`49.. |AbstractEventLoop| replace:: :class:`AbstractEventLoop<asyncio.AbstractEventLoop>`50.. |asyncio.get_running_loop| replace:: :func:`asyncio.get_running_loop()`51.. |asyncio.run| replace:: :func:`asyncio.run()`52.. |loop.run_until_complete| replace::53    :meth:`loop.run_until_complete()<asyncio.loop.run_until_complete()>`54.. |loop.create_task| replace:: :meth:`loop.create_task()<asyncio.loop.create_task()>`55 56.. |logger.trace| replace:: :meth:`logger.trace()<Logger.trace()>`57.. |logger.debug| replace:: :meth:`logger.debug()<Logger.debug()>`58.. |logger.info| replace:: :meth:`logger.info()<Logger.info()>`59.. |logger.success| replace:: :meth:`logger.success()<Logger.success()>`60.. |logger.warning| replace:: :meth:`logger.warning()<Logger.warning()>`61.. |logger.error| replace:: :meth:`logger.error()<Logger.error()>`62.. |logger.critical| replace:: :meth:`logger.critical()<Logger.critical()>`63 64.. |file-like object| replace:: ``file-like object``65.. _file-like object: https://docs.python.org/3/glossary.html#term-file-object66.. |callable| replace:: ``callable``67.. _callable: https://docs.python.org/3/library/functions.html#callable68.. |coroutine function| replace:: ``coroutine function``69.. _coroutine function: https://docs.python.org/3/glossary.html#term-coroutine-function70.. |re.Pattern| replace:: ``re.Pattern``71.. _re.Pattern: https://docs.python.org/3/library/re.html#re-objects72.. |multiprocessing.Context| replace:: ``multiprocessing.Context``73.. _multiprocessing.Context:74   https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods75 76.. |better_exceptions| replace:: ``better_exceptions``77.. _better_exceptions: https://github.com/Qix-/better-exceptions78 79.. |loguru-config| replace:: ``loguru-config``80.. _loguru-config: https://github.com/erezinman/loguru-config81 82.. _Pendulum: https://pendulum.eustace.io/docs/#tokens83 84.. _@Qix-: https://github.com/Qix-85.. _@erezinman: https://github.com/erezinman86.. _@sdispater: https://github.com/sdispater87 88.. _formatting directives: https://docs.python.org/3/library/string.html#format-string-syntax89.. _reentrant: https://en.wikipedia.org/wiki/Reentrancy_(computing)90�N)�91namedtuple)�isclass�iscoroutinefunction�isgeneratorfunction)�current_process�get_context)�BaseContext)�basename�splitext)�current_thread�)�
_asyncio_loop�	_colorama�	_defaults�_filters)�ExceptionFormatter)�	Colorizer)�92ContextVar)�	aware_now)�ErrorInterceptor)�FileSink)�	get_frame)�Handler)�create_logger_lock)�RecordException�93RecordFile�RecordLevel�
RecordProcess�RecordThread)�	AsyncSink�CallableSink�StandardSink�94StreamSink)��)�PathLike)�PurePath�Level)�name�no�color�icon�loguru_context��defaultc�&�\rSrSrSrSrSrSrg)�Core�c��[S[R[R[R5[S[R95[R[R5[S[R[R[R5[S[R[R[R5[S[R[R[R 5[S[R"[R$[R&5[S[R([R*[R,5/nUVs0sHo"R.U_M snUl0UR0R35VVs0sH&up2U[4R6"UR85_M( snnESS0EUlUR0R35VVs0sHup2X3X2R<UR>4_M  snnUl S	Ul!0Ul"0Ul#SUl$[KS965Ul&0Ul'/Ul(SUl)[TRV"5Ul,[[5Ul.gs snfs snnfs snnf)N�TRACE�DEBUG�INFO�SUCCESS�WARNING�ERROR�CRITICAL�r�infT)/r(r�LOGURU_TRACE_NO�LOGURU_TRACE_COLOR�LOGURU_TRACE_ICON�LOGURU_DEBUG_NO�LOGURU_DEBUG_COLOR�LOGURU_DEBUG_ICON�LOGURU_INFO_NO�LOGURU_INFO_COLOR�LOGURU_INFO_ICON�LOGURU_SUCCESS_NO�LOGURU_SUCCESS_COLOR�LOGURU_SUCCESS_ICON�LOGURU_WARNING_NO�LOGURU_WARNING_COLOR�LOGURU_WARNING_ICON�LOGURU_ERROR_NO�LOGURU_ERROR_COLOR�LOGURU_ERROR_ICON�LOGURU_CRITICAL_NO�LOGURU_CRITICAL_COLOR�LOGURU_CRITICAL_ICONr)�levels�itemsr�ansifyr+�levels_ansi_codesr*r,�
levels_lookup�handlers_count�handlers�extra�patcher�float�	min_level�enabled�activation_list�activation_none�	threading�local�
thread_localsr�lock)�selfrR�levelr)s    �TD:\code\apps\devtools\python\user_packages\Python313\site-packages\loguru/_logger.py�__init__�
Core.__init__�s9�����)�)��,�,��+�+�	
�
���)�)��,�,��+�+�	
�
���(�(��+�+��*�*�	
�
���+�+��.�.��-�-�	
�
���+�+��.�.��-�-�	
�
���)�)��,�,��+�+�	
�
���,�,��/�/��.�.�	
�K+97��X7=�=�f�U�z�z�5�(�f�=���"98�FJ�k�k�FW�FW�FY�Z�FY�{�t�t�Y�%�%�e�k�k�2�2�FY�Z�"99��"�"100���IM���HY�HY�H[�101�H[���D��x�x����4�4�H[�102��� �����
���103�����u�������!���#���&�_�_�.���&�(��	��3>��Z��104s�J5�-J:�%Kc�N�URR5nSUS'SUS'U$)Nrbrc)�__dict__�copy�rd�states  rf�__getstate__�Core.__getstate__�s,���
�
�"�"�$��!%��o����f�
���c��URRU5 [R"5Ul[5Ulg�N)rj�updater`rarbrrcrls  rf�__setstate__�Core.__setstate__�s-���
�
���U�#�&�_�_�.���&�(��	rp)
r^r_r]rYrXrWrRrUrVrcr\rZrbN)�__name__�105__module__�__qualname__�__firstlineno__rgrnrt�__static_attributes__�rprfr1r1�s��F)�P�)rpr1c�*�\rSrSrSrSrSr\R\R\R\R\R\R\R\R\R \R"S.106SjrS-SjrS	r\4S107SSSSSS
.SjjrSSSSSSSSS.SjrSr\R4S5rSrS.SjrSrSrSSSSSS.Sjr Sr!\"0SS.Sj5r#\"S5r$S r%S!r&S"r'S#r(S$r)S%r*S&r+S'r,S(r-S)r.S*r/S+r0S,r1g)/�Logger��a�An object to dispatch logging messages to configured handlers.108 109The |Logger| is the core object of ``loguru``, every logging configuration and usage pass110through a call to one of its methods. There is only one logger, so there is no need to retrieve111one before usage.112 113Once the ``logger`` is imported, it can be used to write messages about events happening in your114code. By reading the output logs of your application, you gain a better understanding of the115flow of your program and you more easily track and debug unexpected behaviors.116 117Handlers to which the logger sends log messages are added using the |add| method. Note that you118can use the |Logger| right after import as it comes pre-configured (logs are emitted to119|sys.stderr| by default). Messages can be logged with different severity levels and they can be120formatted using curly braces (it uses |str.format| under the hood).121 122When a message is logged, a "record" is associated with it. This record is a dict which contains123information about the logging context: time, function, file, line, thread, level... It also124contains the ``__name__`` of the module, this is why you don't need named loggers.125 126You should not instantiate a |Logger| by yourself, use ``from loguru import logger`` instead.127c	�(�XlX#XEXgX�U1284	Ulgrr��_core�_options)rd�core�	exception�depth�record�lazy�colors�raw�capture�patchersrYs           rfrg�Logger.__init__�s���129�"�6��g�Y^�_��
rpc�b�S[URRR55-$)Nz<loguru.logger handlers=%r>)�listr�rX�values�rds rf�__repr__�Logger.__repr__�s%��,�t�D�J�J�4G�4G�4N�4N�4P�/Q�Q�Qrp)130re�format�filter�colorize�	serialize�	backtrace�diagnose�enqueue�context�catchc131��URR URRn
UR=RS-
slSSS5 [UW
5nUc	U(aSn[	U[132[45(a,UnSU-nUcSn[U40UD6n0nURnSnSnGO![US5(a�[UR5(a�[USS5=(d [U5nUc[R"U5nUS	La2[R "U5(a[R""U5nOUn[%U5n[US133S5nSnSnGOg[	U[&R(5(a.[U5nUcSn[+U5n[US134S5nSnSnGO[-U5(d[-[USS55(a�[USS5=(d [U5nUcSnUR/S
S5nU	(aUc[0R2"5n[-U5(aUOUR8n[;UUU5nSnSnSnOg[U5(a6[USS5=(d [U5nUcSn[=U5nSnSnSnO![?S[AU5RB-5eU(a [?S[E[GU55-5eUcSnGO�US:Xa[HRJnGO�[	U[1355(a6US-n[MU5nRP"[HRRUUS9nGO~[	U[T5(Ga0nURW5H�unnUb6[	U[1365(d![?S[AU5RB-5eUSLaSnOyUS	LaSnOq[	U[1375(aURYU5RZnO?[	U[\5(aUnO'[?SU<S[AU5RB<S35eUS:a[7SUU4-5eUUU'M� [NRP"[HR^US9nOS[U5(a"U[`Rb:Xa[7S5eUnO![?S[AU5RB-5e[	U[1385(aURYU5RZn O9[	U[\5(aUn O![?S[AU5RB-5eU S:a[7SU -5e[	U[1395(a [dRf"UU-S -5n!Sn"OU[U5(a$U[`Rh:Xa[7S"5eUn!S	n"O![?S#[AU5RB-5e[	U[1405(dS$n[	U141[1425(a[kU1435n144O9U145b6[	U146[l5(d![?S%[AU1475RB-5eURR [oUUUUURpRrRtUS&9n#[)UUU U!U"UUUU	U148U
UU#URRvS'9n$URRxR{5n%U$U%U
'[}URR~U 5URl?U%URl<SSS5 U
$!,(df   GN�=f![4an[7S5UeSnAff=f![6a [7SU<SU<S35Sef=f![6an[7S!5UeSnAff=f!,(df   U
$=f)(u�vAdd a handler sending log messages to a sink adequately configured.149 150Parameters151----------152sink : |file-like object|_, |str|, |Path|, |callable|_, |coroutine function|_ or |Handler|153    An object in charge of receiving formatted logging messages and propagating them to an154    appropriate endpoint.155level : |int| or |str|, optional156    The minimum severity level from which logged messages should be sent to the sink.157format : |str| or |callable|_, optional158    The template used to format logged messages before being sent to the sink.159filter : |callable|_, |str| or |dict|, optional160    A directive optionally used to decide for each logged message whether it should be sent161    to the sink or not.162colorize : |bool|, optional163    Whether the color markups contained in the formatted message should be converted to ansi164    codes for terminal coloration, or stripped otherwise. If ``None``, the choice is165    automatically made based on the sink being a tty or not.166serialize : |bool|, optional167    Whether the logged message and its records should be first converted to a JSON string168    before being sent to the sink.169backtrace : |bool|, optional170    Whether the exception trace formatted should be extended upward, beyond the catching171    point, to show the full stacktrace which generated the error.172diagnose : |bool|, optional173    Whether the exception trace should display the variables values to eases the debugging.174    This should be set to ``False`` in production to avoid leaking sensitive data.175enqueue : |bool|, optional176    Whether the messages to be logged should first pass through a multiprocessing-safe queue177    before reaching the sink. This is useful while logging to a file through multiple178    processes. This also has the advantage of making logging calls non-blocking.179context : |multiprocessing.Context| or |str|, optional180    A context object or name that will be used for all tasks involving internally the181    |multiprocessing| module, in particular when ``enqueue=True``. If ``None``, the default182    context is used.183catch : |bool|, optional184    Whether errors occurring while sink handles logs messages should be automatically185    caught. If ``True``, an exception message is displayed on |sys.stderr| but the exception186    is not propagated to the caller, preventing your app to crash.187**kwargs188    Additional parameters that are only valid to configure a coroutine or file sink (see189    below).190 191 192If and only if the sink is a coroutine function, the following parameter applies:193 194Parameters195----------196loop : |AbstractEventLoop|, optional197    The event loop in which the asynchronous logging task will be scheduled and executed. If198    ``None``, the loop used is the one returned by |asyncio.get_running_loop| at the time of199    the logging call (task is discarded if there is no loop currently running).200 201 202If and only if the sink is a file path, the following parameters apply:203 204Parameters205----------206rotation : |str|, |int|, |time|, |timedelta| or |callable|_, optional207    A condition indicating whenever the current logged file should be closed and a new one208    started.209retention : |str|, |int|, |timedelta| or |callable|_, optional210    A directive filtering old files that should be removed during rotation or end of211    program.212compression : |str| or |callable|_, optional213    A compression or archive format to which log files should be converted at closure.214delay : |bool|, optional215    Whether the file should be created as soon as the sink is configured, or delayed until216    first logged message. It defaults to ``False``.217watch : |bool|, optional218    Whether or not the file should be watched and re-opened when deleted or changed (based219    on its device and inode properties) by an external program. It defaults to ``False``.220mode : |str|, optional221    The opening mode as for built-in |open| function. It defaults to ``"a"`` (open the222    file in appending mode).223buffering : |int|, optional224    The buffering policy as for built-in |open| function. It defaults to ``1`` (line225    buffered file).226encoding : |str|, optional227    The file encoding as for built-in |open| function. It defaults to ``"utf8"``.228**kwargs229    Others parameters are passed to the built-in |open| function.230 231Returns232-------233:class:`int`234    An identifier associated with the added sink and which should be used to235    |remove| it.236 237Raises238------239ValueError240    If any of the arguments passed to configure the sink is invalid.241 242Notes243-----244Extended summary follows.245 246.. _sink:247 248.. rubric:: The sink parameter249 250The ``sink`` handles incoming log messages and proceed to their writing somewhere and251somehow. A sink can take many forms:252 253- A |file-like object|_ like ``sys.stderr`` or ``open("file.log", "w")``. Anything with254  a ``.write()`` method is considered as a file-like object. Custom handlers may also255  implement ``flush()`` (called after each logged message), ``stop()`` (called at sink256  termination) and ``complete()`` (awaited by the eponymous method).257- A file path as |str| or |Path|. It can be parametrized with some additional parameters,258  see below.259- A |callable|_ (such as a simple function) like ``lambda msg: print(msg)``. This260  allows for logging procedure entirely defined by user preferences and needs.261- A asynchronous |coroutine function|_ defined with the ``async def`` statement. The262  coroutine object returned by such function will be added to the event loop using263  |loop.create_task|. The tasks should be awaited before ending the loop by using264  |complete|.265- A built-in |Handler| like ``logging.StreamHandler``. In such a case, the `Loguru` records266  are automatically converted to the structure expected by the |logging| module.267 268Note that the logging functions are not `reentrant`_. This means you should avoid using269the ``logger`` inside any of your sinks or from within |signal| handlers. Otherwise, you270may face deadlock if the module's sink was not explicitly disabled.271 272.. _message:273 274.. rubric:: The logged message275 276The logged message passed to all added sinks is nothing more than a string of the277formatted log, to which a special attribute is associated: the ``.record`` which is a dict278containing all contextual information possibly needed (see below).279 280Logged messages are formatted according to the ``format`` of the added sink. This format281is usually a string containing braces fields to display attributes from the record dict.282 283If fine-grained control is needed, the ``format`` can also be a function which takes the284record as parameter and return the format template string. However, note that in such a285case, you should take care of appending the line ending and exception field to the returned286format, while ``"\n{exception}"`` is automatically appended for convenience if ``format`` is287a string.288 289The ``filter`` attribute can be used to control which messages are effectively passed to the290sink and which one are ignored. A function can be used, accepting the record as an291argument, and returning ``True`` if the message should be logged, ``False`` otherwise. If292a string is used, only the records with the same ``name`` and its children will be allowed.293One can also pass a ``dict`` mapping module names to minimum required level. In such case,294each log record will search for it's closest parent in the ``dict`` and use the associated295level as the filter. The ``dict`` values can be ``int`` severity, ``str`` level name or296``True`` and ``False`` to respectively authorize and discard all module logs297unconditionally. In order to set a default level, the ``""`` module name should be used as298it is the parent of all modules (it does not suppress global ``level`` threshold, though).299 300Note that while calling a logging method, the keyword arguments (if any) are automatically301added to the ``extra`` dict for convenient contextualization (in addition to being used for302formatting).303 304.. _levels:305 306.. rubric:: The severity levels307 308Each logged message is associated with a severity level. These levels make it possible to309prioritize messages and to choose the verbosity of the logs according to usages. For310example, it allows to display some debugging information to a developer, while hiding it to311the end user running the application.312 313The ``level`` attribute of every added sink controls the minimum threshold from which log314messages are allowed to be emitted. While using the ``logger``, you are in charge of315configuring the appropriate granularity of your logs. It is possible to add even more custom316levels by using the |level| method.317 318Here are the standard levels with their default severity value, each one is associated with319a logging method of the same name:320 321+----------------------+------------------------+------------------------+322| Level name           | Severity value         | Logger method          |323+======================+========================+========================+324| ``TRACE``            | 5                      | |logger.trace|         |325+----------------------+------------------------+------------------------+326| ``DEBUG``            | 10                     | |logger.debug|         |327+----------------------+------------------------+------------------------+328| ``INFO``             | 20                     | |logger.info|          |329+----------------------+------------------------+------------------------+330| ``SUCCESS``          | 25                     | |logger.success|       |331+----------------------+------------------------+------------------------+332| ``WARNING``          | 30                     | |logger.warning|       |333+----------------------+------------------------+------------------------+334| ``ERROR``            | 40                     | |logger.error|         |335+----------------------+------------------------+------------------------+336| ``CRITICAL``         | 50                     | |logger.critical|      |337+----------------------+------------------------+------------------------+338 339.. _record:340 341.. rubric:: The record dict342 343The record is just a Python dict, accessible from sinks by ``message.record``. It contains344all contextual information of the logging call (time, function, file, line, level, etc.).345 346Each of the record keys can be used in the handler's ``format`` so the corresponding value347is properly displayed in the logged message (e.g. ``"{level}"`` will return ``"INFO"``).348Some records' values are objects with two or more attributes. These can be formatted with349``"{key.attr}"`` (``"{key}"`` would display one by default).350 351Note that you can use any `formatting directives`_ available in Python's ``str.format()``352method (e.g. ``"{key: >3}"`` will right-align and pad to a width of 3 characters). This is353particularly useful for time formatting (see below).354 355+------------+---------------------------------+----------------------------+356| Key        | Description                     | Attributes                 |357+============+=================================+============================+358| elapsed    | The time elapsed since the      | See |timedelta|            |359|            | start of the program            |                            |360+------------+---------------------------------+----------------------------+361| exception  | The formatted exception if any, | ``type``, ``value``,       |362|            | ``None`` otherwise              | ``traceback``              |363+------------+---------------------------------+----------------------------+364| extra      | The dict of attributes          | None                       |365|            | bound by the user (see |bind|)  |                            |366+------------+---------------------------------+----------------------------+367| file       | The file where the logging call | ``name`` (default),        |368|            | was made                        | ``path``                   |369+------------+---------------------------------+----------------------------+370| function   | The function from which the     | None                       |371|            | logging call was made           |                            |372+------------+---------------------------------+----------------------------+373| level      | The severity used to log the    | ``name`` (default),        |374|            | message                         | ``no``, ``icon``           |375+------------+---------------------------------+----------------------------+376| line       | The line number in the source   | None                       |377|            | code                            |                            |378+------------+---------------------------------+----------------------------+379| message    | The logged message (not yet     | None                       |380|            | formatted)                      |                            |381+------------+---------------------------------+----------------------------+382| module     | The module where the logging    | None                       |383|            | call was made                   |                            |384+------------+---------------------------------+----------------------------+385| name       | The ``__name__`` where the      | None                       |386|            | logging call was made           |                            |387+------------+---------------------------------+----------------------------+388| process    | The process in which the        | ``name``, ``id`` (default) |389|            | logging call was made           |                            |390+------------+---------------------------------+----------------------------+391| thread     | The thread in which the         | ``name``, ``id`` (default) |392|            | logging call was made           |                            |393+------------+---------------------------------+----------------------------+394| time       | The aware local time when the   | See |datetime|             |395|            | logging call was made           |                            |396+------------+---------------------------------+----------------------------+397 398.. _time:399 400.. rubric:: The time formatting401 402To use your favorite time representation, you can set it directly in the time formatter403specifier of your handler format, like for example ``format="{time:HH:mm:ss} {message}"``.404Note that this datetime represents your local time, and it is also made timezone-aware,405so you can display the UTC offset to avoid ambiguities.406 407The time field can be formatted using more human-friendly tokens. These constitute a subset408of the one used by the `Pendulum`_ library of `@sdispater`_. To escape a token, just add409square brackets around it, for example ``"[YY]"`` would display literally ``"YY"``.410 411If you prefer to display UTC rather than local time, you can add ``"!UTC"`` at the very end412of the time format, like ``{time:HH:mm:ss!UTC}``. Doing so will convert the ``datetime``413to UTC before formatting.414 415If no time formatter specifier is used, like for example if ``format="{time} {message}"``,416the default one will use ISO 8601.417 418+------------------------+---------+----------------------------------------+419|                        | Token   | Output                                 |420+========================+=========+========================================+421| Year                   | YYYY    | 2000, 2001, 2002 ... 2012, 2013        |422|                        +---------+----------------------------------------+423|                        | YY      | 00, 01, 02 ... 12, 13                  |424+------------------------+---------+----------------------------------------+425| Quarter                | Q       | 1 2 3 4                                |426+------------------------+---------+----------------------------------------+427| Month                  | MMMM    | January, February, March ...           |428|                        +---------+----------------------------------------+429|                        | MMM     | Jan, Feb, Mar ...                      |430|                        +---------+----------------------------------------+431|                        | MM      | 01, 02, 03 ... 11, 12                  |432|                        +---------+----------------------------------------+433|                        | M       | 1, 2, 3 ... 11, 12                     |434+------------------------+---------+----------------------------------------+435| Day of Year            | DDDD    | 001, 002, 003 ... 364, 365             |436|                        +---------+----------------------------------------+437|                        | DDD     | 1, 2, 3 ... 364, 365                   |438+------------------------+---------+----------------------------------------+439| Day of Month           | DD      | 01, 02, 03 ... 30, 31                  |440|                        +---------+----------------------------------------+441|                        | D       | 1, 2, 3 ... 30, 31                     |442+------------------------+---------+----------------------------------------+443| Day of Week            | dddd    | Monday, Tuesday, Wednesday ...         |444|                        +---------+----------------------------------------+445|                        | ddd     | Mon, Tue, Wed ...                      |446|                        +---------+----------------------------------------+447|                        | d       | 0, 1, 2 ... 6                          |448+------------------------+---------+----------------------------------------+449| Days of ISO Week       | E       | 1, 2, 3 ... 7                          |450+------------------------+---------+----------------------------------------+451| Hour                   | HH      | 00, 01, 02 ... 23, 24                  |452|                        +---------+----------------------------------------+453|                        | H       | 0, 1, 2 ... 23, 24                     |454|                        +---------+----------------------------------------+455|                        | hh      | 01, 02, 03 ... 11, 12                  |456|                        +---------+----------------------------------------+457|                        | h       | 1, 2, 3 ... 11, 12                     |458+------------------------+---------+----------------------------------------+459| Minute                 | mm      | 00, 01, 02 ... 58, 59                  |460|                        +---------+----------------------------------------+461|                        | m       | 0, 1, 2 ... 58, 59                     |462+------------------------+---------+----------------------------------------+463| Second                 | ss      | 00, 01, 02 ... 58, 59                  |464|                        +---------+----------------------------------------+465|                        | s       | 0, 1, 2 ... 58, 59                     |466+------------------------+---------+----------------------------------------+467| Fractional Second      | S       | 0 1 ... 8 9                            |468|                        +---------+----------------------------------------+469|                        | SS      | 00, 01, 02 ... 98, 99                  |470|                        +---------+----------------------------------------+471|                        | SSS     | 000 001 ... 998 999                    |472|                        +---------+----------------------------------------+473|                        | SSSS... | 000[0..] 001[0..] ... 998[0..] 999[0..]|474|                        +---------+----------------------------------------+475|                        | SSSSSS  | 000000 000001 ... 999998 999999        |476+------------------------+---------+----------------------------------------+477| AM / PM                | A       | AM, PM                                 |478+------------------------+---------+----------------------------------------+479| Timezone               | Z       | -07:00, -06:00 ... +06:00, +07:00      |480|                        +---------+----------------------------------------+481|                        | ZZ      | -0700, -0600 ... +0600, +0700          |482|                        +---------+----------------------------------------+483|                        | zz      | EST CST ... MST PST                    |484+------------------------+---------+----------------------------------------+485| Seconds timestamp      | X       | 1381685817, 1234567890.123             |486+------------------------+---------+----------------------------------------+487| Microseconds timestamp | x       | 1234567890123                          |488+------------------------+---------+----------------------------------------+489 490.. _file:491 492.. rubric:: The file sinks493 494If the sink is a |str| or a |Path|, the corresponding file will be opened for writing logs.495The path can also contain a special ``"{time}"`` field that will be formatted with the496current date at file creation. The file is closed at sink stop, i.e. when the application497ends or the handler is removed.498 499The ``rotation`` check is made before logging each message. If there is already an existing500file with the same name that the file to be created, then the existing file is renamed by501appending the date to its basename to prevent file overwriting. This parameter accepts:502 503- an |int| which corresponds to the maximum file size in bytes before that the current504  logged file is closed and a new one started over.505- a |timedelta| which indicates the frequency of each new rotation.506- a |time| which specifies the hour when the daily rotation should occur.507- a |str| for human-friendly parametrization of one of the previously enumerated types.508  Examples: ``"100 MB"``, ``"0.5 GB"``, ``"1 month 2 weeks"``, ``"4 days"``, ``"10h"``,509  ``"monthly"``, ``"18:00"``, ``"sunday"``, ``"w0"``, ``"monday at 12:00"``, ...510- a |callable|_ which will be invoked before logging. It should accept two arguments: the511  logged message and the file object, and it should return ``True`` if the rotation should512  happen now, ``False`` otherwise.513 514The ``retention`` occurs at rotation or at sink stop if rotation is ``None``. Files515resulting from previous sessions or rotations are automatically collected from disk. A file516is selected if it matches the pattern ``"basename(.*).ext(.*)"`` (possible time fields are517beforehand replaced with ``.*``) based on the configured sink. Afterwards, the list is518processed to determine files to be retained. This parameter accepts:519 520- an |int| which indicates the number of log files to keep, while older files are deleted.521- a |timedelta| which specifies the maximum age of files to keep.522- a |str| for human-friendly parametrization of the maximum age of files to keep.523  Examples: ``"1 week, 3 days"``, ``"2 months"``, ...524- a |callable|_ which will be invoked before the retention process. It should accept the525  list of log files as argument and process to whatever it wants (moving files, removing526  them, etc.).527 528The ``compression`` happens at rotation or at sink stop if rotation is ``None``. This529parameter accepts:530 531- a |str| which corresponds to the compressed or archived file extension. This can be one532  of: ``"gz"``, ``"bz2"``, ``"xz"``, ``"lzma"``, ``"tar"``, ``"tar.gz"``, ``"tar.bz2"``,533  ``"tar.xz"``, ``"zip"``.534- a |callable|_ which will be invoked before file termination. It should accept the path of535  the log file as argument and process to whatever it wants (custom compression, network536  sending, removing it, etc.).537 538Either way, if you use a custom function designed according to your preferences, you must be539very careful not to use the ``logger`` within your function. Otherwise, there is a risk that540your program hang because of a deadlock.541 542.. _color:543 544.. rubric:: The color markups545 546To add colors to your logs, you just have to enclose your format string with the appropriate547tags (e.g. ``<red>some message</red>``). These tags are automatically removed if the sink548doesn't support ansi codes. For convenience, you can use ``</>`` to close the last opening549tag without repeating its name (e.g. ``<red>another message</>``).550 551The special tag ``<level>`` (abbreviated with ``<lvl>``) is transformed according to552the configured color of the logged message level.553 554Tags which are not recognized will raise an exception during parsing, to inform you about555possible misuse. If you wish to display a markup tag literally, you can escape it by556prepending a ``\`` like for example ``\<blue>``. To prevent the escaping to occur, you can557simply double the ``\`` (e.g. ``\\<blue>`` will print a literal ``\`` before colored text).558If, for some reason, you need to escape a string programmatically, note that the regex used559internally to parse markup tags is ``r"(\\*)(</?(?:[fb]g\s)?[^<>\s]*>)"``.560 561Note that when logging a message with ``opt(colors=True)``, color tags present in the562formatting arguments (``args`` and ``kwargs``) are completely ignored. This is important if563you need to log strings containing markups that might interfere with the color tags (in this564case, do not use f-string).565 566Here are the available tags (note that compatibility may vary depending on terminal):567 568+------------------------------------+--------------------------------------+569| Color (abbr)                       | Styles (abbr)                        |570+====================================+======================================+571| Black (k)                          | Bold (b)                             |572+------------------------------------+--------------------------------------+573| Blue (e)                           | Dim (d)                              |574+------------------------------------+--------------------------------------+575| Cyan (c)                           | Normal (n)                           |576+------------------------------------+--------------------------------------+577| Green (g)                          | Italic (i)                           |578+------------------------------------+--------------------------------------+579| Magenta (m)                        | Underline (u)                        |580+------------------------------------+--------------------------------------+581| Red (r)                            | Strike (s)                           |582+------------------------------------+--------------------------------------+583| White (w)                          | Reverse (v)                          |584+------------------------------------+--------------------------------------+585| Yellow (y)                         | Blink (l)                            |586+------------------------------------+--------------------------------------+587|                                    | Hide (h)                             |588+------------------------------------+--------------------------------------+589 590Usage:591 592+-----------------+-------------------------------------------------------------------+593| Description     | Examples                                                          |594|                 +---------------------------------+---------------------------------+595|                 | Foreground                      | Background                      |596+=================+=================================+=================================+597| Basic colors    | ``<red>``, ``<r>``              | ``<GREEN>``, ``<G>``            |598+-----------------+---------------------------------+---------------------------------+599| Light colors    | ``<light-blue>``, ``<le>``      | ``<LIGHT-CYAN>``, ``<LC>``      |600+-----------------+---------------------------------+---------------------------------+601| 8-bit colors    | ``<fg 86>``, ``<fg 255>``       | ``<bg 42>``, ``<bg 9>``         |602+-----------------+---------------------------------+---------------------------------+603| Hex colors      | ``<fg #00005f>``, ``<fg #EE1>`` | ``<bg #AF5FD7>``, ``<bg #fff>`` |604+-----------------+---------------------------------+---------------------------------+605| RGB colors      | ``<fg 0,95,0>``                 | ``<bg 72,119,65>``              |606+-----------------+---------------------------------+---------------------------------+607| Stylizing       | ``<bold>``, ``<b>``,  ``<underline>``, ``<u>``                    |608+-----------------+-------------------------------------------------------------------+609 610.. _env:611 612.. rubric:: The environment variables613 614The default values of sink parameters can be entirely customized. This is particularly615useful if you don't like the log format of the pre-configured sink.616 617Each of the |add| default parameter can be modified by setting the ``LOGURU_[PARAM]``618environment variable. For example on Linux: ``export LOGURU_FORMAT="{time} - {message}"``619or ``export LOGURU_DIAGNOSE=NO``.620 621The default levels' attributes can also be modified by setting the ``LOGURU_[LEVEL]_[ATTR]``622environment variable. For example, on Windows: ``setx LOGURU_DEBUG_COLOR "<blue>"``623or ``setx LOGURU_TRACE_ICON "🚀"``. If you use the ``set`` command, do not include quotes624but escape special symbol as needed, e.g. ``set LOGURU_DEBUG_COLOR=^<blue^>``.625 626If you want to disable the pre-configured sink, you can set the ``LOGURU_AUTOINIT``627variable to ``False``.628 629On Linux, you will probably need to edit the ``~/.profile`` file to make this persistent. On630Windows, don't forget to restart your terminal for the change to be taken into account.631 632Examples633--------634>>> logger.add(sys.stdout, format="{time} - {level} - {message}", filter="sub.module")635 636>>> logger.add("file_{time}.log", level="TRACE", rotation="100 MB")637 638>>> def debug_only(record):639...     return record["level"].name == "DEBUG"640...641>>> logger.add("debug.log", filter=debug_only)  # Other levels are filtered out642 643>>> def my_sink(message):644...     record = message.record645...     update_db(message, time=record["time"], level=record["level"])646...647>>> logger.add(my_sink)648 649>>> level_per_module = {650...     "": "DEBUG",651...     "third.lib": "WARNING",652...     "anotherlib": False653... }654>>> logger.add(lambda m: print(m, end=""), filter=level_per_module, level=0)655 656>>> async def publish(message):657...     await api.post(message)658...659>>> logger.add(publish, serialize=True)660 661>>> from logging import StreamHandler662>>> logger.add(StreamHandler(sys.stderr), format="{message}")663 664>>> class RandomStream:665...     def __init__(self, seed, threshold):666...         self.threshold = threshold667...         random.seed(seed)668...     def write(self, message):669...         if random.random() > self.threshold:670...             print(message)671...672>>> stream_object = RandomStream(seed=12345, threshold=0.25)673>>> logger.add(stream_object, level="INFO")674r
NFz'%s'�675r;�writer)T�encoding�__call__rv�loopz�An 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'�.)�parent�lengthzVThe 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_modulez�The 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 correctlyz�The 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')r�r�r�r��hidden_frames_filename�prefix)r)�sink�levelno�	formatter�is_formatter_dynamic�filter_r�r�r��multiprocessing_context�id_�error_interceptor�exception_formatterrU)@r�rcrWr�676isinstance�strr&rr��hasattr�callabler��getattr�reprr�should_colorize�should_wrap�wrapr#�loggingrr"r�popr�get_running_loop�RuntimeError�677ValueErrorr�r r!�	TypeError�typerv�next�iterr�filter_none�len�	functools�partial�filter_by_name�dictrSrer*�int�filter_by_level�builtinsr�r�prepare_formatr�rr	rr��__code__�co_filenamerUrXrk�minr\)&rdr�rer�r�r�r�r�r�r�r�r��kwargs�678handler_idr��pathr)�wrapped_sinkr��679terminator�exception_prefix�streamr��e�coro�filter_funcr�r�r��module�level_�levelno_r�r�r�r��handlerrXs&                                      rf�add�680Logger.add�sY��~�Z�Z�_�_����2�2�J��J�J�%�%��*�%��-�U�J�?����	��H��d�S�(�O�,�,��D��D�=�D��� ��#�D�3�F�3�L��F�#�,�,�H��J�!��
�T�7�
#�
#�����(<�(<��4���.�<�$�t�*�D���$�4�4�T�:���4��I�$9�$9�$�$?�$?�"����-����%�f�-�L��t�Z��6�H��J�!��
��g�o�o�
.�
.���:�D��� ��'��-�L��t�Z��6�H��J�#��
 ��
&�
&�*=��D�*�d�+�+681�+682��4��T�2�@�d�4�j�D��� ���:�:�f�d�+�D��4�<��(�9�9�;�D�/�t�4�4�4�$�-�-�D�$�T�4�1B�C�L��H��J�!��
�d�^�^��4��T�2�@�d�4�j�D��� ��'��-�L��H��J�!���@�4��:�CV�CV�V�W�W���K�d�SW�X^�S_�N`�`�a�a��>��K�
�r�\�"�.�.�K�
���
$�
$��c�\�F���[�F�#�+�+�H�,C�,C�F�[a�b�K�
���
%�
%�!��"(�,�,�.�����%�j���.E�.E�#�E�GK�F�|�G\�G\�]����U�?�$�H��t�^� �H����,�,�$�#'�:�:�f�#5�#8�#8�� ���,�,�%�H�#�"�4��<�#8�#8�:���683�a�<�$�E�HN�PX�GY�Z���,4� ��(�?#1�@$�+�+��(�(�;K��K��f�
�
�����(� �*���684!�K��X��v�,�'�'�(��
�685�e�S�!�!��j�j��'�*�*�G�
��s�
#�
#��G��O��u�+�&�&�'��
�686�Q�;��O�RY�Y��
��f�c�"�"�
�%�4�4�V�j�5H�=�5X�Y�	�687$)� �
�f�
�
�����(� �*���688�I�#'� ��P��v�,�'�'�(��
�689�(�C�(�(��H��g�s�#�#�!�'�*�G�
�
 ��G�[�)I�)I���"�7�m�4�4�5��
�690�Z�Z�_�_�"4�!�!�!�#�'+�z�z�':�':�'F�'F�'�
#����!��#�%9�#�!�#��(/��"3�$7�"&�*�*�">�">��G�"�z�z�*�*�/�/�1�H�#*�H�Z� �#&�t�z�z�';�';�W�#E�D�J�J� �"*�D�J�J��?�B��Q�_��@$��$�^�������d&�$�(�<B�F�L�� $�$�$��l�
� �Q�����
��>�_�B��sT�6\=�']�3]-�8^�3C^.�=691]�692]*�]%�%]*�- ^
�693^+�^&�&^+�.694^=Nc��Ub6[U[5(d![S[U5R-5eUR695R Ub(XR696R;a[SU-5SeUc [UR697R5nOU/nUH�nUR698RR5nURU5nSUR55n[U[S5S9UR699lX0R700lUR!5 M� SSS5 g!,(df   g=f)aBRemove a previously added handler and stop sending logs to its sink.701 702Parameters703----------704handler_id : |int| or ``None``705    The id of the sink to remove, as it was returned by the |add| method. If ``None``, all706    handlers are removed. The pre-configured handler is guaranteed to have the index ``0``.707 708Raises709------710ValueError711    If ``handler_id`` is not ``None`` but there is no active handler with such id.712 713Examples714--------715>>> i = logger.add(sys.stderr, format="{message}")716>>> logger.info("Logging")717Logging718>>> logger.remove(i)719>>> logger.info("No longer logging")720NzbInvalid 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�8# �UHoRv� M g7frr)r�)�.0�hs  rf�	<genexpr>� Logger.remove.<locals>.<genexpr>&s���A�/@�!�I�I�/@�s�r<r.)r�r�r�r�rvr�rcrXr�r�rkr�r�r�r[r\�stop)rdr��handler_idsrXr��levelnoss      rf�remove�
Logger.remove�s��,�"�j��S�&A�&A��=�?C�J�?O�?X�?X�Y��
�721�Z�Z�_�_��%�*�J�J�<O�<O�*O� �!J�Z�!W�X�^b�b��!�"�4�:�:�#6�#6�7��)�l��)�722��:�:�.�.�3�3�5��"�,�,�z�2��B�x���/@�A��'*�8�U�5�\�'J��723�724�$�&.�725�726�#�����*��_�_�s
�C)E�727Ec�d^�/mURR URRR5nUR	5H2nUR5 TR
UR55 M4 SSS5 "U4SjS5nU"5$!,(df   N"=f)aVWait for the end of enqueued messages and asynchronous tasks scheduled by handlers.728 729This method proceeds in two steps: first it waits for all logging messages added to handlers730with ``enqueue=True`` to be processed, then it returns an object that can be awaited to731finalize all logging tasks added to the event loop by coroutine sinks.732 733It can be called from non-asynchronous code. This is especially recommended when the734``logger`` is utilized with ``multiprocessing`` to ensure messages put to the internal735queue have been properly transmitted before leaving a child process.736 737The returned object should be awaited before the end of a coroutine executed by738|asyncio.run| or |loop.run_until_complete| to ensure all asynchronous logging messages are739processed. The function |asyncio.get_running_loop| is called beforehand, only tasks740scheduled in the same loop that the current one will be awaited by the method.741 742Returns743-------744:term:`awaitable`745    An awaitable object which ensures all asynchronous logging calls are completed when746    awaited.747 748Examples749--------750>>> async def sink(message):751...     await asyncio.sleep(0.1)  # IO processing...752...     print(message, end="")753...754>>> async def work():755...     logger.info("Start")756...     logger.info("End")757...     await logger.complete()758...759>>> logger.add(sink)7601761>>> asyncio.run(work())762Start763End764 765>>> def process():766...     logger.info("Message sent from the child")767...     logger.complete()768...769>>> logger.add(sys.stderr, enqueue=True)7701771>>> process = multiprocessing.Process(target=process)772>>> process.start()773>>> process.join()774Message sent from the child775Nc�">�\rSrSrU4SjrSrg)�+Logger.complete.<locals>.AwaitableCompleterifc3�T># �THnUR5Shv�N M gN	7frr)�	__await__)rd�task�taskss  �rfr��5Logger.complete.<locals>.AwaitableCompleter.__await__gs#����!�D�#�~�~�/�/�/�"�/�s�(�&�776(r{N)rvrwrxryr�rz)r�s�rf�AwaitableCompleterr�fs
���
0�
0rpr�)r�rcrXrkr��complete_queue�extend�tasks_to_complete)rdrXr�r�r�s    @rf�complete�Logger.complete,s����d��
�Z�Z�_�_��z�z�*�*�/�/�1�H�#�?�?�,���&�&�(����W�6�6�8�9�-��	0�	0�777"�#�#��_�s�A+B!�!778B/r9Fz�An error has been caught in function '{record[function]}', process '{record[process].name}' ({record[process].id}), thread '{record[thread].name}' ({record[thread].id}):)re�reraise�onerror�excluder/�messagec��^^^^^^^^^	�[T5(a;[T5(a[T[5(dUR	5"T5$Um	"UUUUUU	UUU4	SjS5mT"S5$)uT779Return a decorator to automatically log possibly caught error in wrapped function.780 781This is useful to ensure unexpected exceptions are logged, the entire program can be782wrapped by this method. This is also very useful to decorate |Thread.run| methods while783using threads to propagate errors to the main logger thread.784 785Note that the visibility of variables values (which uses the great |better_exceptions|_786library from `@Qix-`_) depends on the ``diagnose`` option of each configured sink.787 788The returned object can also be used as a context manager.789 790Parameters791----------792exception : |Exception|, optional793    The type of exception to intercept. If several types should be caught, a tuple of794    exceptions can be used too.795level : |str| or |int|, optional796    The level name or severity with which the message should be logged.797reraise : |bool|, optional798    Whether the exception should be raised again and hence propagated to the caller.799onerror : |callable|_, optional800    A function that will be called if an error occurs, once the message has been logged.801    It should accept the exception instance as it sole argument.802exclude : |Exception|, optional803    A type of exception (or a tuple of types) that will be purposely ignored and hence804    propagated to the caller without being logged.805default : |Any|, optional806    The value to be returned by the decorated function if an error occurred without being807    re-raised.808message : |str|, optional809    The message that will be automatically logged if an exception occurs. Note that it will810    be formatted with the ``record`` attribute.811 812Returns813-------814:term:`decorator` / :term:`context manager`815    An object that can be used to decorate a function or as a context manager to log816    exceptions possibly caught.817 818Examples819--------820>>> @logger.catch821... def f(x):822...     100 / x823...824>>> def g():825...     f(10)826...     f(0)827...828>>> g()829ERROR - An error has been caught in function 'g', process 'Main' (367), thread 'ch1' (1398):830Traceback (most recent call last):831  File "program.py", line 12, in <module>832    g()833    └ <function g at 0x7f225fe2bc80>834> File "program.py", line 10, in g835    f(0)836    └ <function f at 0x7f225fe2b9d8>837  File "program.py", line 6, in f838    100 / x839          └ 0840ZeroDivisionError: division by zero841 842>>> with logger.catch(message="Because we never know..."):843...    main()  # No exception, no logs844 845>>> # Use 'onerror' to prevent the program exit code to be 0 (if 'reraise=False') while846>>> # also avoiding the stacktrace to be duplicated on stderr (if 'reraise=True').847>>> @logger.catch(onerror=lambda _: sys.exit(1))848... def main():849...     1 / 0850c�H>	�\rSrSrSrSrUUUUUUU4SjrUU4SjrSrg)�Logger.catch.<locals>.Catcheri�c��Xlgrr��_from_decorator)rd�from_decorators  rfrg�&Logger.catch.<locals>.Catcher.__init__�s��'5�$rpc��grrr{r�s rf�	__enter__�'Logger.catch.<locals>.Catcher.__enter__�s��rpc�>�Ucg[TRRSS5(ag[UT	5(dgT851b[UT8525(agURnTR853tpVpWU(aUS-
nXU4US/UQnSTRRlTRTXHT
S05 STRRlTbT"U5 T(+$!STRRlf=f)N�already_logging_exceptionFr
Tr{)r�r�rb�854issubclassrr�r�_log)rd�type_�value�855traceback_r�_r��options�
catch_optionsr�rre�loggerrr�r�s         �������rf�__exit__�&Logger.catch.<locals>.Catcher.__exit__�s�����=���6�<�<�5�5�7R�TY�Z�Z� �!�%��3�3� ��&�:�e�W�+E�+E� �!%�!5�!5��(.���%��!�!��Q�J�E�"'�856�!;�U�D� S�7� S�
�GK����*�*�D�Q��K�K��~�g�r�SU�V�KP�F�L�L�.�.�H��&��E�N�"�{�"��LQ�F�L�L�.�.�H�s�C!�!C>c�>^^�[T5(a[STR-5eT"S5m[T5(a	UUU4SjnO![	T5(a	UUU4SjnOUUU4Sjn[857R"UT5 U$)Nz`Invalid object decorated with 'catch()', it must be a function, not a class (tried to wrap '%s')Tc��l># �T T"U0UD6IShv�NsSSS5 $N
!,(df   T$=f7frrr{��argsr��catcherr/�functions  ���rf�
catch_wrapper�=Logger.catch.<locals>.Catcher.__call__.<locals>.catch_wrappers/����$�)1�4�)B�6�)B�#B�%�W�#B�%�W�&��� �4�"� �"�8584�"�8591�4c?�l># �T T"U0UD6Shv�NsSSS5 $N
!,(df   T$=f7frrr{rs  ���rfr r!s/����$�/7��/H��/H�$H�%�W�$H�%�W�&��r"c�P>�T T"U0UD6sSSS5 $!,(df   T$=frrr{rs  ���rfr r!s"���$�#+�T�#<�V�#<�%�W�W�&��s��860%)rr�rvrrr��update_wrapper)rdrr r�Catcherr/s ` @��rfr��&Logger.catch.<locals>.Catcher.__call__�s�����8�$�$�#�;�=E�=N�=N�O���861"�$�-��&�x�0�0�'�'�862)��2�2�'�'�'�863�(�(���A�$�$rprN)	rvrwrxryrgrrr�rz)	r&r/r�rrerrr�r�s	���������rfr&r�s"���
6�
�$
#�$
#�L
%�
%rpr&F)r�rr�
BaseExceptionr�)864rdr�rer�r�rr/rr&rs865 ```````@@rfr��Logger.catchms^����j�I����	�"�"�*�Y�
�*N�*N��:�:�<�	�*�*���L	%�L	%�L	%�\�u�~�rpTr)r�r�r�r�r�r�r��ansic866��U(aSn[R"S[SS9 URSSn	[	UR867XX#XEU/U	Q76$)aParametrize a logging call to slightly change generated log message.868 869Note that it's not possible to chain |opt| calls, the last one takes precedence over the870others as it will "reset" the options to their default values.871 872Parameters873----------874exception : |bool|, |tuple| or |Exception|, optional875    If it does not evaluate as ``False``, the passed exception is formatted and added to the876    log message. It could be an |Exception| object or a ``(type, value, traceback)`` tuple,877    otherwise the exception information is retrieved from |sys.exc_info|.878record : |bool|, optional879    If ``True``, the record dict contextualizing the logging call can be used to format the880    message by using ``{record[key]}`` in the log message.881lazy : |bool|, optional882    If ``True``, the logging call attribute to format the message should be functions which883    will be called only if the level is high enough. This can be used to avoid expensive884    functions if not necessary.885colors : |bool|, optional886    If ``True``, logged message will be colorized according to the markups it possibly887    contains.888raw : |bool|, optional889    If ``True``, the formatting of each sink will be bypassed and the message will be sent890    as is.891capture : |bool|, optional892    If ``False``, the ``**kwargs`` of logged message will not automatically populate893    the ``extra`` dict (although they are still used for formatting).894depth : |int|, optional895    Specify which stacktrace should be used to contextualize the logged message. This is896    useful while using the logger from inside a wrapped function to retrieve worthwhile897    information.898ansi : |bool|, optional899    Deprecated since version 0.4.1: the ``ansi`` parameter will be removed in Loguru 1.0.0,900    it is replaced by ``colors`` which is a more appropriate name.901 902Returns903-------904:class:`~Logger`905    A logger wrapping the core logger, but transforming logged message adequately before906    sending.907 908Examples909--------910>>> try:911...     1 / 0912... except ZeroDivisionError:913...    logger.opt(exception=True).debug("Exception logged with debug level:")914...915[18:10:02] DEBUG in '<module>' - Exception logged with debug level:916Traceback (most recent call last, catch point marked):917> File "<stdin>", line 2, in <module>918ZeroDivisionError: division by zero919 920>>> logger.opt(record=True).info("Current line is: {record[line]}")921[18:10:33] INFO in '<module>' - Current line is: 1922 923>>> logger.opt(lazy=True).debug("If sink <= DEBUG: {x}", x=lambda: math.factorial(2**5))924[18:11:19] DEBUG in '<module>' - If sink <= DEBUG: 263130836933693530167218012160000000925 926>>> logger.opt(colors=True).warning("We got a <red>BIG</red> problem")927[18:11:30] WARNING in '<module>' - We got a BIG problem928 929>>> logger.opt(raw=True).debug("No formatting\n")930No formatting931 932>>> logger.opt(capture=False).info("Displayed but not captured: {value}", value=123)933[18:11:41] Displayed but not captured: 123934 935>>> def wrapped():936...     logger.opt(depth=1).info("Get parent context")937...938>>> def func():939...     wrapped()940...941>>> func()942[18:11:54] DEBUG in 'func' - Get parent context943Tz?The 'ansi' parameter is deprecated, please use 'colors' instead���944stacklevel�����N)�warnings�warn�DeprecationWarningr�r}r�)945rdr�r�r�r�r�r�r�r*rs946          rf�opt�947Logger.optsQ��r��F��M�M�Q�"��
��}�}�R�S�!���d�j�j�)�F�&�w�^�Y]�^�^rpc�V�URGtp#[UR/UQ0UEUEP76$)a^Bind attributes to the ``extra`` dict of each logged message record.948 949This is used to add custom context to each logging call.950 951Parameters952----------953**kwargs954    Mapping between keys and values that will be added to the ``extra`` dict.955 956Returns957-------958:class:`~Logger`959    A logger wrapping the core logger, but which sends record with the customized ``extra``960    dict.961 962Examples963--------964>>> logger.add(sys.stderr, format="{extra[ip]} - {message}")965>>> class Server:966...     def __init__(self, ip):967...         self.ip = ip968...         self.logger = logger.bind(ip=ip)969...     def call(self, message):970...         self.logger.info(message)971...972>>> instance_1 = Server("192.168.0.200")973>>> instance_2 = Server("127.0.0.1")974>>> instance_1.call("First instance")975192.168.0.200 - First instance976>>> instance_2.call("Second instance")977127.0.0.1 - Second instance978�r�r}r�)�
_Logger__selfr�rrYs    rf�bind�Logger.bind}s4��B!�/�/����f�l�l�B�W�B�.A��.A�&�.A�B�Brpc+��# �URR 0[R5EUEn[R	U5nSSS5 Sv� URR [RW5 SSS5 g!,(df   NH=f!,(df   g=f!URR [RW5 SSS5 f!,(df   f=f=f7f)aBind attributes to the context-local ``extra`` dict while inside the ``with`` block.979 980Contrary to |bind| there is no ``logger`` returned, the ``extra`` dict is modified in-place981and updated globally. Most importantly, it uses |contextvars| which means that982contextualized values are unique to each threads and asynchronous tasks.983 984The ``extra`` dict will retrieve its initial state once the context manager is exited.985 986Parameters987----------988**kwargs989    Mapping between keys and values that will be added to the context-local ``extra`` dict.990 991Returns992-------993:term:`context manager` / :term:`decorator`994    A context manager (usable as a decorator too) that will bind the attributes once entered995    and restore the initial state of the ``extra`` dict while exited.996 997Examples998--------999>>> logger.add(sys.stderr, format="{message} | {extra}")100011001>>> def task():1002...     logger.info("Processing!")1003...1004>>> with logger.contextualize(task_id=123):1005...     task()1006...1007Processing! | {'task_id': 123}1008>>> logger.info("Done.")1009Done. | {}1010N)r�rcr��get�set�reset)r7r��new_context�tokens    rf�
contextualize�Logger.contextualize�s����F�\�\�
�
�5�W�[�[�]�5�f�5�K��K�K��,�E��	%�����"�"��
�
�e�$�#�"��
��#�"�����"�"��
�
�e�$�#�"�"�sd�C5�.B	�C5�B+�C5�*B�	C5�	1011B�C5�1012B(�$C5�+C2�C!�	C2�!1013C/�+C2�2C5c�\�URGtp#n[UR/UQ/UQUPPUP76$)atAttach a function to modify the record dict created by each logging call.1014 1015The ``patcher`` may be used to update the record on-the-fly before it's propagated to the1016handlers. This allows the "extra" dict to be populated with dynamic values and also permits1017advanced modifications of the record emitted while logging a message. The function is called1018once before sending the log message to the different handlers.1019 1020It is recommended to apply modification on the ``record["extra"]`` dict rather than on the1021``record`` dict itself, as some values are used internally by `Loguru`, and modify them may1022produce unexpected results.1023 1024The logger can be patched multiple times. In this case, the functions are called in the1025same order as they are added.1026 1027Parameters1028----------1029patcher: |callable|_1030    The function to which the record dict will be passed as the sole argument. This function1031    is in charge of updating the record in-place, the function does not need to return any1032    value, the modified record object will be re-used.1033 1034Returns1035-------1036:class:`~Logger`1037    A logger wrapping the core logger, but which records are passed through the ``patcher``1038    function before being sent to the added handlers.1039 1040Examples1041--------1042>>> logger.add(sys.stderr, format="{extra[utc]} {message}")1043>>> logger = logger.patch(lambda record: record["extra"].update(utc=datetime.utcnow())1044>>> logger.info("That's way, you can log messages with time displayed in UTC")1045 1046>>> def wrapper(func):1047...     @functools.wraps(func)1048...     def wrapped(*args, **kwargs):1049...         logger.patch(lambda r: r.update(function=func.__name__)).info("Wrapped!")1050...         return func(*args, **kwargs)1051...     return wrapped1052 1053>>> def recv_record_from_network(pipe):1054...     record = pickle.loads(pipe.read())1055...     level, message = record["level"], record["message"]1056...     logger.patch(lambda r: r.update(record)).log(level, message)1057r6)rdrZrr�rYs     rf�patch�Logger.patch�s<��\%)�M�M�!��E��d�j�j�H�7�H�,@�h�,@��,@�H�%�H�Hrpc��[U[5(d![S[U5R-5eX#s=La	Us=LacO OUR1058RU$XR1059R;aUc[SU-5eSupVO%Ub[SU-5eURU5uprpVUcUnUcUn[U[5(d![S[U5R-5eUS:a[S	U-5e[R"U5n[XX45n	UR1060R X�R1061RU'X�R1062RU'XX$4UR1063R U'UR1064R"R%5Hn1065U1066R'U5 M SSS5 U	$![a [SU-5Sef=f!,(df   U	$=f)1067uAdd, update or retrieve a logging level.1068 1069Logging levels are defined by their ``name`` to which a severity ``no``, an ansi ``color``1070tag and an ``icon`` are associated and possibly modified at run-time. To |log| to a custom1071level, you should necessarily use its name, the severity number is not linked back to levels1072name (this implies that several levels can share the same severity).1073 1074To add a new level, its ``name`` and its ``no`` are required. A ``color`` and an ``icon``1075can also be specified or will be empty by default.1076 1077To update an existing level, pass its ``name`` with the parameters to be changed. It is not1078possible to modify the ``no`` of a level once it has been added.1079 1080To retrieve level information, the ``name`` solely suffices.1081 1082Parameters1083----------1084name : |str|1085    The name of the logging level.1086no : |int|1087    The severity of the level to be added or updated.1088color : |str|1089    The color markup of the level to be added or updated.1090icon : |str|1091    The icon of the level to be added or updated.1092 1093Returns1094-------1095``Level``1096    A |namedtuple| containing information about the level.1097 1098Raises1099------1100ValueError1101    If attempting to access a level with a ``name`` that is not registered, or if trying to1102    change the severity ``no`` of an existing level.1103 1104Examples1105--------1106>>> level = logger.level("ERROR")1107>>> print(level)1108Level(name='ERROR', no=40, color='<red><bold>', icon='❌')1109>>> logger.add(sys.stderr, format="{level.no} {level.icon} {message}")111011111>>> logger.level("CUSTOM", no=15, color="<blue>", icon="@")1112Level(name='CUSTOM', no=15, color='<blue>', icon='@')1113>>> logger.log("CUSTOM", "Logging...")111415 @ Logging...1115>>> logger.level("WARNING", icon=r"/!\\")1116Level(name='WARNING', no=30, color='<yellow><bold>', icon='/!\\\\')1117>>> logger.warning("Updated!")111830 /!\\ Updated!1119z4Invalid level name, it should be a string, not: '%s'N�Level '%s' does not existzILevel '%s' does not exist, you have to create it by specifying a level no)r;� 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)r�r�r�r�rvr�rR�KeyErrorr�rer�rrTr(rcrUrVrXr��
update_format)rdr)r*r+r,�	old_color�old_iconrr*rer�s           rfre�Logger.level�s���l�$��$�$��F��d��I\�I\�\��
��&�$�&�&�
O��z�z�(�(��.�.��z�z�(�(�(��z� �_�����#*��I�x�
�^��Z�]a�a�b�b�)-���D�)9�&�A�9��=��E��<��D��"�c�"�"��F��b��IZ�IZ�Z��
���6��Y�\^�^�_�_�����&���d��,��
�Z�Z�_�_�&+�J�J���d�#�15�J�J�(�(��.�.2�"�-C�D�J�J�$�$�T�*��:�:�.�.�5�5�7���%�%�d�+�8�	����O�
O� �!<�t�!C�D�$�N�
O��@�_���s�	G�BG1�G.�11120Hc�(�URUS5 g)a�Disable logging of messages coming from ``name`` module and its children.1121 1122Developers of library using `Loguru` should absolutely disable it to avoid disrupting1123users with unrelated logs messages.1124 1125Note that in some rare circumstances, it is not possible for `Loguru` to1126determine the module's ``__name__`` value. In such situation, ``record["name"]`` will be1127equal to ``None``, this is why ``None`` is also a valid argument.1128 1129Parameters1130----------1131name : |str| or ``None``1132    The name of the parent module to disable.1133 1134Examples1135--------1136>>> logger.info("Allowed message by default")1137[22:21:55] Allowed message by default1138>>> logger.disable("my_library")1139>>> logger.info("While publishing a library, don't forget to disable logging")1140FN��_change_activation�rdr)s  rf�disable�Logger.disablefs��,	
����e�,rpc�(�URUS5 g)azEnable logging of messages coming from ``name`` module and its children.1141 1142Logging is generally disabled by imported library using `Loguru`, hence this function1143allows users to receive these messages anyway.1144 1145To enable all logs regardless of the module they are coming from, an empty string ``""`` can1146be passed.1147 1148Parameters1149----------1150name : |str| or ``None``1151    The name of the parent module to re-allow.1152 1153Examples1154--------1155>>> logger.disable("__main__")1156>>> logger.info("Disabled, so nothing is logged.")1157>>> logger.enable("__main__")1158>>> logger.info("Re-enabled, messages are logged.")1159[22:46:12] Re-enabled, messages are logged.1160TNrNrPs  rf�enable�
Logger.enable~s��,	
����d�+rp)rXrRrYrZ�1161activationc��UbUR5 O/nUbUHnUR"S0UD6 M Ub/URR X@RlSSS5 UbhURR URR1162R
5 URR1163RU5 SSS5 Ub6UH0upxU(aURU5 MURU5 M2 UVs/sHo`R"S0UD6PM sn$!,(df   N�=f!,(df   Nz=fs snf)uEConfigure the core logger.1164 1165It should be noted that ``extra`` values set using this function are available across all1166modules, so this is the best way to set overall default values.1167 1168To load the configuration directly from a file, such as JSON or YAML, it is also possible to1169use the |loguru-config|_ library developed by `@erezinman`_.1170 1171Parameters1172----------1173handlers : |list| of |dict|, optional1174    A list of each handler to be added. The list should contain dicts of params passed to1175    the |add| function as keyword arguments. If not ``None``, all previously added1176    handlers are first removed.1177levels : |list| of |dict|, optional1178    A list of each level to be added or updated. The list should contain dicts of params1179    passed to the |level| function as keyword arguments. This will never remove previously1180    created levels.1181extra : |dict|, optional1182    A dict containing additional parameters bound to the core logger, useful to share1183    common properties if you call |bind| in several of your files modules. If not ``None``,1184    this will remove previously configured ``extra`` dict.1185patcher : |callable|_, optional1186    A function that will be applied to the record dict of each logged messages across all1187    modules using the logger. It should modify the dict in-place without returning anything.1188    The function is executed prior to the one possibly added by the |patch| method. If not1189    ``None``, this will replace previously configured ``patcher`` function.1190activation : |list| of |tuple|, optional1191    A list of ``(name, state)`` tuples which denotes which loggers should be enabled (if1192    ``state`` is ``True``) or disabled (if ``state`` is ``False``). The calls to |enable|1193    and |disable| are made accordingly to the list order. This will not modify previously1194    activated loggers, so if you need a fresh start prepend your list with ``("", False)``1195    or ``("", True)``.1196 1197Returns1198-------1199:class:`list` of :class:`int`1200    A list containing the identifiers of added sinks (if any).

Showing the first 1,200 of 1355 lines. Download the file for the rest.

codekingpro/portable-devtools · Team Ai