Phillip
Phillip

Reputation: 335

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

Upvotes: 12

Views: 5702

Answers (3)

Febin Stephen
Febin Stephen

Reputation: 93

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

Upvotes: 3

Endre Both
Endre Both

Reputation: 5730

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

Upvotes: 15

p14z
p14z

Reputation: 1810

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

Upvotes: 3

Related Questions