[Solved]-Add timestamp and username to log

14👍

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'],
        },
    },
}

3👍

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))
👤p14z

3👍

'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.

Leave a comment