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
script, the LOGGING variable is defined:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
},
},
'formatters' : {
'info_format' : {
'format' : '%(asctime)s %(levelname)s - %(message)s',
},
}
}
I wish to use a format, something like:
'format' : '%(asctime).19s %(levelname)s - %(username)s: %(message)s'
Where username would be the currently logged in user. Maybe any other kind of session's variables may be added here.
A workaround here is to use the extra
parameter on the logger methods, which receives a dictionary with the keys as the strings I want to use on the format string:
logger.info(message, extra={'username' : request.user.username})
Another (ugly) workaround would be to build the message attribute to include the things that are not part of the default attributes that logging formatters have.
message = request.user.username + " - " + message
logger.info(message)
But, is there a way to set up the format string with certain attributes and make Django give them automatically to the logging API? If %(username)s for example, the request.user.username, of any others perhaps...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…