nts.logging


Naments.logging JSON
Version 0.0.1 PyPI version JSON
download
home_pageNone
SummaryAsyncio logging handlers
upload_time2024-11-05 06:33:02
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseMIT License Copyright (c) 2024 Anton Bondarenko Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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/`](./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](./examples/README.md).

## 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:
```bash
pip install nts.logging
```

To install all optional dependencies (including Redis and upcoming PostgreSQL support), use:
```bash
pip install nts.logging[all]
```

Or, to install individual dependencies as needed:
```bash
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.

```python
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.

```python
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:

```python
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

```python
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.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "nts.logging",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": null,
    "author": null,
    "author_email": "Anton Bondarenko <bond.anton@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/c5/0a/876309dd9399ff27af8e4f7bc761470a4d09626436bfe592e9dfea3e6226/nts_logging-0.0.1.tar.gz",
    "platform": null,
    "description": "# nts.logging\n\n**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.\n\n## Features\n\n- **Asynchronous Logging**: Log messages are queued and handled asynchronously, reducing impact on application performance.\n- **Multiple Backends**: Supports console and Redis logging out of the box.\n- **Flexible Logging Levels**: Compatible with Python\u2019s standard logging levels (`DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`).\n- **Optional Dependencies**: Only installs dependencies for the specific backends you need.\n\n## Examples\n\nExplore the [`examples/`](./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.\n\nFor detailed descriptions of each example, refer to the [Examples README](./examples/README.md).\n\n## Requirements\n\n- Python 3.9+\n- Additional dependencies for specific backends:\n  - **Redis support**: `redis.asyncio` (`pip install nts.logging[redis]`)\n  - **PostgreSQL support**: *Coming Soon!* `asyncpg` (`pip install nts.logging[postgres]`)\n\n## Installation\n\nInstall the base package with:\n```bash\npip install nts.logging\n```\n\nTo install all optional dependencies (including Redis and upcoming PostgreSQL support), use:\n```bash\npip install nts.logging[all]\n```\n\nOr, to install individual dependencies as needed:\n```bash\npip install nts.logging[redis]     # For Redis logging\npip install nts.logging[postgres]  # For PostgreSQL logging\n```\n\n## Basic Usage\n\n### Console Logging\nThe following example shows how to set up asynchronous console logging.\n\n```python\nimport logging\nfrom nts.logging import AsyncBaseHandler\nimport asyncio\n\n# Set up logger and handler\nlogger = logging.getLogger(\"MyAsyncLogger\")\nlogger.setLevel(logging.DEBUG)\nhandler = AsyncBaseHandler()\nlogger.addHandler(handler)\n\nasync def main():\n    await handler.start_logging()\n    logger.info(\"This is an asynchronous log message\")\n    await handler.stop_logging()\n\nasyncio.run(main())\n```\n\n### Redis Logging\nThis example demonstrates logging to a Redis stream.\n\n```python\nimport logging\nfrom nts.logging import AsyncRedisHandler\nimport asyncio\n\n# Set up logger and Redis handler\nlogger = logging.getLogger(\"MyAsyncLogger\")\nlogger.setLevel(logging.DEBUG)\nhandler = AsyncRedisHandler(stream_name=\"my_log_stream\")\nlogger.addHandler(handler)\n\nasync def main():\n    await handler.start_logging()\n    logger.error(\"This error message will be logged to Redis!\")\n    await handler.stop_logging()\n\nasyncio.run(main())\n```\n\n## Configuration\n\nnts.logging is designed to allow easy configuration of additional backends and custom logging formats:\n\nFormatting: Use Python\u2019s standard logging Formatter to customize output. For example, to log timestamps in ISO format:\n\n```python\nformatter = logging.Formatter(\n    fmt=\"%(asctime)s - %(levelname)s - %(message)s\",\n    datefmt=\"%Y-%m-%dT%H:%M:%SZ\"\n)\nhandler.setFormatter(formatter)\n```\n\n## Extending nts.logging\n\nTo 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.\n\n### Example: Custom Database Handler\n\n```python\nfrom nts.logging import AsyncBaseHandler\nimport asyncpg\n\nclass AsyncPostgresHandler(AsyncBaseHandler):\n    def __init__(self, db_url):\n        super().__init__()\n        self.db_url = db_url\n        self.queues[\"postgres\"] = asyncio.Queue()\n        self.workers.append(self._postgres_worker())\n\n    async def _postgres_worker(self):\n        self.conn = await asyncpg.connect(self.db_url)\n        while self.logging_running_event.is_set() or not self.queues[\"postgres\"].empty():\n            record = await self.queues[\"postgres\"].get()\n            await self.conn.execute(\"INSERT INTO logs (level, message) VALUES ($1, $2)\", record.levelname, record.getMessage())\n            self.queues[\"postgres\"].task_done()\n\n    def emit(self, record):\n        super().emit(record)\n        asyncio.create_task(self.queues[\"postgres\"].put(record))\n```\n\n## Contributing\n\nContributions are welcome! If you find a bug or want to add a feature, please open an issue or submit a pull request.\n\n## License\n\nThis project is licensed under the MIT License.\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2024 Anton Bondarenko  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
    "summary": "Asyncio logging handlers",
    "version": "0.0.1",
    "project_urls": {
        "Bug Tracker": "https://github.com/bond-anton/nts.logging/issues",
        "Homepage": "https://github.com/bond-anton/nts.logging"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9d8c4b9026d6290371462eafa91f2747b2bf41582421eb18ef211d215ee09854",
                "md5": "d85866599880d3f962886da705144b5e",
                "sha256": "9b464ec36e83d4c6e6f718621260fa4ff4ed5d39bfea25adf0278f1def9519c6"
            },
            "downloads": -1,
            "filename": "nts.logging-0.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d85866599880d3f962886da705144b5e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 11779,
            "upload_time": "2024-11-05T06:33:00",
            "upload_time_iso_8601": "2024-11-05T06:33:00.210584Z",
            "url": "https://files.pythonhosted.org/packages/9d/8c/4b9026d6290371462eafa91f2747b2bf41582421eb18ef211d215ee09854/nts.logging-0.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c50a876309dd9399ff27af8e4f7bc761470a4d09626436bfe592e9dfea3e6226",
                "md5": "e8e3baf5d9a5842c6d46ae8e879a9aa9",
                "sha256": "48a40e873ddb309dcc66332049426803e50e38bf21928856aa00e47fae1936a4"
            },
            "downloads": -1,
            "filename": "nts_logging-0.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "e8e3baf5d9a5842c6d46ae8e879a9aa9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 14224,
            "upload_time": "2024-11-05T06:33:02",
            "upload_time_iso_8601": "2024-11-05T06:33:02.892351Z",
            "url": "https://files.pythonhosted.org/packages/c5/0a/876309dd9399ff27af8e4f7bc761470a4d09626436bfe592e9dfea3e6226/nts_logging-0.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-05 06:33:02",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "bond-anton",
    "github_project": "nts.logging",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "nts.logging"
}
        
Elapsed time: 0.51970s