django logging - django.request logger and extra context

后端 未结 2 1399
感情败类
感情败类 2021-02-05 11:24

Am on django 1.3., python 2.6

In the django docs here
https://docs.djangoproject.com/en/1.3/topics/logging/#django-request
it says that messages have the followi

2条回答
  •  梦毁少年i
    2021-02-05 11:35

    You can't use request.user in the format string, as %-formatting doesn't handle that. You could use a format string such as

    '[%(asctime)s] %(levelname)s %(module)s %(message)s %(user)s'
    

    and, in your logging call, use something like

    logger.debug('My message with %s', 'args', extra={'user': request.user})
    

    The extra dict is merged into the logging event record, which ends up with a user attribute, and this then gets picked up through the format string and appears in the log.

    If using the django.request logger, the status_code and the request will be passed in the extra dict by Django. If you need the request.user, you'll probably need to add a logging.Filter which does something like:

    class RequestUserFilter(logging.Filter):
        def filter(self, record):
            record.user = record.request.user
            return True
    

    so that you can show the user in the formatted output.

提交回复
热议问题