I am trying to add a variable to my log line through my settings.py file.
This is the code in settings (the logging part):
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'CRITICAL',
'class': 'django.utils.log.AdminEmailHandler'
},
'customhandler':{
'level':'DEBUG',
'class':'logging.RotatingFileHandler',
'formatter':'custom_format',
'filename':LOG_LOCATION
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'CRITICAL',
'propagate': True,
},
'Logger_Custom1': {
'handlers':['customhandler'],
'level':'DEBUG',
'propagate':True
},
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
'custom_format':{
'format':'[%(asctime)s %(levelname)s T:%(threadName)s F:%(funcName)s ] %(message)s '
},
}
}
The above code is working fine, but now I would like each log message to have a variable at the end. Something like:
MyVariable = "Somelines"
[%(asctime)s %(levelname)s T:%(threadName)s F:%(funcName)s ] %(message)s 'MyVariable
So my log would have that variable’s contents at the end of each logging line. I know we can do that inside the view function like this: logging.warning('% before you %','Look','Leap') But that will require us to include that line everywhere separately. Also, when we need to add or change that variable name, we will need to change that line everywhere in every file.
So I was wondering if there is any way to do that directly from settings.py, so that we can make one change and it will apply to all logging messages.
I found out the solution by myself. I don’t know if this is a good practice, but it works.
All I did was assign a variable:
And then append this variable, like this:
The output will have the variable in your log entry merged with the log format.
Thank you. Please let me know if there are more ways to do it.