How can Django use logging to log using custom attributes in the formatter? I\'m thinking of logging the logged in username for example.
In the settings.py
You can use a filter to add your custom attribute. For example :
def add_my_custom_attribute(record):
record.myAttribute = 'myValue'
record.username = record.request.user.username
return True
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
...
'add_my_custom_attribute': {
'()': 'django.utils.log.CallbackFilter',
'callback': add_my_custom_attribute,
}
},
'handlers': {
...
'django.server': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'filters': ['add_my_custom_attribute'],
'formatter': 'django.server',
},
},
...
}
By installing a filter, you can process each log record and decide whether it should be passed from logger to handler.
The filter get the log record which contains all the details of log (i.e : time, severity, request, status code).
The attributes of the record are used by the formatter to format it to string message. If you add your custom attributes to that record - they will also be available to the formatter.