Getting request context for error logging in Flask?

ぃ、小莉子 提交于 2019-12-06 15:37:32

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

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

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

Two reasons:

  1. There is no request context when you're setting up the logger since no request is inbound
  2. Even if there was, that code won't actually do what you want it to do. It will add the request headers from the request in scope when you set up the logger (so all requests will be that first request).

See also: https://realpython.com/blog/python/python-web-applications-with-flask-part-iii/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!