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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With