django日志记录-django.request记录器和其他上下文 [英] django logging - django.request logger and extra context

查看:354
本文介绍了django日志记录-django.request记录器和其他上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Am on django 1.3.,python 2.6

Am on django 1.3., python 2.6

在django文档中
https://docs.djangoproject.com/en/1.3/topics/logging/#django-请求
它表示消息具有以下额外上下文:状态和请求.
您如何将它们显示在调试文件中?我在日志记录配置中尝试过类似的操作:

In the django docs here
https://docs.djangoproject.com/en/1.3/topics/logging/#django-request
it says that messages have the following extra context: status and request.
How do you get these to show up in the debug file? i tried in my logging config something like:

'formatters': {        
        'simple_debug': {
            'format': '[%(asctime)s] %(levelname)s %(module)s %(message)s %(request.user)s',        
        }
    },

但这会导致整体日志记录失败(即没有日志记录输出发生)

but that causes the overall logging to fail (i.e. no logging output happens)

因此,提交问题后,我立即遇到了这个问题: http://groups.google.com/group/django-users/browse_thread/thread/af682beb1e4af7f6/ace3338348e92a21

So immediately after submitting the question i came across this: http://groups.google.com/group/django-users/browse_thread/thread/af682beb1e4af7f6/ace3338348e92a21

有人可以帮助解释/详细说明

can someone help explain/elaborate on

文档中所有引号的真正含义是,其中的所有位置 使用django.request的django的请求,该请求是显式的 作为额外内容的一部分传递.

All the quote from the docs really means is that all the places inside of django where django.request is used, the request is explicitly passed in as part of extra.

将请求显式传递到哪里?

where is request explicitly passed in as part of extra to?

推荐答案

您不能在格式字符串中使用request.user,因为%-formatting无法处理该问题.您可以使用格式字符串,例如

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

extra dict被合并到日志事件记录中,该记录以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.

如果使用django.request记录器,则Django将在extra字典中传递status_code和请求.如果您需要request.user,则可能需要添加一个logging.Filter,其功能类似于:

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.

这篇关于django日志记录-django.request记录器和其他上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆