risclog.logging


Namerisclog.logging JSON
Version 1.2.1 PyPI version JSON
download
home_pagehttps://github.com/risclog-solution/risclog.logging
SummaryA logger based on structlog
upload_time2024-09-20 11:47:02
maintainerNone
docs_urlNone
authorriscLOG Solution GmbH
requires_python>=3.8
licenseMIT license
keywords risclog.logging
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ===============
risclog.logging
===============

.. image:: https://github.com/risclog-solution/risclog.logging/actions/workflows/test.yml/badge.svg
     :target: https://github.com/risclog-solution/risclog.logging/actions/workflows/test.yml
     :alt: CI Status


.. image:: https://img.shields.io/pypi/v/risclog.logging.svg
        :target: https://pypi.python.org/pypi/risclog.logging


The risclog.logging package provides a comprehensive solution for structured logging in Python applications. Risclog.logging uses structlog and logging to generate detailed and formatted log entries. The package supports both synchronous and asynchronous log messages and provides options for automatic e-mail notification of exception errors.


* Free software: MIT license
* Documentation: https://risclog.logging.readthedocs.io.


Features
========


Creating a logger
-----------------

To create a logger, use the get_logger function. This function ensures that you get an instance of RiscLogger that is properly configured.

.. code-block:: python

    from risclog.logging import get_logger

    # create logger
    logger = get_logger(name='my_logger')


Configuration of the logger
---------------------------

The logger configuration takes place automatically when the logger instance is created using get_logger. The _configure_logger method sets up structlog and logging to provide logs with timestamps, context variables and formatting. You can customize the configuration as required.

The module is configured to automatically read the logging level from an environment variable. By default, the level is set to `INFO`. To adjust this, set the `LOG_LEVEL` environment variable:

.. code-block:: bash

    export LOG_LEVEL=DEBUG


Use the following methods to log messages with different log levels:

* Debug-message: logger.debug("This is a debug message")
* Info-message: logger.info("This is an info message")
* Warning-message: logger.warning("This is a warning message")
* Error-message: logger.error("This is an error message")
* Critical-message: logger.critical("This is a critical message")
* Fatal-message: logger.fatal("This is a fatal message")
* Exception-message: logger.exception("This is an exception message")


Asynchronous and synchronous log messages
-----------------------------------------

The risclog.logging package supports both synchronous and asynchronous log messages. If you are working in an asynchronous environment, use the asynchronous versions of the log methods:

* Asynchronous debug message: await logger.debug("Async debug message")
* Asynchronous info message: await logger.info("Async info message")
* And so on...


Decorator for logging
---------------------

The decorator decorator can be used to provide methods with automatic logging and optional e-mail notification of exceptions

.. code-block:: python

    from risclog.logging import get_logger

    logger = get_logger(name='my_logger')

    @logger.decorator(send_email=True)
    async def some_async_function(x, y):
        return x + y

.. code-block:: python

    from risclog.logging import get_logger

    logger = get_logger(name='my_logger')

    @logger.decorator
    def some_sync_function(x, y):
        return x + y


Error handling and e-mail notification
--------------------------------------

If you set the send_email parameter to True, an email notification is automatically sent in the event of an exception. The email is sent asynchronously via a ThreadPoolExecutor and contains the exception details.

**To be able to send e-mails, the following environment variables must be set!**

* 'logging_email_smtp_user'
* 'logging_email_smtp_password'
* 'logging_email_to'
* 'logging_email_smtp_server'


Example
-------

Here is a complete example showing how to use the risclog.logginng package in an application


.. code-block:: python

    import os
    import asyncio
    from risclog.logging import get_logger


    os.environ["LOG_LEVEL"] = "DEBUG"

    logger = get_logger("async_debug_example")


    @logger.decorator(send_email=True)
    async def fetch_data(url: str):
        await logger.debug(f"Start retrieving data from  {url}")
        await asyncio.sleep(2)  # Simulates a delay, such as a network request
        await logger.debug(f"Successfully retrieved data from {url}")
        return {"data": f"Sample data from {url}"}


    @logger.decorator
    async def main():
        url = "https://example.com"
        await logger.debug(f"Start main function with URL: {url}")
        data = await fetch_data(url)
        await logger.debug(f"Data received: {data}")


    if __name__ == "__main__":
        logger.info("Start main function")
        asyncio.run(main())


output:

.. code-block:: bash

    2024-08-05 11:38:51 [info     ] [async_debug_example] __id=4378622064 __sender=inline message=Start main function
    2024-08-05 11:38:51 [info     ] [async_debug_example] __id=4384943584 __sender=async_logging_decorator _function=main _script=example.py message=Method "main" called with no arguments.
    2024-08-05 11:38:51 [debug    ] [async_debug_example] __id=4378552584 __sender=inline _function=main _script=example.py message=Start main function with URL: https://example.com
    2024-08-05 11:38:51 [info     ] [async_debug_example] __id=4384943744 __sender=async_logging_decorator _function=fetch_data _script=example.py message=Method called: "fetch_data" with: "{'arg_0': 'https://example.com'}"
    2024-08-05 11:38:51 [debug    ] [async_debug_example] __id=4366292144 __sender=inline _function=fetch_data _script=example.py message=Start retrieving data from  https://example.com
    2024-08-05 11:38:53 [debug    ] [async_debug_example] __id=4366292144 __sender=inline _function=fetch_data _script=example.py message=Successfully retrieved data from https://example.com
    2024-08-05 11:38:53 [info     ] [async_debug_example] __id=4384943744 __sender=async_logging_decorator _function=fetch_data _script=example.py message=Method "fetch_data" returned: "{'data': 'Sample data from https://example.com'}"
    2024-08-05 11:38:53 [debug    ] [async_debug_example] __id=4378552584 __sender=inline message=Data received: {'data': 'Sample data from https://example.com'}
    2024-08-05 11:38:53 [info     ] [async_debug_example] __id=4384943584 __sender=async_logging_decorator message=Method "main" returned: "None"



Run tests::

    $ ./pytest


Credits
=======

This package was created with Cookiecutter_ and the `risclog-solution/risclog-cookiecutter-pypackage`_ project template.

.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`risclog-solution/risclog-cookiecutter-pypackage`: https://github.com/risclog-solution/risclog-cookiecutter-pypackage


This package uses AppEnv_ for running tests inside this package.

.. _AppEnv: https://github.com/flyingcircusio/appenv


==============================
Change log for risclog.logging
==============================


1.2.1 (2024-09-20)
==================

- forward exceptions


1.2.0 (2024-09-19)
==================

- rename email environments


1.1.0 (2024-08-27)
==================

- Allow logging with multiple loggers in a single module.


1.0.2 (2024-08-06)
==================

- Fix CI status badge.


1.0.1 (2024-08-06)
==================

- Fix `classifiers` and README structure.


1.0 (2024-08-06)
================

* initial release

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/risclog-solution/risclog.logging",
    "name": "risclog.logging",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "risclog.logging",
    "author": "riscLOG Solution GmbH",
    "author_email": "info@risclog.de",
    "download_url": "https://files.pythonhosted.org/packages/c6/32/08d2165a4d499419ae74cac5b321b085296e2d5f41ec15d717dec4dc1e94/risclog.logging-1.2.1.tar.gz",
    "platform": null,
    "description": "===============\nrisclog.logging\n===============\n\n.. image:: https://github.com/risclog-solution/risclog.logging/actions/workflows/test.yml/badge.svg\n     :target: https://github.com/risclog-solution/risclog.logging/actions/workflows/test.yml\n     :alt: CI Status\n\n\n.. image:: https://img.shields.io/pypi/v/risclog.logging.svg\n        :target: https://pypi.python.org/pypi/risclog.logging\n\n\nThe risclog.logging package provides a comprehensive solution for structured logging in Python applications. Risclog.logging uses structlog and logging to generate detailed and formatted log entries. The package supports both synchronous and asynchronous log messages and provides options for automatic e-mail notification of exception errors.\n\n\n* Free software: MIT license\n* Documentation: https://risclog.logging.readthedocs.io.\n\n\nFeatures\n========\n\n\nCreating a logger\n-----------------\n\nTo create a logger, use the get_logger function. This function ensures that you get an instance of RiscLogger that is properly configured.\n\n.. code-block:: python\n\n    from risclog.logging import get_logger\n\n    # create logger\n    logger = get_logger(name='my_logger')\n\n\nConfiguration of the logger\n---------------------------\n\nThe logger configuration takes place automatically when the logger instance is created using get_logger. The _configure_logger method sets up structlog and logging to provide logs with timestamps, context variables and formatting. You can customize the configuration as required.\n\nThe module is configured to automatically read the logging level from an environment variable. By default, the level is set to `INFO`. To adjust this, set the `LOG_LEVEL` environment variable:\n\n.. code-block:: bash\n\n    export LOG_LEVEL=DEBUG\n\n\nUse the following methods to log messages with different log levels:\n\n* Debug-message: logger.debug(\"This is a debug message\")\n* Info-message: logger.info(\"This is an info message\")\n* Warning-message: logger.warning(\"This is a warning message\")\n* Error-message: logger.error(\"This is an error message\")\n* Critical-message: logger.critical(\"This is a critical message\")\n* Fatal-message: logger.fatal(\"This is a fatal message\")\n* Exception-message: logger.exception(\"This is an exception message\")\n\n\nAsynchronous and synchronous log messages\n-----------------------------------------\n\nThe risclog.logging package supports both synchronous and asynchronous log messages. If you are working in an asynchronous environment, use the asynchronous versions of the log methods:\n\n* Asynchronous debug message: await logger.debug(\"Async debug message\")\n* Asynchronous info message: await logger.info(\"Async info message\")\n* And so on...\n\n\nDecorator for logging\n---------------------\n\nThe decorator decorator can be used to provide methods with automatic logging and optional e-mail notification of exceptions\n\n.. code-block:: python\n\n    from risclog.logging import get_logger\n\n    logger = get_logger(name='my_logger')\n\n    @logger.decorator(send_email=True)\n    async def some_async_function(x, y):\n        return x + y\n\n.. code-block:: python\n\n    from risclog.logging import get_logger\n\n    logger = get_logger(name='my_logger')\n\n    @logger.decorator\n    def some_sync_function(x, y):\n        return x + y\n\n\nError handling and e-mail notification\n--------------------------------------\n\nIf you set the send_email parameter to True, an email notification is automatically sent in the event of an exception. The email is sent asynchronously via a ThreadPoolExecutor and contains the exception details.\n\n**To be able to send e-mails, the following environment variables must be set!**\n\n* 'logging_email_smtp_user'\n* 'logging_email_smtp_password'\n* 'logging_email_to'\n* 'logging_email_smtp_server'\n\n\nExample\n-------\n\nHere is a complete example showing how to use the risclog.logginng package in an application\n\n\n.. code-block:: python\n\n    import os\n    import asyncio\n    from risclog.logging import get_logger\n\n\n    os.environ[\"LOG_LEVEL\"] = \"DEBUG\"\n\n    logger = get_logger(\"async_debug_example\")\n\n\n    @logger.decorator(send_email=True)\n    async def fetch_data(url: str):\n        await logger.debug(f\"Start retrieving data from  {url}\")\n        await asyncio.sleep(2)  # Simulates a delay, such as a network request\n        await logger.debug(f\"Successfully retrieved data from {url}\")\n        return {\"data\": f\"Sample data from {url}\"}\n\n\n    @logger.decorator\n    async def main():\n        url = \"https://example.com\"\n        await logger.debug(f\"Start main function with URL: {url}\")\n        data = await fetch_data(url)\n        await logger.debug(f\"Data received: {data}\")\n\n\n    if __name__ == \"__main__\":\n        logger.info(\"Start main function\")\n        asyncio.run(main())\n\n\noutput:\n\n.. code-block:: bash\n\n    2024-08-05 11:38:51 [info     ] [async_debug_example] __id=4378622064 __sender=inline message=Start main function\n    2024-08-05 11:38:51 [info     ] [async_debug_example] __id=4384943584 __sender=async_logging_decorator _function=main _script=example.py message=Method \"main\" called with no arguments.\n    2024-08-05 11:38:51 [debug    ] [async_debug_example] __id=4378552584 __sender=inline _function=main _script=example.py message=Start main function with URL: https://example.com\n    2024-08-05 11:38:51 [info     ] [async_debug_example] __id=4384943744 __sender=async_logging_decorator _function=fetch_data _script=example.py message=Method called: \"fetch_data\" with: \"{'arg_0': 'https://example.com'}\"\n    2024-08-05 11:38:51 [debug    ] [async_debug_example] __id=4366292144 __sender=inline _function=fetch_data _script=example.py message=Start retrieving data from  https://example.com\n    2024-08-05 11:38:53 [debug    ] [async_debug_example] __id=4366292144 __sender=inline _function=fetch_data _script=example.py message=Successfully retrieved data from https://example.com\n    2024-08-05 11:38:53 [info     ] [async_debug_example] __id=4384943744 __sender=async_logging_decorator _function=fetch_data _script=example.py message=Method \"fetch_data\" returned: \"{'data': 'Sample data from https://example.com'}\"\n    2024-08-05 11:38:53 [debug    ] [async_debug_example] __id=4378552584 __sender=inline message=Data received: {'data': 'Sample data from https://example.com'}\n    2024-08-05 11:38:53 [info     ] [async_debug_example] __id=4384943584 __sender=async_logging_decorator message=Method \"main\" returned: \"None\"\n\n\n\nRun tests::\n\n    $ ./pytest\n\n\nCredits\n=======\n\nThis package was created with Cookiecutter_ and the `risclog-solution/risclog-cookiecutter-pypackage`_ project template.\n\n.. _Cookiecutter: https://github.com/audreyr/cookiecutter\n.. _`risclog-solution/risclog-cookiecutter-pypackage`: https://github.com/risclog-solution/risclog-cookiecutter-pypackage\n\n\nThis package uses AppEnv_ for running tests inside this package.\n\n.. _AppEnv: https://github.com/flyingcircusio/appenv\n\n\n==============================\nChange log for risclog.logging\n==============================\n\n\n1.2.1 (2024-09-20)\n==================\n\n- forward exceptions\n\n\n1.2.0 (2024-09-19)\n==================\n\n- rename email environments\n\n\n1.1.0 (2024-08-27)\n==================\n\n- Allow logging with multiple loggers in a single module.\n\n\n1.0.2 (2024-08-06)\n==================\n\n- Fix CI status badge.\n\n\n1.0.1 (2024-08-06)\n==================\n\n- Fix `classifiers` and README structure.\n\n\n1.0 (2024-08-06)\n================\n\n* initial release\n",
    "bugtrack_url": null,
    "license": "MIT license",
    "summary": "A logger based on structlog",
    "version": "1.2.1",
    "project_urls": {
        "Homepage": "https://github.com/risclog-solution/risclog.logging"
    },
    "split_keywords": [
        "risclog.logging"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1a42f654b47c96097414822c5d52a034913ad58abaec819e7ccfb347ab99c7bc",
                "md5": "cc11c63e373d0906a808f2fbbb470e24",
                "sha256": "a75bb87bab6a5c2ad70687273db6de155fc3a8d18be1b9e24773458dd7ba85d7"
            },
            "downloads": -1,
            "filename": "risclog.logging-1.2.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "cc11c63e373d0906a808f2fbbb470e24",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 11426,
            "upload_time": "2024-09-20T11:47:00",
            "upload_time_iso_8601": "2024-09-20T11:47:00.501588Z",
            "url": "https://files.pythonhosted.org/packages/1a/42/f654b47c96097414822c5d52a034913ad58abaec819e7ccfb347ab99c7bc/risclog.logging-1.2.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c63208d2165a4d499419ae74cac5b321b085296e2d5f41ec15d717dec4dc1e94",
                "md5": "48251b4d2c21c5ba3a49f220f1398226",
                "sha256": "65e9a01949ef08eba68f43de4318eb761a1409dfccaba9dbdf241e413aef8fb7"
            },
            "downloads": -1,
            "filename": "risclog.logging-1.2.1.tar.gz",
            "has_sig": false,
            "md5_digest": "48251b4d2c21c5ba3a49f220f1398226",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 18304,
            "upload_time": "2024-09-20T11:47:02",
            "upload_time_iso_8601": "2024-09-20T11:47:02.289549Z",
            "url": "https://files.pythonhosted.org/packages/c6/32/08d2165a4d499419ae74cac5b321b085296e2d5f41ec15d717dec4dc1e94/risclog.logging-1.2.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-09-20 11:47:02",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "risclog-solution",
    "github_project": "risclog.logging",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "risclog.logging"
}
        
Elapsed time: 0.66905s