Django GUID

3.5.2 · active · verified Thu Apr 16

django-guid is a Python middleware library for Django applications, enabling single request-response cycle tracing by injecting a unique ID (GUID) into project logs. It supports both ASGI and WSGI applications and includes integrations for tools like Sentry and Celery. The library is currently at version 3.5.2 and maintains an active release cadence, frequently updating to support new Django and Python versions.

Common errors

Warnings

Install

Imports

Quickstart

To quickly integrate `django-guid`, add `'django_guid'` to `INSTALLED_APPS` and `GuidMiddleware` to your `MIDDLEWARE` in `settings.py`. It's recommended to place the middleware at the top of the list. Crucially, configure your `LOGGING` dictionary to use the `django_guid.log_filters.CorrelationId` filter and include `{correlation_id}` in your formatter strings.

import logging
from django.http import HttpResponse
from django.conf import settings

# Minimal settings.py content for quickstart
settings.configure(
    INSTALLED_APPS=['django_guid'],
    MIDDLEWARE=['django_guid.middleware.GuidMiddleware'],
    LOGGING={
        'version': 1,
        'disable_existing_loggers': False,
        'filters': {
            'correlation_id': {
                '()': 'django_guid.log_filters.CorrelationId'
            }
        },
        'formatters': {
            'verbose': {
                'format': '{levelname} {asctime} {module} {process:d} {thread:d} {correlation_id} {message}',
                'style': '{',
            },
        },
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'formatter': 'verbose',
                'filters': ['correlation_id']
            },
        },
        'loggers': {
            'django': {
                'handlers': ['console'],
                'level': 'INFO',
                'propagate': True,
            },
            '': { # root logger
                'handlers': ['console'],
                'level': 'INFO',
            }
        }
    }
)

logger = logging.getLogger(__name__)

def my_view(request):
    logger.info("This log message will include the GUID.")
    return HttpResponse("Hello, world!")

# To demonstrate outside a full Django runserver context (for testing):
# from django.test import RequestFactory
# from django_guid.middleware import GuidMiddleware
# from django.urls import path
# from django.core.handlers.wsgi import WSGIRequest

# try:
#     from django.test.utils import setup_test_environment, teardown_test_environment
# except ImportError:
#     # For Django < 1.10
#     pass

# if hasattr(settings, 'configure') and settings.configured is False:
#     settings.configure(DEBUG=True)

# # Basic URLConf for demonstration
# urlpatterns = [
#     path('test-guid/', my_view),
# ]

# # Simulate a request (requires more setup for full Django context)
# # This part is illustrative; a real test suite or `python manage.py runserver` is needed.
# if __name__ == '__main__':
#     print("To run, integrate into a Django project with 'python manage.py runserver'.")
#     print("Ensure settings.py includes 'django_guid' in INSTALLED_APPS and GuidMiddleware.")
#     print("Logging configuration should apply 'correlation_id' filter as shown above.")

view raw JSON →