Configuration
Once django guid has been installed, add the following to your projects’ settings.py:
1. Installed Apps
Add django_guid to your INSTALLED_APPS:
INSTALLED_APPS = [
...
'django_guid',
]
2. Middleware
Add the django_guid.middleware.guid_middleware to your MIDDLEWARE:
MIDDLEWARE = [
'django_guid.middleware.guid_middleware',
...
]
It is recommended that you add the middleware at the top, so that the remaining middleware loggers include the requests GUID.
3. Logging Configuration
Add django_guid.log_filters.CorrelationId as a filter in your LOGGING configuration:
LOGGING = {
...
'filters': {
'correlation_id': {
'()': 'django_guid.log_filters.CorrelationId',
# You can optionally override the record field name where the guid is stored
'correlation_id_field': 'correlation_id'
}
}
}
Put that filter in your handler:
LOGGING = {
...
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'medium',
'filters': ['correlation_id'],
}
}
}
And make sure to add the new correlation_id filter to one or all of your formatters:
LOGGING = {
...
'formatters': {
'medium': {
'format': '%(levelname)s %(asctime)s [%(correlation_id)s] %(name)s %(message)s'
}
}
}
If these settings were confusing, please have a look in the demo projects’ settings.py file for a complete example.
4. Django GUID Logger (Optional)
If you wish to see the Django GUID middleware outputs, you may configure a logger for the module. Simply add django_guid to your loggers in the project, like in the example below:
LOGGING = {
...
'loggers': {
'django_guid': {
'handlers': ['console', 'logstash'],
'level': 'WARNING',
'propagate': False,
}
}
}
This is especially useful when implementing the package, if you plan to pass existing GUIDs to the middleware, as misconfigured GUIDs will not raise exceptions, but will generate warning logs.
5. Django Management commands (Optional)
There is no obvious entry point for Django management commands so GUIDs are not added to code within those commands by default. If you wish to add GUIDs to logs generated from management commands, you can use a custom base class, such as this example:
from django.core.management import BaseCommand
from django_guid.context import guid
from django_guid.utils import generate_guid
class CommandWithGUID(BaseCommand):
def handle(self, *args, **options):
guid.set(generate_guid())
self.do_task(*args, **options)
def do_task(self, *args, **options):
"""
The actual logic of the command. Subclasses must implement
this method.
"""
raise NotImplementedError(
"subclasses of CommandWithGUID must provide a do_task() method"
)
You can then inherit from this when creating your own management commands and all logs will have a GUID available. For example, if you have the class above in a file command.py in your home app:
from home.command import CommandWithGUID
class MyCommandWithGUID(CommandWithGUID):
def do_task(self, *args, **options):
"""
Add the code for your custom command here
"""
do_something()