Skip to main content

django-custom-logging django-custom-logging logo

django middleware for custom format logging

PyPI PyPI - License PyPI - Python Version PyPI - Downloads PyPI - Wheel Test Lint Code style: black

Installation

  1. Install the package
python -m pip install django-custom-logging
  1. Add adequate middlewares to MIDDLEWARE in setting file. Current version only supports a middleware that captures request into local thread(threading.local())
MIDDLEWARE = (
    # other middlewares ...
    "custom_logging.middlewares.capture_request",
)
  1. 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.
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.

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

Contribution

Feel free to open issue or pull request.

Contributors

Metadata

Release files for django-custom-logging 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-custom-logging 0.2.1
File Size Uploaded Provenance Actions
django_custom_logging-0.2.1.tar.gz 5.8 kB Without provenance Details for django_custom_logging-0.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-custom-logging 0.2.1
File Interpreter ABI Platform Actions
django_custom_logging-0.2.1-py3-none-any.whl Python 3 none any Details for django_custom_logging-0.2.1-py3-none-any.whl

Total release size: 12.4 kB

Release files / django_custom_logging-0.2.1.tar.gz

Download URL django_custom_logging-0.2.1.tar.gz
Size 5.8 kB
Tags Source
SHA-256 checksum
How to use checksums
1e4064f2a31c434893e503904ce1c86c3db0bd63a000eff9ab0fb24a3a8861d2
BLAKE2b-256 checksum
How to use checksums
2fbb3a5d29f9d2be3f77c22fe5cff42f1a801c8fce7aa44f73f01675c774ff81
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/4.0.2 CPython/3.11.8

Release files / django_custom_logging-0.2.1-py3-none-any.whl

Download URL django_custom_logging-0.2.1-py3-none-any.whl
Size 6.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
95ebac5b5ee4fb5c392baa09657aa1e644857d9a2643f23c6d1af900da681a1f
BLAKE2b-256 checksum
How to use checksums
679b827e4269c05d0429ab3a524300246d5a66a28f3b5e726029d294c8cf2dca
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/4.0.2 CPython/3.11.8

Security for django-custom-logging 0.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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