Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add timestamp and username to log

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,
        },
    },
}
like image 320
Phillip Avatar asked Mar 26 '19 22:03

Phillip


3 Answers

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'],
        },
    },
}
like image 97
Endre Both Avatar answered Nov 18 '22 12:11

Endre Both


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))
like image 31
p14z Avatar answered Nov 18 '22 12:11

p14z


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

like image 3
Febin Stephen Avatar answered Nov 18 '22 14:11

Febin Stephen