Django Request Logging

0.7.5 · active · verified Thu Apr 16

Django Request Logging is a middleware for Django projects that provides intuitive and color-coded logging of HTTP request and response payloads, suitable for both web and API requests. It integrates with Django's standard logging system, allowing developers to monitor traffic and debug applications effectively. The library is currently active, with version 0.7.5 released in February 2022, and supports Django 1.8+.

Common errors

Warnings

Install

Imports

Quickstart

To quickly set up `django-request-logging`, add `request_logging.middleware.LoggingMiddleware` to your `MIDDLEWARE` list in `settings.py`. Crucially, configure your Django `LOGGING` settings to handle the `django.request` logger. This logger is where `django-request-logging` outputs its messages. Setting `propagate: False` for `django.request` prevents log messages from being handled by parent loggers and potentially duplicated. You can also use the `@no_logging` decorator on views to control logging behavior for sensitive endpoints.

import logging

# settings.py

INSTALLED_APPS = [
    # ...
    # 'request_logging', # Not strictly required, but can be added if you want to explicitly signal app presence
    # ...
]

MIDDLEWARE = [
    # ... other middleware
    'request_logging.middleware.LoggingMiddleware',
    # ... other middleware
]

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['console'],
            'level': 'DEBUG', # Change debug level as appropriate
            'propagate': False, # Important: prevent duplication if other loggers handle 'django'
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'WARNING',
    }
}

# Optional: Customize log levels for specific HTTP status codes
# REQUEST_LOGGING_HTTP_4XX_LOG_LEVEL = logging.WARNING
# REQUEST_LOGGING_DATA_LOG_LEVEL = logging.INFO
# REQUEST_LOGGING_ENABLE_COLORIZE = False # Disable color for file logging

# Example usage in a view to disable logging
from django.http import HttpResponse
from request_logging.decorators import no_logging

@no_logging()
def sensitive_view(request):
    return HttpResponse("This view's requests/responses are not logged.")

@no_logging(log_headers=False, log_body=False)
def partially_sensitive_view(request):
    return HttpResponse("This view logs only metadata, no headers or body.")

view raw JSON →