r"""Add a handler sending log messages to a sink adequately configured.

        Parameters
        ----------
        sink : |file-like object|_, |str|, |Path|, |function|_, |Handler| or |class|_
            An object in charge of receiving formatted logging messages and propagating them to an
            appropriate endpoint.
        level : |int| or |str|, optional
            The minimum severity level from which logged messages should be sent to the sink.
        format : |str| or |function|_, optional
            The template used to format logged messages before being sent to the sink.
        filter : |function|_ or |str|, optional
            A directive used to optionally filter out logged messages before they are sent to the
            sink.
        colorize : |bool|, optional
            Whether or not the color markups contained in the formatted message should be converted
            to ansi codes for terminal coloration, or stripped otherwise. If ``None``, the choice
            is automatically made based on the sink being a tty or not.
        serialize : |bool|, optional
            Whether or not the logged message and its records should be first converted to a JSON
            string before being sent to the sink.
        backtrace : |bool|, optional
            Whether or not the exception trace formatted should be extended upward, beyond the
            catching point, to show the full stacktrace which generated the error.
        diagnose : |bool|, optional
            Whether or not the exception trace should display the variables values to eases the
            debugging. This should be set to ``False`` in production to avoid leaking sensitive
            data.
        enqueue : |bool|, optional
            Whether or not the messages to be logged should first pass through a multiprocess-safe
            queue before reaching the sink. This is useful while logging to a file through multiple
            processes.
        catch : |bool|, optional
            Whether or not errors occurring while sink handles logs messages should be caught or
            not. If ``True``, an exception message is displayed on |sys.stderr| but the exception is
            not propagated to the caller, preventing your app to crash.
        **kwargs
            Additional parameters that will be passed to the sink while creating it or while
            logging messages (the exact behavior depends on the sink type).


        If and only if the sink is a file, the following parameters apply:

        Parameters
        ----------
        rotation : |str|, |int|, |time|, |timedelta| or |function|_, optional
            A condition indicating whenever the current logged file should be closed and a new one
            started.
        retention : |str|, |int|, |timedelta| or |function|_, optional
            A directive filtering old files that should be removed during rotation or end of
            program.
        compression : |str| or |function|_, optional
            A compression or archive format to which log files should be converted at closure.
        delay : |bool|, optional
            Whether or not the file should be created as soon as the sink is configured, or delayed
            until first logged message. It defaults to ``False``.
        mode : |str|, optional
            The opening mode as for built-in |open| function. It defaults to ``"a"`` (open the
            file in appending mode).
        buffering : |int|, optional
            The buffering policy as for built-in |open| function. It defaults to ``1`` (line
            buffered file).
        encoding : |str|, optional
            The file encoding as for built-in |open| function. If ``None``, it defaults to
            ``locale.getpreferredencoding()``.
        **kwargs
            Others parameters are passed to the built-in |open| function.

        Returns
        -------
        :class:`int`
            An identifier associated with the added sink and which should be used to
            |remove| it.

        Notes
        -----
        Extended summary follows.

        .. _sink:

        .. rubric:: The sink parameter

        The ``sink`` handles incoming log messages and proceed to their writing somewhere and
        somehow. A sink can take many forms:

        - A |file-like object|_ like ``sys.stderr`` or ``open("somefile.log", "w")``. Anything with
          a ``.write()`` method is considered as a file-like object. If it has a ``.flush()``
          method, it will be automatically called after each logged message. If it has a ``.stop()``
          method, it will be automatically called at sink termination.
        - A file path as |str| or |Path|. It can be parametrized with some additional parameters,
          see below.
        - A simple |function|_ like ``lambda msg: print(msg)``. This allows for logging
          procedure entirely defined by user preferences and needs.
        - A built-in |Handler| like ``logging.StreamHandler``. In such a case, the `Loguru` records
          are automatically converted to the structure expected by the |logging| module.
        - A |class|_ object that will be used to instantiate the sink using ``**kwargs`` attributes
          passed. Hence the class should instantiate objects which are therefore valid sinks.

        Note that you should avoid using  the ``logger`` inside any of your sinks as this would
        result in infinite recursion or dead lock if the module's sink was not explicitly disabled.

        .. _message:

        .. rubric:: The logged message

        The logged message passed to all added sinks is nothing more than a string of the
        formatted log, to which a special attribute is associated: the ``.record`` which is a dict
        containing all contextual information possibly needed (see below).

        Logged messages are formatted according to the ``format`` of the added sink. This format
        is usually a string containing braces fields to display attributes from the record dict.

        If fine-grained control is needed, the ``format`` can also be a function which takes the
        record as parameter and return the format template string. However, note that in such a
        case, you should take care of appending the line ending and exception field to the returned
        format, while ``"\n{exception}"`` is automatically appended for convenience if ``format`` is
        a string.

        The ``filter`` attribute can be used to control which messages are effectively passed to the
        sink and which one are ignored. A function can be used, accepting the record as an
        argument, and returning ``True`` if the message should be logged, ``False`` otherwise. If
        a string is used, only the records with the same ``name`` and its children will be allowed.

        .. _levels:

        .. rubric:: The severity levels

        Each logged message is associated with a severity level. These levels make it possible to
        prioritize messages and to choose the verbosity of the logs according to usages. For
        example, it allows to display some debugging information to a developer, while hiding it to
        the end user running the application.

        The ``level`` attribute of every added sink controls the minimum threshold from which log
        messages are allowed to be emitted. While using the ``logger``, you are in charge of
        configuring the appropriate granularity of your logs. It is possible to add even more custom
        levels by using the |level| method.

        Here are the standard levels with their default severity value, each one is associated with
        a logging method of the same name:

        +----------------------+------------------------+------------------------+
        | Level name           | Severity value         | Logger method          |
        +======================+========================+========================+
        | ``TRACE``            | 5                      | |logger.trace|         |
        +----------------------+------------------------+------------------------+
        | ``DEBUG``            | 10                     | |logger.debug|         |
        +----------------------+------------------------+------------------------+
        | ``INFO``             | 20                     | |logger.info|          |
        +----------------------+------------------------+------------------------+
        | ``SUCCESS``          | 25                     | |logger.success|       |
        +----------------------+------------------------+------------------------+
        | ``WARNING``          | 30                     | |logger.warning|       |
        +----------------------+------------------------+------------------------+
        | ``ERROR``            | 40                     | |logger.error|         |
        +----------------------+------------------------+------------------------+
        | ``CRITICAL``         | 50                     | |logger.critical|      |
        +----------------------+------------------------+------------------------+

        .. _record:

        .. rubric:: The record dict

        The record is just a Python dict, accessible from sinks by ``message.record``. It contains
        all contextual information of the logging call (time, function, file, line, level, etc.).
        Each of its key can be used in the handler's ``format`` so the corresponding value is
        properly displayed in the logged message (eg. ``"{level}"`` -> ``"INFO"``). Some record's
        values are objects with two or more attributes, those can be formatted with ``"{key.attr}"``
        (``"{key}"`` would display one by default). Formatting directives like ``"{key: >3}"`` also
        works and is particularly useful for time (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),        |
        |            | the 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. Those 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 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 ``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 |function|_ which will be called 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 are
        selected according to their basename, if it is the same that the sink file, with possible
        time field being replaced with ``.*``. This parameter accepts:

        - an |int| which indicates the number of log files to keep, while older files are removed.
        - 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 |function|_ which will be called 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 |function|_ which will be called 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.).

        .. _color:

        .. rubric:: The color markups

        To add colors to your logs, you just have to enclose your format string with the appropriate
        tags. This is based on the great `ansimarkup`_ library from `@gvalkov`_. Those tags are
        removed if the sink don't support ansi codes.

        The special tag ``<level>`` (abbreviated with ``<lvl>``) is transformed according to
        the configured color of the logged message level.

        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 (r)                          |
        +------------------------------------+--------------------------------------+
        | Yellow (y)                         | Blink (l)                            |
        +------------------------------------+--------------------------------------+
        |                                    | Hide (h)                             |
        +------------------------------------+--------------------------------------+

        Usage:

        +-----------------+-------------------------------------------------------------------+
        | Description     | Examples                                                          |
        |                 +---------------------------------+---------------------------------+
        |                 | Foreground                      | Background                      |
        +=================+=================================+=================================+
        | Basic colors    | ``<red>``, ``<r>``              | ``<GREEN>``, ``<G>``            |
        +-----------------+---------------------------------+---------------------------------+
        | Light colors    | ``<light-blue>``, ``<le>``      | ``<LIGHT-CYAN>``, ``<LC>``      |
        +-----------------+---------------------------------+---------------------------------+
        | Xterm colors    | ``<fg 86>``, ``<fg 255>``       | ``<bg 42>``, ``<bg 9>``         |
        +-----------------+---------------------------------+---------------------------------+
        | Hex colors      | ``<fg #00005f>``, ``<fg #EE1>`` | ``<bg #AF5FD7>``, ``<bg #fff>`` |
        +-----------------+---------------------------------+---------------------------------+
        | RGB colors      | ``<fg 0,95,0>``                 | ``<bg 72,119,65>``              |
        +-----------------+---------------------------------+---------------------------------+
        | Stylizing       | ``<bold>``, ``<b>`` , ``<underline>``, ``<u>``                    |
        +-----------------+-------------------------------------------------------------------+
        | Shorthand       | ``<red, yellow>``, ``<r, y>``                                     |
        | (FG, BG)        |                                                                   |
        +-----------------+-------------------------------------------------------------------+
        | Shorthand       | ``<bold, cyan, white>``, ``<b,,w>``, ``<b,c,>``                   |
        | (Style, FG, BG) |                                                                   |
        +-----------------+-------------------------------------------------------------------+

        .. _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 "<blue>"``
        or ``setx LOGURU_TRACE_ICON "🚀"``.

        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 my_sink(message):
        ...     record = message.record
        ...     update_db(message, time=record.time, level=record.level)
        ...
        >>> logger.add(my_sink)

        >>> 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, threhold=0.25)
        >>> logger.add(stream_object, level="INFO")
        >>> logger.add(RandomStream, level="DEBUG", seed=34567, threshold=0.5)

def add(
        self,
        sink,
        *,
        level=_defaults.LOGURU_LEVEL,
        format=_defaults.LOGURU_FORMAT,
        filter=_defaults.LOGURU_FILTER,
        colorize=_defaults.LOGURU_COLORIZE,
        serialize=_defaults.LOGURU_SERIALIZE,
        backtrace=_defaults.LOGURU_BACKTRACE,
        diagnose=_defaults.LOGURU_DIAGNOSE,
        enqueue=_defaults.LOGURU_ENQUEUE,
        catch=_defaults.LOGURU_CATCH,
        **kwargs
    ):
        r"""Add a handler sending log messages to a sink adequately configured.

        Parameters
        ----------
        sink : |file-like object|_, |str|, |Path|, |function|_, |Handler| or |class|_
            An object in charge of receiving formatted logging messages and propagating them to an
            appropriate endpoint.
        level : |int| or |str|, optional
            The minimum severity level from which logged messages should be sent to the sink.
        format : |str| or |function|_, optional
            The template used to format logged messages before being sent to the sink.
        filter : |function|_ or |str|, optional
            A directive used to optionally filter out logged messages before they are sent to the
            sink.
        colorize : |bool|, optional
            Whether or not the color markups contained in the formatted message should be converted
            to ansi codes for terminal coloration, or stripped otherwise. If ``None``, the choice
            is automatically made based on the sink being a tty or not.
        serialize : |bool|, optional
            Whether or not the logged message and its records should be first converted to a JSON
            string before being sent to the sink.
        backtrace : |bool|, optional
            Whether or not the exception trace formatted should be extended upward, beyond the
            catching point, to show the full stacktrace which generated the error.
        diagnose : |bool|, optional
            Whether or not the exception trace should display the variables values to eases the
            debugging. This should be set to ``False`` in production to avoid leaking sensitive
            data.
        enqueue : |bool|, optional
            Whether or not the messages to be logged should first pass through a multiprocess-safe
            queue before reaching the sink. This is useful while logging to a file through multiple
            processes.
        catch : |bool|, optional
            Whether or not errors occurring while sink handles logs messages should be caught or
            not. If ``True``, an exception message is displayed on |sys.stderr| but the exception is
            not propagated to the caller, preventing your app to crash.
        **kwargs
            Additional parameters that will be passed to the sink while creating it or while
            logging messages (the exact behavior depends on the sink type).


        If and only if the sink is a file, the following parameters apply:

        Parameters
        ----------
        rotation : |str|, |int|, |time|, |timedelta| or |function|_, optional
            A condition indicating whenever the current logged file should be closed and a new one
            started.
        retention : |str|, |int|, |timedelta| or |function|_, optional
            A directive filtering old files that should be removed during rotation or end of
            program.
        compression : |str| or |function|_, optional
            A compression or archive format to which log files should be converted at closure.
        delay : |bool|, optional
            Whether or not the file should be created as soon as the sink is configured, or delayed
            until first logged message. It defaults to ``False``.
        mode : |str|, optional
            The opening mode as for built-in |open| function. It defaults to ``"a"`` (open the
            file in appending mode).
        buffering : |int|, optional
            The buffering policy as for built-in |open| function. It defaults to ``1`` (line
            buffered file).
        encoding : |str|, optional
            The file encoding as for built-in |open| function. If ``None``, it defaults to
            ``locale.getpreferredencoding()``.
        **kwargs
            Others parameters are passed to the built-in |open| function.

        Returns
        -------
        :class:`int`
            An identifier associated with the added sink and which should be used to
            |remove| it.

        Notes
        -----
        Extended summary follows.

        .. _sink:

        .. rubric:: The sink parameter

        The ``sink`` handles incoming log messages and proceed to their writing somewhere and
        somehow. A sink can take many forms:

        - A |file-like object|_ like ``sys.stderr`` or ``open("somefile.log", "w")``. Anything with
          a ``.write()`` method is considered as a file-like object. If it has a ``.flush()``
          method, it will be automatically called after each logged message. If it has a ``.stop()``
          method, it will be automatically called at sink termination.
        - A file path as |str| or |Path|. It can be parametrized with some additional parameters,
          see below.
        - A simple |function|_ like ``lambda msg: print(msg)``. This allows for logging
          procedure entirely defined by user preferences and needs.
        - A built-in |Handler| like ``logging.StreamHandler``. In such a case, the `Loguru` records
          are automatically converted to the structure expected by the |logging| module.
        - A |class|_ object that will be used to instantiate the sink using ``**kwargs`` attributes
          passed. Hence the class should instantiate objects which are therefore valid sinks.

        Note that you should avoid using  the ``logger`` inside any of your sinks as this would
        result in infinite recursion or dead lock if the module's sink was not explicitly disabled.

        .. _message:

        .. rubric:: The logged message

        The logged message passed to all added sinks is nothing more than a string of the
        formatted log, to which a special attribute is associated: the ``.record`` which is a dict
        containing all contextual information possibly needed (see below).

        Logged messages are formatted according to the ``format`` of the added sink. This format
        is usually a string containing braces fields to display attributes from the record dict.

        If fine-grained control is needed, the ``format`` can also be a function which takes the
        record as parameter and return the format template string. However, note that in such a
        case, you should take care of appending the line ending and exception field to the returned
        format, while ``"\n{exception}"`` is automatically appended for convenience if ``format`` is
        a string.

        The ``filter`` attribute can be used to control which messages are effectively passed to the
        sink and which one are ignored. A function can be used, accepting the record as an
        argument, and returning ``True`` if the message should be logged, ``False`` otherwise. If
        a string is used, only the records with the same ``name`` and its children will be allowed.

        .. _levels:

        .. rubric:: The severity levels

        Each logged message is associated with a severity level. These levels make it possible to
        prioritize messages and to choose the verbosity of the logs according to usages. For
        example, it allows to display some debugging information to a developer, while hiding it to
        the end user running the application.

        The ``level`` attribute of every added sink controls the minimum threshold from which log
        messages are allowed to be emitted. While using the ``logger``, you are in charge of
        configuring the appropriate granularity of your logs. It is possible to add even more custom
        levels by using the |level| method.

        Here are the standard levels with their default severity value, each one is associated with
        a logging method of the same name:

        +----------------------+------------------------+------------------------+
        | Level name           | Severity value         | Logger method          |
        +======================+========================+========================+
        | ``TRACE``            | 5                      | |logger.trace|         |
        +----------------------+------------------------+------------------------+
        | ``DEBUG``            | 10                     | |logger.debug|         |
        +----------------------+------------------------+------------------------+
        | ``INFO``             | 20                     | |logger.info|          |
        +----------------------+------------------------+------------------------+
        | ``SUCCESS``          | 25                     | |logger.success|       |
        +----------------------+------------------------+------------------------+
        | ``WARNING``          | 30                     | |logger.warning|       |
        +----------------------+------------------------+------------------------+
        | ``ERROR``            | 40                     | |logger.error|         |
        +----------------------+------------------------+------------------------+
        | ``CRITICAL``         | 50                     | |logger.critical|      |
        +----------------------+------------------------+------------------------+

        .. _record:

        .. rubric:: The record dict

        The record is just a Python dict, accessible from sinks by ``message.record``. It contains
        all contextual information of the logging call (time, function, file, line, level, etc.).
        Each of its key can be used in the handler's ``format`` so the corresponding value is
        properly displayed in the logged message (eg. ``"{level}"`` -> ``"INFO"``). Some record's
        values are objects with two or more attributes, those can be formatted with ``"{key.attr}"``
        (``"{key}"`` would display one by default). Formatting directives like ``"{key: >3}"`` also
        works and is particularly useful for time (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),        |
        |            | the 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. Those 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 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 ``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 |function|_ which will be called 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 are
        selected according to their basename, if it is the same that the sink file, with possible
        time field being replaced with ``.*``. This parameter accepts:

        - an |int| which indicates the number of log files to keep, while older files are removed.
        - 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 |function|_ which will be called 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 |function|_ which will be called 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.).

        .. _color:

        .. rubric:: The color markups

        To add colors to your logs, you just have to enclose your format string with the appropriate
        tags. This is based on the great `ansimarkup`_ library from `@gvalkov`_. Those tags are
        removed if the sink don't support ansi codes.

        The special tag ``<level>`` (abbreviated with ``<lvl>``) is transformed according to
        the configured color of the logged message level.

        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 (r)                          |
        +------------------------------------+--------------------------------------+
        | Yellow (y)                         | Blink (l)                            |
        +------------------------------------+--------------------------------------+
        |                                    | Hide (h)                             |
        +------------------------------------+--------------------------------------+

        Usage:

        +-----------------+-------------------------------------------------------------------+
        | Description     | Examples                                                          |
        |                 +---------------------------------+---------------------------------+
        |                 | Foreground                      | Background                      |
        +=================+=================================+=================================+
        | Basic colors    | ``<red>``, ``<r>``              | ``<GREEN>``, ``<G>``            |
        +-----------------+---------------------------------+---------------------------------+
        | Light colors    | ``<light-blue>``, ``<le>``      | ``<LIGHT-CYAN>``, ``<LC>``      |
        +-----------------+---------------------------------+---------------------------------+
        | Xterm colors    | ``<fg 86>``, ``<fg 255>``       | ``<bg 42>``, ``<bg 9>``         |
        +-----------------+---------------------------------+---------------------------------+
        | Hex colors      | ``<fg #00005f>``, ``<fg #EE1>`` | ``<bg #AF5FD7>``, ``<bg #fff>`` |
        +-----------------+---------------------------------+---------------------------------+
        | RGB colors      | ``<fg 0,95,0>``                 | ``<bg 72,119,65>``              |
        +-----------------+---------------------------------+---------------------------------+
        | Stylizing       | ``<bold>``, ``<b>`` , ``<underline>``, ``<u>``                    |
        +-----------------+-------------------------------------------------------------------+
        | Shorthand       | ``<red, yellow>``, ``<r, y>``                                     |
        | (FG, BG)        |                                                                   |
        +-----------------+-------------------------------------------------------------------+
        | Shorthand       | ``<bold, cyan, white>``, ``<b,,w>``, ``<b,c,>``                   |
        | (Style, FG, BG) |                                                                   |
        +-----------------+-------------------------------------------------------------------+

        .. _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 "<blue>"``
        or ``setx LOGURU_TRACE_ICON "🚀"``.

        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 my_sink(message):
        ...     record = message.record
        ...     update_db(message, time=record.time, level=record.level)
        ...
        >>> logger.add(my_sink)

        >>> 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, threhold=0.25)
        >>> logger.add(stream_object, level="INFO")
        >>> logger.add(RandomStream, level="DEBUG", seed=34567, threshold=0.5)
        """
        if colorize is None and serialize:
            colorize = False

        if isclass(sink):
            sink = sink(**kwargs)
            return self.add(
                sink,
                level=level,
                format=format,
                filter=filter,
                colorize=colorize,
                serialize=serialize,
                backtrace=backtrace,
                diagnose=diagnose,
                enqueue=enqueue,
                catch=catch,
            )
        elif isinstance(sink, (str, PathLike)):
            path = sink
            sink = FileSink(path, **kwargs)
            return self.add(
                sink,
                level=level,
                format=format,
                filter=filter,
                colorize=colorize,
                serialize=serialize,
                backtrace=backtrace,
                diagnose=diagnose,
                enqueue=enqueue,
                catch=catch,
            )
        elif hasattr(sink, "write") and callable(sink.write):
            if colorize is False:
                stream = sink
            else:
                try:
                    converter = AnsiToWin32(sink, convert=None, strip=False)
                    isatty = converter.stream.isatty()
                except Exception:
                    if colorize is None:
                        colorize = False
                    stream = sink
                else:
                    if colorize is None:
                        colorize = isatty
                    if converter.should_wrap() and colorize:
                        stream = converter.stream
                    else:
                        stream = sink

            stream_write = stream.write
            if kwargs:

                def write(m):
                    return stream_write(m, **kwargs)

            else:
                write = stream_write

            if hasattr(stream, "flush") and callable(stream.flush):
                stream_flush = stream.flush

                def writer(m):
                    write(m)
                    stream_flush()

            else:
                writer = write

            if hasattr(stream, "stop") and callable(stream.stop):
                stopper = stream.stop
            else:

                def stopper():
                    return None

        elif isinstance(sink, logging.Handler):

            def writer(m):
                message = str(m)
                r = m.record
                exc = r["exception"]
                if not is_formatter_dynamic:
                    message = message[:-1]
                record = logging.root.makeRecord(
                    r["name"],
                    r["level"].no,
                    r["file"].path,
                    r["line"],
                    message,
                    (),
                    (exc.type, exc.value, exc.traceback) if exc else None,
                    r["function"],
                    r["extra"],
                    **kwargs
                )
                if exc:
                    record.exc_text = "\n"
                sink.handle(record)

            stopper = sink.close
            if colorize is None:
                colorize = False
        elif callable(sink):
            if kwargs:

                def writer(m):
                    return sink(m, **kwargs)

            else:
                writer = sink

            def stopper():
                return None

            if colorize is None:
                colorize = False
        else:
            raise ValueError("Cannot log to objects of type '%s'." % type(sink).__name__)

        if filter is None or filter == "":
            filter_func = None
        elif isinstance(filter, str):
            parent = filter + "."
            length = len(parent)

            def filter_func(r):
                return (r["name"] + ".")[:length] == parent

        elif callable(filter):
            filter_func = filter
        else:
            raise ValueError(
                "Invalid filter, it should be a function or a string, not: '%s'"
                % type(filter).__name__
            )

        if isinstance(level, str):
            levelno = self.level(level).no
        elif isinstance(level, int):
            levelno = level
        else:
            raise ValueError(
                "Invalid level, it should be an integer or a string, not: '%s'"
                % type(level).__name__
            )

        if levelno < 0:
            raise ValueError(
                "Invalid level value, it should be a positive integer, not: %d" % levelno
            )

        if isinstance(format, str):
            formatter = format + "\n{exception}"
            is_formatter_dynamic = False
        elif callable(format):
            formatter = format
            is_formatter_dynamic = True
        else:
            raise ValueError(
                "Invalid format, it should be a string or a function, not: '%s'"
                % type(format).__name__
            )

        try:
            encoding = sink.encoding
        except AttributeError:
            encoding = None

        if not encoding:
            encoding = "ascii"

        with self._lock:
            handler_id = next(self._handlers_count)
            colors = [lvl.color for lvl in self._levels.values()] + [""]

            exception_formatter = ExceptionFormatter(
                colorize=colorize,
                encoding=encoding,
                diagnose=diagnose,
                backtrace=backtrace,
                hidden_frames_filename=self.catch.__code__.co_filename,
            )

            handler = Handler(
                writer=writer,
                stopper=stopper,
                levelno=levelno,
                formatter=formatter,
                is_formatter_dynamic=is_formatter_dynamic,
                filter_=filter_func,
                colorize=colorize,
                serialize=serialize,
                catch=catch,
                enqueue=enqueue,
                id_=handler_id,
                exception_formatter=exception_formatter,
                colors=colors,
            )

            handlers = self._handlers.copy()
            handlers[handler_id] = handler

            self.__class__._min_level = min(self.__class__._min_level, levelno)
            self.__class__._handlers = handlers

        return handler_id