loguru


Nameloguru JSON
Version 0.7.2 PyPI version JSON
download
home_pagehttps://github.com/Delgan/loguru
SummaryPython logging made (stupidly) simple
upload_time2023-09-11 15:24:37
maintainer
docs_urlNone
authorDelgan
requires_python>=3.5
licenseMIT license
keywords loguru logging logger log
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            .. image:: https://raw.githubusercontent.com/Delgan/loguru/master/docs/_static/img/logo.png
   :target: https://github.com/Delgan/loguru
   :align: center
   :alt: Loguru logo

.. image:: https://raw.githubusercontent.com/Delgan/loguru/master/docs/_static/img/demo.gif
   :target: https://github.com/Delgan/loguru
   :align: center
   :alt: Loguru demo

=========

.. image:: https://img.shields.io/pypi/v/loguru.svg
    :target: https://pypi.python.org/pypi/loguru
    :alt: Pypi version

.. image:: https://img.shields.io/badge/python-3.5%2B%20%7C%20PyPy-blue.svg
    :target: https://github.com/Delgan/loguru/blob/master/.travis.yml
    :alt: Python versions

.. image:: https://img.shields.io/readthedocs/loguru.svg
    :target: https://loguru.readthedocs.io/en/stable/index.html
    :alt: Docs

.. image:: https://img.shields.io/github/actions/workflow/status/Delgan/loguru/tests.yml?branch=master
    :target: https://github.com/Delgan/loguru/actions/workflows/tests.yml?query=branch:master
    :alt: Build status

.. image:: https://img.shields.io/codecov/c/github/delgan/loguru/master.svg
    :target: https://codecov.io/gh/delgan/loguru/branch/master
    :alt: Coverage

.. image:: https://img.shields.io/codacy/grade/be7337df3c0d40d1929eb7f79b1671a6.svg
    :target: https://app.codacy.com/gh/Delgan/loguru/dashboard
    :alt: Code quality

.. image:: https://img.shields.io/github/license/delgan/loguru.svg
    :target: https://github.com/Delgan/loguru/blob/master/LICENSE
    :alt: License

**Loguru** is a library which aims to bring enjoyable logging in Python.

Did you ever feel lazy about configuring a logger and used ``print()`` instead?... I did, yet logging is fundamental to every application and eases the process of debugging. Using **Loguru** you have no excuse not to use logging from the start, this is as simple as ``from loguru import logger``.

Also, this library is intended to make Python logging less painful by adding a bunch of useful functionalities that solve caveats of the standard loggers. Using logs in your application should be an automatism, **Loguru** tries to make it both pleasant and powerful.


.. end-of-readme-intro

Installation
------------

::

    pip install loguru


Features
--------

* `Ready to use out of the box without boilerplate`_
* `No Handler, no Formatter, no Filter: one function to rule them all`_
* `Easier file logging with rotation / retention / compression`_
* `Modern string formatting using braces style`_
* `Exceptions catching within threads or main`_
* `Pretty logging with colors`_
* `Asynchronous, Thread-safe, Multiprocess-safe`_
* `Fully descriptive exceptions`_
* `Structured logging as needed`_
* `Lazy evaluation of expensive functions`_
* `Customizable levels`_
* `Better datetime handling`_
* `Suitable for scripts and libraries`_
* `Entirely compatible with standard logging`_
* `Personalizable defaults through environment variables`_
* `Convenient parser`_
* `Exhaustive notifier`_
* `10x faster than built-in logging`_

Take the tour
-------------

.. |logger| replace:: ``logger``
.. _logger: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger

.. |add| replace:: ``add()``
.. _add: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.add

.. |remove| replace:: ``remove()``
.. _remove: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.remove

.. |complete| replace:: ``complete()``
.. _complete: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.complete

.. |catch| replace:: ``catch()``
.. _catch: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.catch

.. |bind| replace:: ``bind()``
.. _bind: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.bind

.. |contextualize| replace:: ``contextualize()``
.. _contextualize: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.contextualize

.. |patch| replace:: ``patch()``
.. _patch: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.patch

.. |opt| replace:: ``opt()``
.. _opt: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.opt

.. |trace| replace:: ``trace()``
.. _trace: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.trace

.. |success| replace:: ``success()``
.. _success: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.success

.. |level| replace:: ``level()``
.. _level: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.level

.. |configure| replace:: ``configure()``
.. _configure: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.configure

.. |disable| replace:: ``disable()``
.. _disable: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.disable

.. |enable| replace:: ``enable()``
.. _enable: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.enable

.. |parse| replace:: ``parse()``
.. _parse: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.parse

.. _sinks: https://loguru.readthedocs.io/en/stable/api/logger.html#sink
.. _record dict: https://loguru.readthedocs.io/en/stable/api/logger.html#record
.. _log messages: https://loguru.readthedocs.io/en/stable/api/logger.html#message
.. _easily configurable: https://loguru.readthedocs.io/en/stable/api/logger.html#file
.. _markup tags: https://loguru.readthedocs.io/en/stable/api/logger.html#color
.. _fixes it: https://loguru.readthedocs.io/en/stable/api/logger.html#time
.. _No problem: https://loguru.readthedocs.io/en/stable/api/logger.html#env
.. _logging levels: https://loguru.readthedocs.io/en/stable/api/logger.html#levels

.. |better_exceptions| replace:: ``better_exceptions``
.. _better_exceptions: https://github.com/Qix-/better-exceptions

.. |loguru-config| replace:: ``loguru-config``
.. _loguru-config: https://github.com/erezinman/loguru-config

.. |notifiers| replace:: ``notifiers``
.. _notifiers: https://github.com/notifiers/notifiers

Ready to use out of the box without boilerplate
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The main concept of `Loguru` is that **there is one and only one** |logger|_.

For convenience, it is pre-configured and outputs to ``stderr`` to begin with (but that's entirely configurable).

::

    from loguru import logger

    logger.debug("That's it, beautiful and simple logging!")

The |logger|_ is just an interface which dispatches log messages to configured handlers. Simple, right?


No Handler, no Formatter, no Filter: one function to rule them all
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

How to add a handler? How to set up logs formatting? How to filter messages? How to set level?

One answer: the |add|_ function.

::

    logger.add(sys.stderr, format="{time} {level} {message}", filter="my_module", level="INFO")

This function should be used to register sinks_ which are responsible for managing `log messages`_ contextualized with a `record dict`_. A sink can take many forms: a simple function, a string path, a file-like object, a coroutine function or a built-in Handler.

Note that you may also |remove|_ a previously added handler by using the identifier returned while adding it. This is particularly useful if you want to supersede the default ``stderr`` handler: just call ``logger.remove()`` to make a fresh start.


Easier file logging with rotation / retention / compression
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If you want to send logged messages to a file, you just have to use a string path as the sink. It can be automatically timed too for convenience::

    logger.add("file_{time}.log")

It is also `easily configurable`_ if you need rotating logger, if you want to remove older logs, or if you wish to compress your files at closure.

::

    logger.add("file_1.log", rotation="500 MB")    # Automatically rotate too big file
    logger.add("file_2.log", rotation="12:00")     # New file is created each day at noon
    logger.add("file_3.log", rotation="1 week")    # Once the file is too old, it's rotated

    logger.add("file_X.log", retention="10 days")  # Cleanup after some time

    logger.add("file_Y.log", compression="zip")    # Save some loved space


Modern string formatting using braces style
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

`Loguru` favors the much more elegant and powerful ``{}`` formatting over ``%``, logging functions are actually equivalent to ``str.format()``.

::

    logger.info("If you're using Python {}, prefer {feature} of course!", 3.6, feature="f-strings")


Exceptions catching within threads or main
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Have you ever seen your program crashing unexpectedly without seeing anything in the log file? Did you ever notice that exceptions occurring in threads were not logged? This can be solved using the |catch|_ decorator / context manager which ensures that any error is correctly propagated to the |logger|_.

::

    @logger.catch
    def my_function(x, y, z):
        # An error? It's caught anyway!
        return 1 / (x + y + z)


Pretty logging with colors
^^^^^^^^^^^^^^^^^^^^^^^^^^

`Loguru` automatically adds colors to your logs if your terminal is compatible. You can define your favorite style by using `markup tags`_ in the sink format.

::

    logger.add(sys.stdout, colorize=True, format="<green>{time}</green> <level>{message}</level>")


Asynchronous, Thread-safe, Multiprocess-safe
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

All sinks added to the |logger|_ are thread-safe by default. They are not multiprocess-safe, but you can ``enqueue`` the messages to ensure logs integrity. This same argument can also be used if you want async logging.

::

    logger.add("somefile.log", enqueue=True)

Coroutine functions used as sinks are also supported and should be awaited with |complete|_.


Fully descriptive exceptions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Logging exceptions that occur in your code is important to track bugs, but it's quite useless if you don't know why it failed. `Loguru` helps you identify problems by allowing the entire stack trace to be displayed, including values of variables (thanks |better_exceptions|_ for this!).

The code::

    # Caution, "diagnose=True" is the default and may leak sensitive data in prod
    logger.add("out.log", backtrace=True, diagnose=True)

    def func(a, b):
        return a / b

    def nested(c):
        try:
            func(5, c)
        except ZeroDivisionError:
            logger.exception("What?!")

    nested(0)

Would result in:

.. code-block::

    2018-07-17 01:38:43.975 | ERROR    | __main__:nested:10 - What?!
    Traceback (most recent call last):

      File "test.py", line 12, in <module>
        nested(0)
        └ <function nested at 0x7f5c755322f0>

    > File "test.py", line 8, in nested
        func(5, c)
        │       └ 0
        └ <function func at 0x7f5c79fc2e18>

      File "test.py", line 4, in func
        return a / b
               │   └ 0
               └ 5

    ZeroDivisionError: division by zero

Note that this feature won't work on default Python REPL due to unavailable frame data.

See also: `Security considerations when using Loguru <https://loguru.readthedocs.io/en/stable/resources/recipes.html#security-considerations-when-using-loguru>`_.

Structured logging as needed
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Want your logs to be serialized for easier parsing or to pass them around? Using the ``serialize`` argument, each log message will be converted to a JSON string before being sent to the configured sink.

::

    logger.add(custom_sink_function, serialize=True)

Using |bind|_ you can contextualize your logger messages by modifying the `extra` record attribute.

::

    logger.add("file.log", format="{extra[ip]} {extra[user]} {message}")
    context_logger = logger.bind(ip="192.168.0.1", user="someone")
    context_logger.info("Contextualize your logger easily")
    context_logger.bind(user="someone_else").info("Inline binding of extra attribute")
    context_logger.info("Use kwargs to add context during formatting: {user}", user="anybody")

It is possible to modify a context-local state temporarily with |contextualize|_:

::

    with logger.contextualize(task=task_id):
        do_something()
        logger.info("End of task")

You can also have more fine-grained control over your logs by combining |bind|_ and ``filter``:

::

    logger.add("special.log", filter=lambda record: "special" in record["extra"])
    logger.debug("This message is not logged to the file")
    logger.bind(special=True).info("This message, though, is logged to the file!")

Finally, the |patch|_ method allows dynamic values to be attached to the record dict of each new message:

::

    logger.add(sys.stderr, format="{extra[utc]} {message}")
    logger = logger.patch(lambda record: record["extra"].update(utc=datetime.utcnow()))


Lazy evaluation of expensive functions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Sometime you would like to log verbose information without performance penalty in production, you can use the |opt|_ method to achieve this.

::

    logger.opt(lazy=True).debug("If sink level <= DEBUG: {x}", x=lambda: expensive_function(2**64))

    # By the way, "opt()" serves many usages
    logger.opt(exception=True).info("Error stacktrace added to the log message (tuple accepted too)")
    logger.opt(colors=True).info("Per message <blue>colors</blue>")
    logger.opt(record=True).info("Display values from the record (eg. {record[thread]})")
    logger.opt(raw=True).info("Bypass sink formatting\n")
    logger.opt(depth=1).info("Use parent stack context (useful within wrapped functions)")
    logger.opt(capture=False).info("Keyword arguments not added to {dest} dict", dest="extra")


Customizable levels
^^^^^^^^^^^^^^^^^^^

`Loguru` comes with all standard `logging levels`_ to which |trace|_ and |success|_ are added. Do you need more? Then, just create it by using the |level|_ function.

::

    new_level = logger.level("SNAKY", no=38, color="<yellow>", icon="🐍")

    logger.log("SNAKY", "Here we go!")


Better datetime handling
^^^^^^^^^^^^^^^^^^^^^^^^

The standard logging is bloated with arguments like ``datefmt`` or ``msecs``, ``%(asctime)s`` and ``%(created)s``, naive datetimes without timezone information, not intuitive formatting, etc. `Loguru` `fixes it`_:

::

    logger.add("file.log", format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}")


Suitable for scripts and libraries
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Using the logger in your scripts is easy, and you can |configure|_ it at start. To use `Loguru` from inside a library, remember to never call |add|_ but use |disable|_ instead so logging functions become no-op. If a developer wishes to see your library's logs, they can |enable|_ it again.

::

    # For scripts
    config = {
        "handlers": [
            {"sink": sys.stdout, "format": "{time} - {message}"},
            {"sink": "file.log", "serialize": True},
        ],
        "extra": {"user": "someone"}
    }
    logger.configure(**config)

    # For libraries, should be your library's `__name__`
    logger.disable("my_library")
    logger.info("No matter added sinks, this message is not displayed")

    # In your application, enable the logger in the library
    logger.enable("my_library")
    logger.info("This message however is propagated to the sinks")

For additional convenience, you can also use the |loguru-config|_ library to setup the ``logger`` directly from a configuration file.

Entirely compatible with standard logging
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Wish to use built-in logging ``Handler`` as a `Loguru` sink?

::

    handler = logging.handlers.SysLogHandler(address=('localhost', 514))
    logger.add(handler)

Need to propagate `Loguru` messages to standard `logging`?

::

    class PropagateHandler(logging.Handler):
        def emit(self, record: logging.LogRecord) -> None:
            logging.getLogger(record.name).handle(record)

    logger.add(PropagateHandler(), format="{message}")

Want to intercept standard `logging` messages toward your `Loguru` sinks?

::

    class InterceptHandler(logging.Handler):
        def emit(self, record: logging.LogRecord) -> None:
            # Get corresponding Loguru level if it exists.
            level: str | int
            try:
                level = logger.level(record.levelname).name
            except ValueError:
                level = record.levelno

            # Find caller from where originated the logged message.
            frame, depth = inspect.currentframe(), 0
            while frame and (depth == 0 or frame.f_code.co_filename == logging.__file__):
                frame = frame.f_back
                depth += 1

            logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())

    logging.basicConfig(handlers=[InterceptHandler()], level=0, force=True)


Personalizable defaults through environment variables
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Don't like the default logger formatting? Would prefer another ``DEBUG`` color? `No problem`_::

    # Linux / OSX
    export LOGURU_FORMAT="{time} | <lvl>{message}</lvl>"

    # Windows
    setx LOGURU_DEBUG_COLOR "<green>"


Convenient parser
^^^^^^^^^^^^^^^^^

It is often useful to extract specific information from generated logs, this is why `Loguru` provides a |parse|_ method which helps to deal with logs and regexes.

::

    pattern = r"(?P<time>.*) - (?P<level>[0-9]+) - (?P<message>.*)"  # Regex with named groups
    caster_dict = dict(time=dateutil.parser.parse, level=int)        # Transform matching groups

    for groups in logger.parse("file.log", pattern, cast=caster_dict):
        print("Parsed:", groups)
        # {"level": 30, "message": "Log example", "time": datetime(2018, 12, 09, 11, 23, 55)}


Exhaustive notifier
^^^^^^^^^^^^^^^^^^^

`Loguru` can easily be combined with the great |notifiers|_ library (must be installed separately) to receive an e-mail when your program fail unexpectedly or to send many other kind of notifications.

::

    import notifiers

    params = {
        "username": "you@gmail.com",
        "password": "abc123",
        "to": "dest@gmail.com"
    }

    # Send a single notification
    notifier = notifiers.get_notifier("gmail")
    notifier.notify(message="The application is running!", **params)

    # Be alerted on each error message
    from notifiers.logging import NotificationHandler

    handler = NotificationHandler("gmail", defaults=params)
    logger.add(handler, level="ERROR")


10x faster than built-in logging
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Although logging impact on performances is in most cases negligible, a zero-cost logger would allow to use it anywhere without much concern. In an upcoming release, Loguru's critical functions will be implemented in C for maximum speed.


.. end-of-readme-usage


Documentation
-------------

* `API Reference <https://loguru.readthedocs.io/en/stable/api/logger.html>`_
* `Help & Guides <https://loguru.readthedocs.io/en/stable/resources.html>`_
* `Type hints <https://loguru.readthedocs.io/en/stable/api/type_hints.html>`_
* `Contributing <https://loguru.readthedocs.io/en/stable/project/contributing.html>`_
* `License <https://loguru.readthedocs.io/en/stable/project/license.html>`_
* `Changelog <https://loguru.readthedocs.io/en/stable/project/changelog.html>`_

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Delgan/loguru",
    "name": "loguru",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.5",
    "maintainer_email": "",
    "keywords": "loguru,logging,logger,log",
    "author": "Delgan",
    "author_email": "delgan.py@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/9e/30/d87a423766b24db416a46e9335b9602b054a72b96a88a241f2b09b560fa8/loguru-0.7.2.tar.gz",
    "platform": null,
    "description": ".. image:: https://raw.githubusercontent.com/Delgan/loguru/master/docs/_static/img/logo.png\n   :target: https://github.com/Delgan/loguru\n   :align: center\n   :alt: Loguru logo\n\n.. image:: https://raw.githubusercontent.com/Delgan/loguru/master/docs/_static/img/demo.gif\n   :target: https://github.com/Delgan/loguru\n   :align: center\n   :alt: Loguru demo\n\n=========\n\n.. image:: https://img.shields.io/pypi/v/loguru.svg\n    :target: https://pypi.python.org/pypi/loguru\n    :alt: Pypi version\n\n.. image:: https://img.shields.io/badge/python-3.5%2B%20%7C%20PyPy-blue.svg\n    :target: https://github.com/Delgan/loguru/blob/master/.travis.yml\n    :alt: Python versions\n\n.. image:: https://img.shields.io/readthedocs/loguru.svg\n    :target: https://loguru.readthedocs.io/en/stable/index.html\n    :alt: Docs\n\n.. image:: https://img.shields.io/github/actions/workflow/status/Delgan/loguru/tests.yml?branch=master\n    :target: https://github.com/Delgan/loguru/actions/workflows/tests.yml?query=branch:master\n    :alt: Build status\n\n.. image:: https://img.shields.io/codecov/c/github/delgan/loguru/master.svg\n    :target: https://codecov.io/gh/delgan/loguru/branch/master\n    :alt: Coverage\n\n.. image:: https://img.shields.io/codacy/grade/be7337df3c0d40d1929eb7f79b1671a6.svg\n    :target: https://app.codacy.com/gh/Delgan/loguru/dashboard\n    :alt: Code quality\n\n.. image:: https://img.shields.io/github/license/delgan/loguru.svg\n    :target: https://github.com/Delgan/loguru/blob/master/LICENSE\n    :alt: License\n\n**Loguru** is a library which aims to bring enjoyable logging in Python.\n\nDid you ever feel lazy about configuring a logger and used ``print()`` instead?... I did, yet logging is fundamental to every application and eases the process of debugging. Using **Loguru** you have no excuse not to use logging from the start, this is as simple as ``from loguru import logger``.\n\nAlso, this library is intended to make Python logging less painful by adding a bunch of useful functionalities that solve caveats of the standard loggers. Using logs in your application should be an automatism, **Loguru** tries to make it both pleasant and powerful.\n\n\n.. end-of-readme-intro\n\nInstallation\n------------\n\n::\n\n    pip install loguru\n\n\nFeatures\n--------\n\n* `Ready to use out of the box without boilerplate`_\n* `No Handler, no Formatter, no Filter: one function to rule them all`_\n* `Easier file logging with rotation / retention / compression`_\n* `Modern string formatting using braces style`_\n* `Exceptions catching within threads or main`_\n* `Pretty logging with colors`_\n* `Asynchronous, Thread-safe, Multiprocess-safe`_\n* `Fully descriptive exceptions`_\n* `Structured logging as needed`_\n* `Lazy evaluation of expensive functions`_\n* `Customizable levels`_\n* `Better datetime handling`_\n* `Suitable for scripts and libraries`_\n* `Entirely compatible with standard logging`_\n* `Personalizable defaults through environment variables`_\n* `Convenient parser`_\n* `Exhaustive notifier`_\n* `10x faster than built-in logging`_\n\nTake the tour\n-------------\n\n.. |logger| replace:: ``logger``\n.. _logger: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger\n\n.. |add| replace:: ``add()``\n.. _add: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.add\n\n.. |remove| replace:: ``remove()``\n.. _remove: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.remove\n\n.. |complete| replace:: ``complete()``\n.. _complete: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.complete\n\n.. |catch| replace:: ``catch()``\n.. _catch: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.catch\n\n.. |bind| replace:: ``bind()``\n.. _bind: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.bind\n\n.. |contextualize| replace:: ``contextualize()``\n.. _contextualize: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.contextualize\n\n.. |patch| replace:: ``patch()``\n.. _patch: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.patch\n\n.. |opt| replace:: ``opt()``\n.. _opt: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.opt\n\n.. |trace| replace:: ``trace()``\n.. _trace: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.trace\n\n.. |success| replace:: ``success()``\n.. _success: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.success\n\n.. |level| replace:: ``level()``\n.. _level: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.level\n\n.. |configure| replace:: ``configure()``\n.. _configure: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.configure\n\n.. |disable| replace:: ``disable()``\n.. _disable: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.disable\n\n.. |enable| replace:: ``enable()``\n.. _enable: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.enable\n\n.. |parse| replace:: ``parse()``\n.. _parse: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.parse\n\n.. _sinks: https://loguru.readthedocs.io/en/stable/api/logger.html#sink\n.. _record dict: https://loguru.readthedocs.io/en/stable/api/logger.html#record\n.. _log messages: https://loguru.readthedocs.io/en/stable/api/logger.html#message\n.. _easily configurable: https://loguru.readthedocs.io/en/stable/api/logger.html#file\n.. _markup tags: https://loguru.readthedocs.io/en/stable/api/logger.html#color\n.. _fixes it: https://loguru.readthedocs.io/en/stable/api/logger.html#time\n.. _No problem: https://loguru.readthedocs.io/en/stable/api/logger.html#env\n.. _logging levels: https://loguru.readthedocs.io/en/stable/api/logger.html#levels\n\n.. |better_exceptions| replace:: ``better_exceptions``\n.. _better_exceptions: https://github.com/Qix-/better-exceptions\n\n.. |loguru-config| replace:: ``loguru-config``\n.. _loguru-config: https://github.com/erezinman/loguru-config\n\n.. |notifiers| replace:: ``notifiers``\n.. _notifiers: https://github.com/notifiers/notifiers\n\nReady to use out of the box without boilerplate\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe main concept of `Loguru` is that **there is one and only one** |logger|_.\n\nFor convenience, it is pre-configured and outputs to ``stderr`` to begin with (but that's entirely configurable).\n\n::\n\n    from loguru import logger\n\n    logger.debug(\"That's it, beautiful and simple logging!\")\n\nThe |logger|_ is just an interface which dispatches log messages to configured handlers. Simple, right?\n\n\nNo Handler, no Formatter, no Filter: one function to rule them all\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nHow to add a handler? How to set up logs formatting? How to filter messages? How to set level?\n\nOne answer: the |add|_ function.\n\n::\n\n    logger.add(sys.stderr, format=\"{time} {level} {message}\", filter=\"my_module\", level=\"INFO\")\n\nThis function should be used to register sinks_ which are responsible for managing `log messages`_ contextualized with a `record dict`_. A sink can take many forms: a simple function, a string path, a file-like object, a coroutine function or a built-in Handler.\n\nNote that you may also |remove|_ a previously added handler by using the identifier returned while adding it. This is particularly useful if you want to supersede the default ``stderr`` handler: just call ``logger.remove()`` to make a fresh start.\n\n\nEasier file logging with rotation / retention / compression\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIf you want to send logged messages to a file, you just have to use a string path as the sink. It can be automatically timed too for convenience::\n\n    logger.add(\"file_{time}.log\")\n\nIt is also `easily configurable`_ if you need rotating logger, if you want to remove older logs, or if you wish to compress your files at closure.\n\n::\n\n    logger.add(\"file_1.log\", rotation=\"500 MB\")    # Automatically rotate too big file\n    logger.add(\"file_2.log\", rotation=\"12:00\")     # New file is created each day at noon\n    logger.add(\"file_3.log\", rotation=\"1 week\")    # Once the file is too old, it's rotated\n\n    logger.add(\"file_X.log\", retention=\"10 days\")  # Cleanup after some time\n\n    logger.add(\"file_Y.log\", compression=\"zip\")    # Save some loved space\n\n\nModern string formatting using braces style\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n`Loguru` favors the much more elegant and powerful ``{}`` formatting over ``%``, logging functions are actually equivalent to ``str.format()``.\n\n::\n\n    logger.info(\"If you're using Python {}, prefer {feature} of course!\", 3.6, feature=\"f-strings\")\n\n\nExceptions catching within threads or main\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nHave you ever seen your program crashing unexpectedly without seeing anything in the log file? Did you ever notice that exceptions occurring in threads were not logged? This can be solved using the |catch|_ decorator / context manager which ensures that any error is correctly propagated to the |logger|_.\n\n::\n\n    @logger.catch\n    def my_function(x, y, z):\n        # An error? It's caught anyway!\n        return 1 / (x + y + z)\n\n\nPretty logging with colors\n^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n`Loguru` automatically adds colors to your logs if your terminal is compatible. You can define your favorite style by using `markup tags`_ in the sink format.\n\n::\n\n    logger.add(sys.stdout, colorize=True, format=\"<green>{time}</green> <level>{message}</level>\")\n\n\nAsynchronous, Thread-safe, Multiprocess-safe\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nAll sinks added to the |logger|_ are thread-safe by default. They are not multiprocess-safe, but you can ``enqueue`` the messages to ensure logs integrity. This same argument can also be used if you want async logging.\n\n::\n\n    logger.add(\"somefile.log\", enqueue=True)\n\nCoroutine functions used as sinks are also supported and should be awaited with |complete|_.\n\n\nFully descriptive exceptions\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nLogging exceptions that occur in your code is important to track bugs, but it's quite useless if you don't know why it failed. `Loguru` helps you identify problems by allowing the entire stack trace to be displayed, including values of variables (thanks |better_exceptions|_ for this!).\n\nThe code::\n\n    # Caution, \"diagnose=True\" is the default and may leak sensitive data in prod\n    logger.add(\"out.log\", backtrace=True, diagnose=True)\n\n    def func(a, b):\n        return a / b\n\n    def nested(c):\n        try:\n            func(5, c)\n        except ZeroDivisionError:\n            logger.exception(\"What?!\")\n\n    nested(0)\n\nWould result in:\n\n.. code-block::\n\n    2018-07-17 01:38:43.975 | ERROR    | __main__:nested:10 - What?!\n    Traceback (most recent call last):\n\n      File \"test.py\", line 12, in <module>\n        nested(0)\n        \u2514 <function nested at 0x7f5c755322f0>\n\n    > File \"test.py\", line 8, in nested\n        func(5, c)\n        \u2502       \u2514 0\n        \u2514 <function func at 0x7f5c79fc2e18>\n\n      File \"test.py\", line 4, in func\n        return a / b\n               \u2502   \u2514 0\n               \u2514 5\n\n    ZeroDivisionError: division by zero\n\nNote that this feature won't work on default Python REPL due to unavailable frame data.\n\nSee also: `Security considerations when using Loguru <https://loguru.readthedocs.io/en/stable/resources/recipes.html#security-considerations-when-using-loguru>`_.\n\nStructured logging as needed\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nWant your logs to be serialized for easier parsing or to pass them around? Using the ``serialize`` argument, each log message will be converted to a JSON string before being sent to the configured sink.\n\n::\n\n    logger.add(custom_sink_function, serialize=True)\n\nUsing |bind|_ you can contextualize your logger messages by modifying the `extra` record attribute.\n\n::\n\n    logger.add(\"file.log\", format=\"{extra[ip]} {extra[user]} {message}\")\n    context_logger = logger.bind(ip=\"192.168.0.1\", user=\"someone\")\n    context_logger.info(\"Contextualize your logger easily\")\n    context_logger.bind(user=\"someone_else\").info(\"Inline binding of extra attribute\")\n    context_logger.info(\"Use kwargs to add context during formatting: {user}\", user=\"anybody\")\n\nIt is possible to modify a context-local state temporarily with |contextualize|_:\n\n::\n\n    with logger.contextualize(task=task_id):\n        do_something()\n        logger.info(\"End of task\")\n\nYou can also have more fine-grained control over your logs by combining |bind|_ and ``filter``:\n\n::\n\n    logger.add(\"special.log\", filter=lambda record: \"special\" in record[\"extra\"])\n    logger.debug(\"This message is not logged to the file\")\n    logger.bind(special=True).info(\"This message, though, is logged to the file!\")\n\nFinally, the |patch|_ method allows dynamic values to be attached to the record dict of each new message:\n\n::\n\n    logger.add(sys.stderr, format=\"{extra[utc]} {message}\")\n    logger = logger.patch(lambda record: record[\"extra\"].update(utc=datetime.utcnow()))\n\n\nLazy evaluation of expensive functions\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nSometime you would like to log verbose information without performance penalty in production, you can use the |opt|_ method to achieve this.\n\n::\n\n    logger.opt(lazy=True).debug(\"If sink level <= DEBUG: {x}\", x=lambda: expensive_function(2**64))\n\n    # By the way, \"opt()\" serves many usages\n    logger.opt(exception=True).info(\"Error stacktrace added to the log message (tuple accepted too)\")\n    logger.opt(colors=True).info(\"Per message <blue>colors</blue>\")\n    logger.opt(record=True).info(\"Display values from the record (eg. {record[thread]})\")\n    logger.opt(raw=True).info(\"Bypass sink formatting\\n\")\n    logger.opt(depth=1).info(\"Use parent stack context (useful within wrapped functions)\")\n    logger.opt(capture=False).info(\"Keyword arguments not added to {dest} dict\", dest=\"extra\")\n\n\nCustomizable levels\n^^^^^^^^^^^^^^^^^^^\n\n`Loguru` comes with all standard `logging levels`_ to which |trace|_ and |success|_ are added. Do you need more? Then, just create it by using the |level|_ function.\n\n::\n\n    new_level = logger.level(\"SNAKY\", no=38, color=\"<yellow>\", icon=\"\ud83d\udc0d\")\n\n    logger.log(\"SNAKY\", \"Here we go!\")\n\n\nBetter datetime handling\n^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe standard logging is bloated with arguments like ``datefmt`` or ``msecs``, ``%(asctime)s`` and ``%(created)s``, naive datetimes without timezone information, not intuitive formatting, etc. `Loguru` `fixes it`_:\n\n::\n\n    logger.add(\"file.log\", format=\"{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}\")\n\n\nSuitable for scripts and libraries\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nUsing the logger in your scripts is easy, and you can |configure|_ it at start. To use `Loguru` from inside a library, remember to never call |add|_ but use |disable|_ instead so logging functions become no-op. If a developer wishes to see your library's logs, they can |enable|_ it again.\n\n::\n\n    # For scripts\n    config = {\n        \"handlers\": [\n            {\"sink\": sys.stdout, \"format\": \"{time} - {message}\"},\n            {\"sink\": \"file.log\", \"serialize\": True},\n        ],\n        \"extra\": {\"user\": \"someone\"}\n    }\n    logger.configure(**config)\n\n    # For libraries, should be your library's `__name__`\n    logger.disable(\"my_library\")\n    logger.info(\"No matter added sinks, this message is not displayed\")\n\n    # In your application, enable the logger in the library\n    logger.enable(\"my_library\")\n    logger.info(\"This message however is propagated to the sinks\")\n\nFor additional convenience, you can also use the |loguru-config|_ library to setup the ``logger`` directly from a configuration file.\n\nEntirely compatible with standard logging\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nWish to use built-in logging ``Handler`` as a `Loguru` sink?\n\n::\n\n    handler = logging.handlers.SysLogHandler(address=('localhost', 514))\n    logger.add(handler)\n\nNeed to propagate `Loguru` messages to standard `logging`?\n\n::\n\n    class PropagateHandler(logging.Handler):\n        def emit(self, record: logging.LogRecord) -> None:\n            logging.getLogger(record.name).handle(record)\n\n    logger.add(PropagateHandler(), format=\"{message}\")\n\nWant to intercept standard `logging` messages toward your `Loguru` sinks?\n\n::\n\n    class InterceptHandler(logging.Handler):\n        def emit(self, record: logging.LogRecord) -> None:\n            # Get corresponding Loguru level if it exists.\n            level: str | int\n            try:\n                level = logger.level(record.levelname).name\n            except ValueError:\n                level = record.levelno\n\n            # Find caller from where originated the logged message.\n            frame, depth = inspect.currentframe(), 0\n            while frame and (depth == 0 or frame.f_code.co_filename == logging.__file__):\n                frame = frame.f_back\n                depth += 1\n\n            logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())\n\n    logging.basicConfig(handlers=[InterceptHandler()], level=0, force=True)\n\n\nPersonalizable defaults through environment variables\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nDon't like the default logger formatting? Would prefer another ``DEBUG`` color? `No problem`_::\n\n    # Linux / OSX\n    export LOGURU_FORMAT=\"{time} | <lvl>{message}</lvl>\"\n\n    # Windows\n    setx LOGURU_DEBUG_COLOR \"<green>\"\n\n\nConvenient parser\n^^^^^^^^^^^^^^^^^\n\nIt is often useful to extract specific information from generated logs, this is why `Loguru` provides a |parse|_ method which helps to deal with logs and regexes.\n\n::\n\n    pattern = r\"(?P<time>.*) - (?P<level>[0-9]+) - (?P<message>.*)\"  # Regex with named groups\n    caster_dict = dict(time=dateutil.parser.parse, level=int)        # Transform matching groups\n\n    for groups in logger.parse(\"file.log\", pattern, cast=caster_dict):\n        print(\"Parsed:\", groups)\n        # {\"level\": 30, \"message\": \"Log example\", \"time\": datetime(2018, 12, 09, 11, 23, 55)}\n\n\nExhaustive notifier\n^^^^^^^^^^^^^^^^^^^\n\n`Loguru` can easily be combined with the great |notifiers|_ library (must be installed separately) to receive an e-mail when your program fail unexpectedly or to send many other kind of notifications.\n\n::\n\n    import notifiers\n\n    params = {\n        \"username\": \"you@gmail.com\",\n        \"password\": \"abc123\",\n        \"to\": \"dest@gmail.com\"\n    }\n\n    # Send a single notification\n    notifier = notifiers.get_notifier(\"gmail\")\n    notifier.notify(message=\"The application is running!\", **params)\n\n    # Be alerted on each error message\n    from notifiers.logging import NotificationHandler\n\n    handler = NotificationHandler(\"gmail\", defaults=params)\n    logger.add(handler, level=\"ERROR\")\n\n\n10x faster than built-in logging\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nAlthough logging impact on performances is in most cases negligible, a zero-cost logger would allow to use it anywhere without much concern. In an upcoming release, Loguru's critical functions will be implemented in C for maximum speed.\n\n\n.. end-of-readme-usage\n\n\nDocumentation\n-------------\n\n* `API Reference <https://loguru.readthedocs.io/en/stable/api/logger.html>`_\n* `Help & Guides <https://loguru.readthedocs.io/en/stable/resources.html>`_\n* `Type hints <https://loguru.readthedocs.io/en/stable/api/type_hints.html>`_\n* `Contributing <https://loguru.readthedocs.io/en/stable/project/contributing.html>`_\n* `License <https://loguru.readthedocs.io/en/stable/project/license.html>`_\n* `Changelog <https://loguru.readthedocs.io/en/stable/project/changelog.html>`_\n",
    "bugtrack_url": null,
    "license": "MIT license",
    "summary": "Python logging made (stupidly) simple",
    "version": "0.7.2",
    "project_urls": {
        "Changelog": "https://github.com/Delgan/loguru/blob/master/CHANGELOG.rst",
        "Documentation": "https://loguru.readthedocs.io/en/stable/index.html",
        "Download": "https://github.com/Delgan/loguru/archive/0.7.2.tar.gz",
        "Homepage": "https://github.com/Delgan/loguru"
    },
    "split_keywords": [
        "loguru",
        "logging",
        "logger",
        "log"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "030a4f6fed21aa246c6b49b561ca55facacc2a44b87d65b8b92362a8e99ba202",
                "md5": "731e4e224d9c25bc52e1d6015a15b513",
                "sha256": "003d71e3d3ed35f0f8984898359d65b79e5b21943f78af86aa5491210429b8eb"
            },
            "downloads": -1,
            "filename": "loguru-0.7.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "731e4e224d9c25bc52e1d6015a15b513",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.5",
            "size": 62549,
            "upload_time": "2023-09-11T15:24:35",
            "upload_time_iso_8601": "2023-09-11T15:24:35.016195Z",
            "url": "https://files.pythonhosted.org/packages/03/0a/4f6fed21aa246c6b49b561ca55facacc2a44b87d65b8b92362a8e99ba202/loguru-0.7.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9e30d87a423766b24db416a46e9335b9602b054a72b96a88a241f2b09b560fa8",
                "md5": "572c233002a3ab88ffb727a916716ad5",
                "sha256": "e671a53522515f34fd406340ee968cb9ecafbc4b36c679da03c18fd8d0bd51ac"
            },
            "downloads": -1,
            "filename": "loguru-0.7.2.tar.gz",
            "has_sig": false,
            "md5_digest": "572c233002a3ab88ffb727a916716ad5",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.5",
            "size": 145103,
            "upload_time": "2023-09-11T15:24:37",
            "upload_time_iso_8601": "2023-09-11T15:24:37.926573Z",
            "url": "https://files.pythonhosted.org/packages/9e/30/d87a423766b24db416a46e9335b9602b054a72b96a88a241f2b09b560fa8/loguru-0.7.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-09-11 15:24:37",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Delgan",
    "github_project": "loguru",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "loguru"
}
        
Elapsed time: 0.12994s