Skip to main content

Asyncio logging handlers

Project description

nts.logging

nts.logging is an asynchronous logging package designed for high-performance applications that require non-blocking logging. It uses asyncio to manage log message queues and provides multiple backends, such as console and Redis logging, allowing for easy extension to other logging targets.

Features

  • Asynchronous Logging: Log messages are queued and handled asynchronously, reducing impact on application performance.
  • Multiple Backends: Supports console and Redis logging out of the box.
  • Flexible Logging Levels: Compatible with Python’s standard logging levels (DEBUG, INFO, WARNING, ERROR, CRITICAL).
  • Optional Dependencies: Only installs dependencies for the specific backends you need.

Examples

Explore the examples/ directory to see usage examples that demonstrate how to set up and work with nts.logging. Each example provides a practical setup for different logging scenarios, including basic console logging and Redis-based logging.

For detailed descriptions of each example, refer to the Examples README.

Requirements

  • Python 3.9+
  • Additional dependencies for specific backends:
    • Redis support: redis.asyncio (pip install nts.logging[redis])
    • PostgreSQL support: Coming Soon! asyncpg (pip install nts.logging[postgres])

Installation

Install the base package with:

pip install nts.logging

To install all optional dependencies (including Redis and upcoming PostgreSQL support), use:

pip install nts.logging[all]

Or, to install individual dependencies as needed:

pip install nts.logging[redis]     # For Redis logging
pip install nts.logging[postgres]  # For PostgreSQL logging

Basic Usage

Console Logging

The following example shows how to set up asynchronous console logging.

import logging
from nts.logging import AsyncBaseHandler
import asyncio

# Set up logger and handler
logger = logging.getLogger("MyAsyncLogger")
logger.setLevel(logging.DEBUG)
handler = AsyncBaseHandler()
logger.addHandler(handler)

async def main():
    await handler.start_logging()
    logger.info("This is an asynchronous log message")
    await handler.stop_logging()

asyncio.run(main())

Redis Logging

This example demonstrates logging to a Redis stream.

import logging
from nts.logging import AsyncRedisHandler
import asyncio

# Set up logger and Redis handler
logger = logging.getLogger("MyAsyncLogger")
logger.setLevel(logging.DEBUG)
handler = AsyncRedisHandler(stream_name="my_log_stream")
logger.addHandler(handler)

async def main():
    await handler.start_logging()
    logger.error("This error message will be logged to Redis!")
    await handler.stop_logging()

asyncio.run(main())

Configuration

nts.logging is designed to allow easy configuration of additional backends and custom logging formats:

Formatting: Use Python’s standard logging Formatter to customize output. For example, to log timestamps in ISO format:

formatter = logging.Formatter(
    fmt="%(asctime)s - %(levelname)s - %(message)s",
    datefmt="%Y-%m-%dT%H:%M:%SZ"
)
handler.setFormatter(formatter)

Extending nts.logging

To add support for additional logging backends, subclass AsyncBaseHandler and implement new workers as shown in the Redis example. The structure of the package allows for seamless extension by adding new worker methods for different logging destinations.

Example: Custom Database Handler

from nts.logging import AsyncBaseHandler
import asyncpg

class AsyncPostgresHandler(AsyncBaseHandler):
    def __init__(self, db_url):
        super().__init__()
        self.db_url = db_url
        self.queues["postgres"] = asyncio.Queue()
        self.workers.append(self._postgres_worker())

    async def _postgres_worker(self):
        self.conn = await asyncpg.connect(self.db_url)
        while self.logging_running_event.is_set() or not self.queues["postgres"].empty():
            record = await self.queues["postgres"].get()
            await self.conn.execute("INSERT INTO logs (level, message) VALUES ($1, $2)", record.levelname, record.getMessage())
            self.queues["postgres"].task_done()

    def emit(self, record):
        super().emit(record)
        asyncio.create_task(self.queues["postgres"].put(record))

Contributing

Contributions are welcome! If you find a bug or want to add a feature, please open an issue or submit a pull request.

License

This project is licensed under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nts_logging-0.0.1.tar.gz (14.2 kB view details)

Uploaded Source

Built Distribution

nts.logging-0.0.1-py3-none-any.whl (11.8 kB view details)

Uploaded Python 3

File details

Details for the file nts_logging-0.0.1.tar.gz.

File metadata

  • Download URL: nts_logging-0.0.1.tar.gz
  • Upload date:
  • Size: 14.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for nts_logging-0.0.1.tar.gz
Algorithm Hash digest
SHA256 48a40e873ddb309dcc66332049426803e50e38bf21928856aa00e47fae1936a4
MD5 e8e3baf5d9a5842c6d46ae8e879a9aa9
BLAKE2b-256 c50a876309dd9399ff27af8e4f7bc761470a4d09626436bfe592e9dfea3e6226

See more details on using hashes here.

Provenance

The following attestation bundles were made for nts_logging-0.0.1.tar.gz:

Publisher: python-publish.yml on bond-anton/nts.logging

Attestations:

File details

Details for the file nts.logging-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: nts.logging-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 11.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for nts.logging-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9b464ec36e83d4c6e6f718621260fa4ff4ed5d39bfea25adf0278f1def9519c6
MD5 d85866599880d3f962886da705144b5e
BLAKE2b-256 9d8c4b9026d6290371462eafa91f2747b2bf41582421eb18ef211d215ee09854

See more details on using hashes here.

Provenance

The following attestation bundles were made for nts.logging-0.0.1-py3-none-any.whl:

Publisher: python-publish.yml on bond-anton/nts.logging

Attestations:

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page