Skip to main content

scietex.logging

scietex.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, Redis, Valkey, and MQTT 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, Redis, Valkey, and MQTT 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 scietex.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.10+
  • Additional dependencies for specific backends:
    • Redis support: redis (pip install scietex.logging[redis])
    • Valkey support: valkey-glide (pip install scietex.logging[valkey])
    • MQTT support: aiomqtt (pip install scietex.logging[mqtt])

Installation

Install the base package with:

pip install scietex.logging

To install all optional dependencies (including Redis, Valkey, and MQTT support), use:

pip install scietex.logging[all]

Or, to install individual dependencies as needed:

pip install scietex.logging[redis]   # For Redis logging
pip install scietex.logging[valkey]  # For Valkey logging
pip install scietex.logging[mqtt]    # For MQTT logging

Basic Usage

Console Logging

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

import logging
from scietex.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 scietex.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())

Valkey Logging

This example demonstrates logging to a Valkey stream.

import logging
from scietex.logging import AsyncValkeyHandler
import asyncio

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


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


asyncio.run(main())

MQTT Logging

This example demonstrates publishing log records to an MQTT topic.

import logging
from scietex.logging import AsyncMqttHandler
import asyncio

# Set up logger and MQTT handler
logger = logging.getLogger("MyAsyncLogger")
logger.setLevel(logging.DEBUG)
handler = AsyncMqttHandler(topic="my/log/topic")
logger.addHandler(handler)


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


asyncio.run(main())

Configuration

scietex.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)

A formatter affects the console (stdout) output only; broker backends build their payloads from the handler's service_name/worker_id config and the record directly, so they are invariant under setFormatter. See docs/configuration.md.

Extending scietex.logging

To add support for additional logging backends, subclass AsyncBrokerHandler and implement connect(), disconnect(), and send_message() methods. AsyncLoggingHandler is the pure-machinery base that owns the queue/worker infrastructure but no sink of its own; AsyncBaseHandler builds on it and registers the console as a peer backend (enabled by default via stdout_enable), while AsyncBrokerHandler is designed for message broker backends like Redis or Valkey.

Example: Custom Database Handler

from scietex.logging import AsyncBrokerHandler


class AsyncPostgresHandler(AsyncBrokerHandler):
    def __init__(self, db_url):
        super().__init__(queue_name="postgres")
        self.db_url = db_url
        self._db_conn = None

    async def connect(self):
        import asyncpg

        self._db_conn = await asyncpg.connect(self.db_url)

    async def disconnect(self):
        if self._db_conn:
            await self._db_conn.close()

    async def send_message(self, record):
        await self._db_conn.execute(
            "INSERT INTO logs (level, message) VALUES ($1, $2)",
            record["level"],
            record["message"],
        )

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.

Download files

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

Source Distribution

scietex_logging-1.4.0.tar.gz (44.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

scietex_logging-1.4.0-py3-none-any.whl (34.0 kB view details)

Uploaded Python 3

File details

Details for the file scietex_logging-1.4.0.tar.gz.

File metadata

  • Download URL: scietex_logging-1.4.0.tar.gz
  • Upload date:
  • Size: 44.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for scietex_logging-1.4.0.tar.gz
Algorithm Hash digest
SHA256 030e362c6fc9df42ea5cdfab177d6f577da5e57958b6633f5fa373a2a8a3d3bf
MD5 16c790002d6d796508b77ec372768b3e
BLAKE2b-256 7f849a10282aa05daa6b0f941a99d199acced72965d009252f138816074414cd

See more details on using hashes here.

Provenance

The following attestation bundles were made for scietex_logging-1.4.0.tar.gz:

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

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file scietex_logging-1.4.0-py3-none-any.whl.

File metadata

File hashes

Hashes for scietex_logging-1.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e00c840931d4cff820c2a1ea8c7d1ab9b5401e792f5d43ebc7a608bdf6c88bc7
MD5 a5858204c9061a303100330cdcd6d999
BLAKE2b-256 8a6157bf958e805a9bee7eadc11ecdd28c06de70c8a0c8f02d486992e90214d4

See more details on using hashes here.

Provenance

The following attestation bundles were made for scietex_logging-1.4.0-py3-none-any.whl:

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

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

2.0.0

2 files

1.8.0

2 files

1.7.0

2 files

1.6.0

2 files

This release

1.4.0 This release

2 files

1.3.0

2 files

1.2.0

2 files

1.1.0

2 files

1.0.0

2 files

0.2.0

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

0.0.3

2 files

0.0.2

2 files

0.0.1

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page