Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Flask's "after_request" handler to get tracebacks of errors

Tags:

python

flask

The documentation for after_request says "As of Flask 0.7 this function might not be executed at the end of the request in case an unhandled exception occurred." Is there a way to change this so after_request functions are called even for unhandled exceptions, for example to log the traceback?

like image 906
user1005909 Avatar asked Feb 09 '23 12:02

user1005909


1 Answers

Use teardown_request instead.

Register a function to be run at the end of each request, regardless of whether there was an exception or not.

These functions are not allowed to modify the request, and their return values are ignored. If an exception occurred while processing the request, it gets passed to each teardown_request function.

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

Note that by the time teardown_request is called, the traceback has already fallen out of scope; only the exception is available. You can change this by setting PROPAGATE_EXCEPTIONS = True, although this may have performance issues. Given that the traceback is logged by Flask already, it may be easier to configure logging rather than trying to log it yourself.

like image 62
davidism Avatar answered May 22 '23 22:05

davidism