使用Flask的“after_request”处理程序来获取错误的追溯

时间:2015-07-22 14:32:58

标签: python flask

after_request的文档说“从Flask 0.7开始,如果发生未处理的异常,可能不会在请求结束时执行此函数。”有没有办法改变这个,所以即使对于未处理的异常,也会调用height:100%函数,例如记录回溯?

1 个答案:

答案 0 :(得分:6)

改为使用teardown_request

  

注册要在每个请求结束时运行的函数,无论是否存在异常。

     

不允许这些函数修改请求,并忽略它们的返回值。如果在处理请求时发生异常,则会将其传递给每个teardown_request函数。

from flask import Flask

app = Flask(__name__)
# unhandled teardown won't happen while in debug mode
# app.debug = True
# set this if you need the full traceback, not just the exception
# app.config['PROPAGATE_EXCEPTIONS'] = True

@app.route('/')
def index():
    print(test)

@app.teardown_request
def log_unhandled(e):
    if e is not None:
        print(repr(e))
        # app.logger.exception(e)  # only works with PROPAGATE_EXCEPTIONS

app.run('localhost')

请注意,在调用teardown_request时,回溯已超出范围;只有异常可用。您可以通过设置PROPAGATE_EXCEPTIONS = True来更改此设置,但这可能会出现性能问题。鉴于Flask已经记录了回溯,可能更容易配置日志记录而不是尝试自己记录。