获取请求上下文以在Flask中记录错误? [英] Getting request context for error logging in Flask?

查看:179
本文介绍了获取请求上下文以在Flask中记录错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Flask教程提供了一个在发生错误时通过电子邮件发送电子邮件给自己的示例。我想从请求添加一些信息,但一直收到错误:

The Flask tutorial has an example of emailing yourself when an error occurs. I would like to add some information from request, but kept receiving an error:

RuntimeError: working outside of request context

这里是我所拥有的:

if  __name__ == '__main__':
    if not app.debug:  

        # create mail handler
        import logging
        from logging.handlers import SMTPHandler
        mail_handler = SMTPHandler('127.0.0.1',
                               'server-error@example.com',
                               ['admin@example.com'], 'YourApplication Failed')

        # Log format
        from logging import Formatter
        mail_handler.setFormatter(Formatter('''
        Message type:       %(levelname)s
        Location:           %(pathname)s:%(lineno)d
        Module:             %(module)s
        Function:           %(funcName)s
        Time:               %(asctime)s

        Message:

        %(message)s
        ''' % request.headers ))   # Added request here

        # Attach log handler to app
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)

如何获取记录的请求上下文?

How do I get the request context for logging?

推荐答案

您实际上需要向其中添加过滤器将所需的内容添加到记录器中:

You actually need to add a filter to add what you want to the logger:

import logging

class ContextualFilter(logging.Filter):
    def filter(self, log_record):
        log_record.url = request.path
        log_record.method = request.method
        log_record.ip = request.environ.get("REMOTE_ADDR")
        log_record.headers = request.headers

        return True

然后您可以在应用的记录器中注册 filter

Then you can register the filter with the app's logger:

context_provider = ContextualFilter()
app.logger.addFilter(context_provider)

并使用在格式化程序中添加到上下文的其他键:

And use the extra keys you added to the context in your formatter:

mail_handler.setFormatter(Formatter('''
    Message type:       %(levelname)s
    Location:           %(pathname)s:%(lineno)d
    Module:             %(module)s
    Function:           %(funcName)s
    Time:               %(asctime)s
    URL:                %(url)s
    Method:             %(method)s
    Headers:            %(headers)s

    Message:

    %(message)s
    '''))



为什么我不能只添加 request.headers 到我的格式化程序



两个原因:

Why can't I just add request.headers to my formatter

Two reasons:


  1. 由于没有入站请求,因此在设置记录器时没有请求上下文

  2. 即使存在,该代码也不会实际执行您想要的操作去做。设置记录器时,它将在范围内添加请求中的请求标头(因此所有请求将是第一个请求)。

另请参见: https://realpython.com/博客/ python / python-web-applications-with-flask-part-iii /

这篇关于获取请求上下文以在Flask中记录错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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