I have setup Logging inside my settings.py, and I want to know if it's possible to add to the error log line - Which user experienced the error and a timestamp for the issue. Is this possible?
Current code
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
You can add formatters and use them in your handlers. Here is a list of available default attributes you can add, e.g. a timestamp with {asctime}
. To add the user, you'd have to supply it in the logging call as an extra argument as shown here.
LOGGING = {
'formatters': {
'timestamp': {
'format': '{asctime} {levelname} {message}',
'style': '{',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'timestamp'
},
},
'loggers': {
'django': {
'handlers': ['console'],
},
},
}
You can define a formatter for the log, for example:
'formatters': {
'verbose': {
'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
'style': '{',
}
},
To log the user that experiences the error you would have to pass the username in the message, for example in your view:
def my_view(request):
logger.error('View error for user {}'.format(request.user.username))
'formatters': {
'verbose': {
'format': '%(asctime)s; %(name)s] Message "%(message)s" from %
(pathname)s:%(lineno)d in %(funcName)s',
'datefmt': "%d/%b/%Y %H:%M:%S"
},
}
You can add new formatter with above format. it should be able to log line no. but to log username, I don't think of any other ways than manually doing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With