bunyan-formatter


Namebunyan-formatter JSON
Version 0.1.4 PyPI version JSON
download
home_pageNone
SummaryA custom formatter for Python's logging module that outputs logs in the Bunyan JSON format.
upload_time2024-10-01 15:47:20
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseMIT License Copyright (c) 2024 Kristofers Solo 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 bunyan formatter logger logging
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Bunyan Formatter

<!-- toc -->

- [Description](#description)
- [Installation](#installation)
- [Usage](#usage)
  * [Django](#django)
- [Examples](#examples)
  * [Basic Logging](#basic-logging)
  * [Error Logging with Exception](#error-logging-with-exception)
  * [Custom Fields](#custom-fields)
- [Contributing](#contributing)
- [License](#license)

<!-- tocstop -->

A custom formatter for Python's logging module that outputs logs in the Bunyan
JSON format.

## Description

This package provides a `BunyanFormatter` class that formats log records into
the Bunyan JSON format. Bunyan is a lightweight JSON logger for Node.js, but
this formatter allows you to use the same log format in Python projects.

Key features:

- Outputs logs in JSON format
- Includes project name, hostname, file path, line number, and other metadata
- Supports various log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL)
- Handles both project and external file paths

## Installation

To install the Bunyan Formatter package, run:

```bash
pip install bunyan-formatter
```

## Usage

Here's a basic example of how to use the Bunyan Formatter in your Python project:

```python
import logging
from bunyan_formatter import BunyanFormatter

# Create a logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Create a handler and set the formatter
handler = logging.StreamHandler()
formatter = BunyanFormatter(project_name="MyProject", project_root="/path/to/my/project")
handler.setFormatter(formatter)

# Add the handler to the logger
logger.addHandler(handler)

# Now you can use the logger
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")
```

### Django

In your Django project's `settings.py` file, add the following logging configuration:

```python
BASE_DIR = Path(__file__).resolve().parent.parent

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "bunyan": {
            "()": BunyanFormatter,
            "project_name": "MyProject",
            "project_root": BASE_DIR,
        },
    },
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "bunyan",
            "stream": "ext://sys.stdout",
        },
        "file": {
            "level": "DEBUG",
            "class": "logging.FileHandler",
            "filename": BASE_DIR / "logs" / "django.log",
            "formatter": "bunyan",
        },
    },
    "root": {
        "level": "DEBUG",
        "handlers": ["console", "file"],
    },
}
```

## Examples

### Basic Logging

```python
logger.info("User logged in", extra={"username": "john_doe"})
```

Output:

```json
{
  "v": 0,
  "name": "MyProject",
  "msg": "User logged in",
  "level": 30,
  "levelname": "INFO",
  "hostname": "your-hostname",
  "target": "__main__",
  "line": 10,
  "file": "main.py",
  "extra": {
    "username": "john_doe"
  }
}
```

### Error Logging with Exception

```python
try:
    result = 1 / 0
except ZeroDivisionError as e:
    logger.exception("An error occurred", exc_info=True)
```

Output:

```json
{
  "v": 0,
  "name": "MyProject",
  "msg": "An error occurred",
  "level": 50,
  "levelname": "ERROR",
  "hostname": "your-hostname",
  "target": "__main__",
  "line": 15,
  "file": "main.py",
  "err": {
    "message": "division by zero",
    "name": "ZeroDivisionError",
    "stack": [
      // Stack trace here
    ]
  }
}
```

### Custom Fields

You can add custom fields to your log entries:

```python
logger.info("Order processed", extra={
    "order_id": 12345,
    "customer_id": 67890,
    "total_amount": 100.00
})
```

Output:

```json
{
  "v": 0,
  "name": "MyProject",
  "msg": "Order processed",
  "level": 30,
  "levelname": "INFO",
  "hostname": "your-hostname",
  "target": "__main__",
  "line": 20,
  "file": "main.py",
  "extra": {
    "order_id": 12345,
    "customer_id": 67890,
    "total_amount": 100.0
  }
}
```

## Contributing

Contributions are welcome! Please submit pull requests or issues on our GitHub repository.

## License

This project is licensed under the MIT License - see the LICENSE file for details.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "bunyan-formatter",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "bunyan, formatter, logger, logging",
    "author": null,
    "author_email": "Kristofers Solo <dev@kristofers.xyz>",
    "download_url": "https://files.pythonhosted.org/packages/9c/77/2f8835b9a90e22cbba7c983d17173ed2fee34597a9e62ee0037e5c4c2827/bunyan_formatter-0.1.4.tar.gz",
    "platform": null,
    "description": "# Bunyan Formatter\n\n<!-- toc -->\n\n- [Description](#description)\n- [Installation](#installation)\n- [Usage](#usage)\n  * [Django](#django)\n- [Examples](#examples)\n  * [Basic Logging](#basic-logging)\n  * [Error Logging with Exception](#error-logging-with-exception)\n  * [Custom Fields](#custom-fields)\n- [Contributing](#contributing)\n- [License](#license)\n\n<!-- tocstop -->\n\nA custom formatter for Python's logging module that outputs logs in the Bunyan\nJSON format.\n\n## Description\n\nThis package provides a `BunyanFormatter` class that formats log records into\nthe Bunyan JSON format. Bunyan is a lightweight JSON logger for Node.js, but\nthis formatter allows you to use the same log format in Python projects.\n\nKey features:\n\n- Outputs logs in JSON format\n- Includes project name, hostname, file path, line number, and other metadata\n- Supports various log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL)\n- Handles both project and external file paths\n\n## Installation\n\nTo install the Bunyan Formatter package, run:\n\n```bash\npip install bunyan-formatter\n```\n\n## Usage\n\nHere's a basic example of how to use the Bunyan Formatter in your Python project:\n\n```python\nimport logging\nfrom bunyan_formatter import BunyanFormatter\n\n# Create a logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n# Create a handler and set the formatter\nhandler = logging.StreamHandler()\nformatter = BunyanFormatter(project_name=\"MyProject\", project_root=\"/path/to/my/project\")\nhandler.setFormatter(formatter)\n\n# Add the handler to the logger\nlogger.addHandler(handler)\n\n# Now you can use the logger\nlogger.debug(\"This is a debug message\")\nlogger.info(\"This is an info message\")\nlogger.warning(\"This is a warning message\")\nlogger.error(\"This is an error message\")\nlogger.critical(\"This is a critical message\")\n```\n\n### Django\n\nIn your Django project's `settings.py` file, add the following logging configuration:\n\n```python\nBASE_DIR = Path(__file__).resolve().parent.parent\n\nLOGGING = {\n    \"version\": 1,\n    \"disable_existing_loggers\": False,\n    \"formatters\": {\n        \"bunyan\": {\n            \"()\": BunyanFormatter,\n            \"project_name\": \"MyProject\",\n            \"project_root\": BASE_DIR,\n        },\n    },\n    \"handlers\": {\n        \"console\": {\n            \"level\": \"DEBUG\",\n            \"class\": \"logging.StreamHandler\",\n            \"formatter\": \"bunyan\",\n            \"stream\": \"ext://sys.stdout\",\n        },\n        \"file\": {\n            \"level\": \"DEBUG\",\n            \"class\": \"logging.FileHandler\",\n            \"filename\": BASE_DIR / \"logs\" / \"django.log\",\n            \"formatter\": \"bunyan\",\n        },\n    },\n    \"root\": {\n        \"level\": \"DEBUG\",\n        \"handlers\": [\"console\", \"file\"],\n    },\n}\n```\n\n## Examples\n\n### Basic Logging\n\n```python\nlogger.info(\"User logged in\", extra={\"username\": \"john_doe\"})\n```\n\nOutput:\n\n```json\n{\n  \"v\": 0,\n  \"name\": \"MyProject\",\n  \"msg\": \"User logged in\",\n  \"level\": 30,\n  \"levelname\": \"INFO\",\n  \"hostname\": \"your-hostname\",\n  \"target\": \"__main__\",\n  \"line\": 10,\n  \"file\": \"main.py\",\n  \"extra\": {\n    \"username\": \"john_doe\"\n  }\n}\n```\n\n### Error Logging with Exception\n\n```python\ntry:\n    result = 1 / 0\nexcept ZeroDivisionError as e:\n    logger.exception(\"An error occurred\", exc_info=True)\n```\n\nOutput:\n\n```json\n{\n  \"v\": 0,\n  \"name\": \"MyProject\",\n  \"msg\": \"An error occurred\",\n  \"level\": 50,\n  \"levelname\": \"ERROR\",\n  \"hostname\": \"your-hostname\",\n  \"target\": \"__main__\",\n  \"line\": 15,\n  \"file\": \"main.py\",\n  \"err\": {\n    \"message\": \"division by zero\",\n    \"name\": \"ZeroDivisionError\",\n    \"stack\": [\n      // Stack trace here\n    ]\n  }\n}\n```\n\n### Custom Fields\n\nYou can add custom fields to your log entries:\n\n```python\nlogger.info(\"Order processed\", extra={\n    \"order_id\": 12345,\n    \"customer_id\": 67890,\n    \"total_amount\": 100.00\n})\n```\n\nOutput:\n\n```json\n{\n  \"v\": 0,\n  \"name\": \"MyProject\",\n  \"msg\": \"Order processed\",\n  \"level\": 30,\n  \"levelname\": \"INFO\",\n  \"hostname\": \"your-hostname\",\n  \"target\": \"__main__\",\n  \"line\": 20,\n  \"file\": \"main.py\",\n  \"extra\": {\n    \"order_id\": 12345,\n    \"customer_id\": 67890,\n    \"total_amount\": 100.0\n  }\n}\n```\n\n## Contributing\n\nContributions are welcome! Please submit pull requests or issues on our GitHub repository.\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2024 Kristofers Solo  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": "A custom formatter for Python's logging module that outputs logs in the Bunyan JSON format.",
    "version": "0.1.4",
    "project_urls": {
        "Source": "https://github.com/kristoferssolo/bunyan-formatter",
        "Tracker": "https://github.com/kristoferssolo/bunyan-formatter/issues"
    },
    "split_keywords": [
        "bunyan",
        " formatter",
        " logger",
        " logging"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0bff5361bcda50e978fb8f9b03a876cba66e9f621cbd2d07219689bf10141b79",
                "md5": "b66ff05097caaae285db6c266c52ed3e",
                "sha256": "e6ed3461c607e2a52d9f7b4e63fc454772e9322003b68a4d970dabe599c30e37"
            },
            "downloads": -1,
            "filename": "bunyan_formatter-0.1.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "b66ff05097caaae285db6c266c52ed3e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 5822,
            "upload_time": "2024-10-01T15:47:18",
            "upload_time_iso_8601": "2024-10-01T15:47:18.816749Z",
            "url": "https://files.pythonhosted.org/packages/0b/ff/5361bcda50e978fb8f9b03a876cba66e9f621cbd2d07219689bf10141b79/bunyan_formatter-0.1.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9c772f8835b9a90e22cbba7c983d17173ed2fee34597a9e62ee0037e5c4c2827",
                "md5": "771218b8f23cc426fd348805ca4c4105",
                "sha256": "df7230bc0fc0f2d90e2b5324f7b0741d0b1910f3d245f70cd4e29bf5449b0b79"
            },
            "downloads": -1,
            "filename": "bunyan_formatter-0.1.4.tar.gz",
            "has_sig": false,
            "md5_digest": "771218b8f23cc426fd348805ca4c4105",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 21444,
            "upload_time": "2024-10-01T15:47:20",
            "upload_time_iso_8601": "2024-10-01T15:47:20.484029Z",
            "url": "https://files.pythonhosted.org/packages/9c/77/2f8835b9a90e22cbba7c983d17173ed2fee34597a9e62ee0037e5c4c2827/bunyan_formatter-0.1.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-01 15:47:20",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "kristoferssolo",
    "github_project": "bunyan-formatter",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "tox": true,
    "lcname": "bunyan-formatter"
}
        
Elapsed time: 0.34137s