Skip to main content

Django middleware for custom format logging

Project description

django-custom-logging

Test PyPI PyPI - Python Version PyPI - License

Django middleware for custom format logging

⚠️ Currently pre-release version is only supported.

Installation

  1. Install the package
python -m pip install django-custom-logging
  1. Add adequate middlewares to MIDDLEWARE in setting file
MIDDLEWARE = (
    # other middlewares ...
    "django-custom-logging.middleware.capture_request",
)

Available Middlewares:

  • capture_request
  • (TBD)
  1. Add custom_logging.filters.CustomFilter to LOGGING in setting file and update formatter, and add filter on handler's filter. You should put placeholder $DJANGO_CUSTOM_LOGGING in format string which will be replaced by CustomFilter.
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "verbose": {
            "format": "{levelname} {asctime} {module} {process:d} {thread:d}"
                      " $DJANGO_CUSTOM_LOGGING {message}",
            "style": "{",
        },
    },
    "filters": {
        "custom_filter": {
            "()": "custom_logging.filters.CustomFilter",
            "capture_list": (
                # (capture_in, capture_out)
                ("request.user.id", "user_id"),
            ),
        },
    },
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "verbose",
            "filters": ["custom_filter"],
        },
    },
    "root": {"level": "INFO", "handlers": ["console"]},
}

Current version only supports "{" style format.

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 2021-03-25 11:33:25,505 views 35052 4748750336 [USER_ID:33] example log

Supported versions

  • Python: >=3.6
  • Django: >=3

Project details


Download files

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

Source Distribution

django-custom-logging-0.0.1b6.tar.gz (5.6 kB view hashes)

Uploaded Source

Built Distribution

django_custom_logging-0.0.1b6-py3-none-any.whl (5.5 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page