Django GUID
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
-
ModuleNotFoundError: No module named 'django_guid.utils'
cause Attempting to import `guid_context` or other utilities from the deprecated `django_guid.utils` module after upgrading to `django-guid` v3.5.1 or newer.fixChange `from django_guid.utils import guid_context` (or similar) to `from django_guid.context import guid_context`. -
ImproperlyConfigured: 'django_guid' must be in your INSTALLED_APPS
cause The `django_guid` app has not been added to your `INSTALLED_APPS` list in your Django project's `settings.py` file.fixAdd `'django_guid'` to your `INSTALLED_APPS` list in `settings.py`. -
Log messages appear without the correlation_id field.
cause The `django_guid.log_filters.CorrelationId` filter is not correctly applied to your logging handlers or the formatter string does not include `{correlation_id}`.fixReview your `LOGGING` configuration in `settings.py`. Ensure that `CorrelationId` is defined as a filter, included in your desired handler(s), and that the formatter used by those handlers has `{correlation_id}` in its format string. -
Multiple versions of Django-GUID for different Django versions (e.g., 2.x.x vs 3.x.x for ASGI/WSGI)
cause Using an incorrect `django-guid` version for your Django setup (e.g., v2.x.x for Django 3.1+ with ASGI/async, which requires v3.x.x).fixRefer to the `django-guid` documentation's compatibility matrix. For Django versions 3.1.1 or above, use `django-guid` v3.x.x for both ASGI and WSGI. Older Django versions (3.0.0-3.1.0 or 2.2.x) should use v2.x.x (WSGI only).
Warnings
- breaking `django-guid` v3.4.0 introduced breaking changes by dropping support for Python 3.7 and Django versions lower than 3.2.
- gotcha The GUID will not appear in your application logs if the `CorrelationId` filter is not correctly applied to your logging handlers and formatters in `settings.py`.
- deprecated Direct access to the GUID context variable moved from `django_guid.utils.guid_context` to `django_guid.context.guid_context` in `django-guid` v3.5.1.
- gotcha When using `django-guid` with Sentry, support for Sentry SDK v2 (`sentry>2`) was added in v3.5.2 for Celery integration. Ensure compatibility if you are using older Sentry SDK versions.
- gotcha The `UUID_FORMAT` setting (introduced in v3.3.0) defaults to `hex`. If you need the standard UUID string format with hyphens (e.g., `776336d4-545e-...`), you must explicitly configure it.
Install
-
pip install django-guid
Imports
- GuidMiddleware
from django_guid.middleware import GuidMiddleware
- CorrelationId
from django_guid.log_filters import CorrelationId
- guid_context
from django_guid.utils import guid_context
from django_guid.context import guid_context
- SentryIntegration
from django_guid.integrations import SentryIntegration
- CeleryIntegration
from django_guid.integrations import CeleryIntegration
- get_guid
from django_guid.api import get_guid
Quickstart
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.")