django-custom-logging


Namedjango-custom-logging JSON
Version 0.2.1 PyPI version JSON
download
home_page
SummaryDjango middleware for custom format logging
upload_time2024-03-02 07:26:03
maintainer
docs_urlNone
author
requires_python>=3.5
license
keywords django logging middleware
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # django-custom-logging <img src="https://github.com/sh-cho/django-custom-logging/assets/11611397/934a41d5-2f95-49a1-9033-294db188cbac" width="250" align="right" alt="django-custom-logging logo">

> django middleware for custom format logging

[![PyPI](https://img.shields.io/pypi/v/django-custom-logging)](https://pypi.python.org/pypi/django-custom-logging/)
[![PyPI - License](https://img.shields.io/pypi/l/django-custom-logging)](https://github.com/sh-cho/django-custom-logging/blob/master/LICENSE)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/django-custom-logging)](https://pypi.python.org/pypi/django-custom-logging/)
[![PyPI - Downloads](https://img.shields.io/pypi/dm/django-custom-logging)](https://pypi.python.org/pypi/django-custom-logging/)
![PyPI - Wheel](https://img.shields.io/pypi/wheel/django-custom-logging)
[![Test](https://github.com/sh-cho/django-custom-logging/actions/workflows/test.yml/badge.svg?branch=develop)](https://github.com/sh-cho/django-custom-logging/actions/workflows/test.yml)
[![Lint](https://github.com/sh-cho/django-custom-logging/actions/workflows/lint.yml/badge.svg?branch=develop)](https://github.com/sh-cho/django-custom-logging/actions/workflows/lint.yml)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)


## Installation
1. Install the package
```sh
python -m pip install django-custom-logging
```

2. Add adequate middlewares to `MIDDLEWARE` in setting file. Current version only supports a middleware that captures `request` into local thread(`threading.local()`)
```python
MIDDLEWARE = (
    # other middlewares ...
    "custom_logging.middlewares.capture_request",
)
```

3. Add `custom_logging.filters.CustomFilter` to `LOGGING` in setting file and set `capture_list` containing a list of variables to be captured(`capture_in`) and format string to be printed(`capture_out`). Also add filter on handler's filter list.
```python
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "verbose": {
            "format": "{levelname} {asctime} {module} {meta[REMOTE_ADDR]} {meta[CONTENT_LENGTH]} {process:d} {thread:d}"
                      " [USER_ID:{user_id}] {message}",
                                #^^^^^^^^^ - (A)
            "style": "{",
        },
    },
    "filters": {
        "custom_filter": {
        #^^^^^^^^^^^^^ - (B)
            "()": "custom_logging.filters.CustomFilter",
            "capture_list": (
                # (capture_in, capture_out)
                ("request.user.id", "user_id"),
                                    #^^^^^^^ - (A)
                ("request.META", "meta"),
            ),
            "default_values" : {
                "meta": {
                    "REMOTE_ADDR": "127.0.0.1",
                    "CONTENT_LENGTH": 0,
                }
            },
        },
    },
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "verbose",
            "filters": ["custom_filter"],
                        #^^^^^^^^^^^^^ - (B)
        },
    },
    "root": {"level": "INFO", "handlers": ["console"]},
}
```
Note that you can use any format styles(%, {, $), but should make format arguments with `str` type. For example, if you want to capture `request.user.id` as `user_id`, please follow format below.
```
%-style: %(user_id)s
{-style: {user_id}
$-style: ${user_id}
```

### ⚠️ Specifying Default Values
Default values should be provided if `capture_out` is object and its attribute can be undefined. (ex. `{meta[REMOTE_ADDR]}`)

For example, accessing request variable in filter while using scheduling cronjob(ex. `@shared_task`) can raise error because it is not HTTP request so `request` is not defined.

If `capture_out` is single value(ex. str, int, etc.), default value is not needed. It will be replaced with placeholder `-` if it is not defined.


## How to use
You can use `logger` just like before. No extra parameter is needed.

```python
import logging

from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

logger = logging.getLogger(__name__)


class ExampleView(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request, format=None):
        logger.info("example log")
        return Response({"hello": "world!"}, status=status.HTTP_200_OK)
```

```
INFO 2024-03-01 11:33:25,170 credentials 127.0.0.1 0 35052 4748750336 [USER_ID:-] Found credentials in shared credentials file: ~/.aws/credentials
INFO 2024-03-01 11:33:25,505 views 123.123.123.123 1000 35052 4748750336 [USER_ID:33] example log
```


## Supported versions
- Python: >=3.5
- Django: >=3

## License
See [LICENSE](./LICENSE)


## Contribution
Feel free to open issue or pull request.

### Contributors

<a href="https://github.com/sh-cho/django-custom-logging/graphs/contributors">
  <img src="https://contrib.rocks/image?repo=sh-cho/django-custom-logging" />
</a>

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "django-custom-logging",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.5",
    "maintainer_email": "",
    "keywords": "django,logging,middleware",
    "author": "",
    "author_email": "Seonghyeon Cho <seonghyeoncho96@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/2f/bb/3a5d29f9d2be3f77c22fe5cff42f1a801c8fce7aa44f73f01675c774ff81/django_custom_logging-0.2.1.tar.gz",
    "platform": null,
    "description": "# django-custom-logging <img src=\"https://github.com/sh-cho/django-custom-logging/assets/11611397/934a41d5-2f95-49a1-9033-294db188cbac\" width=\"250\" align=\"right\" alt=\"django-custom-logging logo\">\n\n> django middleware for custom format logging\n\n[![PyPI](https://img.shields.io/pypi/v/django-custom-logging)](https://pypi.python.org/pypi/django-custom-logging/)\n[![PyPI - License](https://img.shields.io/pypi/l/django-custom-logging)](https://github.com/sh-cho/django-custom-logging/blob/master/LICENSE)\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/django-custom-logging)](https://pypi.python.org/pypi/django-custom-logging/)\n[![PyPI - Downloads](https://img.shields.io/pypi/dm/django-custom-logging)](https://pypi.python.org/pypi/django-custom-logging/)\n![PyPI - Wheel](https://img.shields.io/pypi/wheel/django-custom-logging)\n[![Test](https://github.com/sh-cho/django-custom-logging/actions/workflows/test.yml/badge.svg?branch=develop)](https://github.com/sh-cho/django-custom-logging/actions/workflows/test.yml)\n[![Lint](https://github.com/sh-cho/django-custom-logging/actions/workflows/lint.yml/badge.svg?branch=develop)](https://github.com/sh-cho/django-custom-logging/actions/workflows/lint.yml)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n\n\n## Installation\n1. Install the package\n```sh\npython -m pip install django-custom-logging\n```\n\n2. Add adequate middlewares to `MIDDLEWARE` in setting file. Current version only supports a middleware that captures `request` into local thread(`threading.local()`)\n```python\nMIDDLEWARE = (\n    # other middlewares ...\n    \"custom_logging.middlewares.capture_request\",\n)\n```\n\n3. Add `custom_logging.filters.CustomFilter` to `LOGGING` in setting file and set `capture_list` containing a list of variables to be captured(`capture_in`) and format string to be printed(`capture_out`). Also add filter on handler's filter list.\n```python\nLOGGING = {\n    \"version\": 1,\n    \"disable_existing_loggers\": False,\n    \"formatters\": {\n        \"verbose\": {\n            \"format\": \"{levelname} {asctime} {module} {meta[REMOTE_ADDR]} {meta[CONTENT_LENGTH]} {process:d} {thread:d}\"\n                      \" [USER_ID:{user_id}] {message}\",\n                                #^^^^^^^^^ - (A)\n            \"style\": \"{\",\n        },\n    },\n    \"filters\": {\n        \"custom_filter\": {\n        #^^^^^^^^^^^^^ - (B)\n            \"()\": \"custom_logging.filters.CustomFilter\",\n            \"capture_list\": (\n                # (capture_in, capture_out)\n                (\"request.user.id\", \"user_id\"),\n                                    #^^^^^^^ - (A)\n                (\"request.META\", \"meta\"),\n            ),\n            \"default_values\" : {\n                \"meta\": {\n                    \"REMOTE_ADDR\": \"127.0.0.1\",\n                    \"CONTENT_LENGTH\": 0,\n                }\n            },\n        },\n    },\n    \"handlers\": {\n        \"console\": {\n            \"level\": \"DEBUG\",\n            \"class\": \"logging.StreamHandler\",\n            \"formatter\": \"verbose\",\n            \"filters\": [\"custom_filter\"],\n                        #^^^^^^^^^^^^^ - (B)\n        },\n    },\n    \"root\": {\"level\": \"INFO\", \"handlers\": [\"console\"]},\n}\n```\nNote that you can use any format styles(%, {, $), but should make format arguments with `str` type. For example, if you want to capture `request.user.id` as `user_id`, please follow format below.\n```\n%-style: %(user_id)s\n{-style: {user_id}\n$-style: ${user_id}\n```\n\n### \u26a0\ufe0f Specifying Default Values\nDefault values should be provided if `capture_out` is object and its attribute can be undefined. (ex. `{meta[REMOTE_ADDR]}`)\n\nFor example, accessing request variable in filter while using scheduling cronjob(ex. `@shared_task`) can raise error because it is not HTTP request so `request` is not defined.\n\nIf `capture_out` is single value(ex. str, int, etc.), default value is not needed. It will be replaced with placeholder `-` if it is not defined.\n\n\n## How to use\nYou can use `logger` just like before. No extra parameter is needed.\n\n```python\nimport logging\n\nfrom rest_framework import status\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nlogger = logging.getLogger(__name__)\n\n\nclass ExampleView(APIView):\n    permission_classes = (IsAuthenticated,)\n\n    def post(self, request, format=None):\n        logger.info(\"example log\")\n        return Response({\"hello\": \"world!\"}, status=status.HTTP_200_OK)\n```\n\n```\nINFO 2024-03-01 11:33:25,170 credentials 127.0.0.1 0 35052 4748750336 [USER_ID:-] Found credentials in shared credentials file: ~/.aws/credentials\nINFO 2024-03-01 11:33:25,505 views 123.123.123.123 1000 35052 4748750336 [USER_ID:33] example log\n```\n\n\n## Supported versions\n- Python: >=3.5\n- Django: >=3\n\n## License\nSee [LICENSE](./LICENSE)\n\n\n## Contribution\nFeel free to open issue or pull request.\n\n### Contributors\n\n<a href=\"https://github.com/sh-cho/django-custom-logging/graphs/contributors\">\n  <img src=\"https://contrib.rocks/image?repo=sh-cho/django-custom-logging\" />\n</a>\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "Django middleware for custom format logging",
    "version": "0.2.1",
    "project_urls": {
        "Documentation": "https://github.com/sh-cho/django-custom-logging#readme",
        "Issues": "https://github.com/sh-cho/django-custom-logging/issues",
        "Source": "https://github.com/sh-cho/django-custom-logging"
    },
    "split_keywords": [
        "django",
        "logging",
        "middleware"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "679b827e4269c05d0429ab3a524300246d5a66a28f3b5e726029d294c8cf2dca",
                "md5": "9671923bcec0a3fba9c8d198fd7da27f",
                "sha256": "95ebac5b5ee4fb5c392baa09657aa1e644857d9a2643f23c6d1af900da681a1f"
            },
            "downloads": -1,
            "filename": "django_custom_logging-0.2.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "9671923bcec0a3fba9c8d198fd7da27f",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.5",
            "size": 6527,
            "upload_time": "2024-03-02T07:26:01",
            "upload_time_iso_8601": "2024-03-02T07:26:01.701698Z",
            "url": "https://files.pythonhosted.org/packages/67/9b/827e4269c05d0429ab3a524300246d5a66a28f3b5e726029d294c8cf2dca/django_custom_logging-0.2.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2fbb3a5d29f9d2be3f77c22fe5cff42f1a801c8fce7aa44f73f01675c774ff81",
                "md5": "0675f3b87665d692a3d97bd803a44459",
                "sha256": "1e4064f2a31c434893e503904ce1c86c3db0bd63a000eff9ab0fb24a3a8861d2"
            },
            "downloads": -1,
            "filename": "django_custom_logging-0.2.1.tar.gz",
            "has_sig": false,
            "md5_digest": "0675f3b87665d692a3d97bd803a44459",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.5",
            "size": 5840,
            "upload_time": "2024-03-02T07:26:03",
            "upload_time_iso_8601": "2024-03-02T07:26:03.507984Z",
            "url": "https://files.pythonhosted.org/packages/2f/bb/3a5d29f9d2be3f77c22fe5cff42f1a801c8fce7aa44f73f01675c774ff81/django_custom_logging-0.2.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-02 07:26:03",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "sh-cho",
    "github_project": "django-custom-logging#readme",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "django-custom-logging"
}
        
Elapsed time: 0.34822s