如何在未处理的异常中使Flask记录链式异常?

时间:2017-05-09 23:18:55

标签: python-3.x logging flask error-logging

Python 3引入了异常链接,所以:

import logging

logger = logging.getLogger(__name__)

class MyException(Exception):
    pass

def blow_up():
    try:
        impossible = 42 / 0
    except ZeroDivisionError as zde:
        raise MyException('Uh oh!') from zde

try:
    blow_up()
except:
    logger.exception('It blew up!')

产生这个:

It blew up!
Traceback (most recent call last):
  File "ka-boom.py", line 10, in blow_up
    impossible = 42 / 0
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "ka-boom.py", line 15, in <module>
    blow_up()
  File "ka-boom.py", line 12, in blow_up
    raise MyException('Uh oh!') from zde
MyException: Uh oh!

但是当在Flask视图方法中抛出未处理的异常时,__cause__不会被记录,这会使调试变得困难。

我可以这样做:

@app.errorhandler(Exception)
def better_exception_handler(error):
    current_app.logger.exception('Whoopsie!')
    return 'Internal server error', 500

但我觉得很难捕捉到这样的所有例外情况,并且感觉不是很优雅。有没有办法让Flask的内置异常处理程序记录链式异常?

1 个答案:

答案 0 :(得分:1)

您能提供您正在使用的Python和Flask版本吗?使用Python 3.5.2和Flask 0.12.1,我看到你说的应该发生的事情。

from flask import Flask
app = Flask(__name__)


@app.route('/error')
def error_out():
    try:
        blow_up()
    except:
        app.logger.exception('it blew up!')
        return 'something went wrong'
    return 'everything is a-ok!'


def blow_up():
    try:
        impossible = 42 / 0
    except ZeroDivisionError as zde:
        raise MyExc('Uh oh!') from zde


class MyExc(Exception):
    pass


if __name__ == "__main__":
    app.run()

然后按我localhost:5000/error将在控制台中记录以下内容:

Seaking:flask-err rdbaker $ ~/.pyenv/versions/3.5.2/bin/python app.py 
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2017-05-15 12:19:52,229] ERROR in app: it blew up!
Traceback (most recent call last):
  File "app.py", line 21, in blow_up
    impossible = 42 / 0
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "app.py", line 12, in error_out
    blow_up()
  File "app.py", line 23, in blow_up
    raise MyExc('Uh oh!') from zde
MyExc: Uh oh!
127.0.0.1 - - [15/May/2017 12:19:52] "GET /error HTTP/1.1" 200 -

我在浏览器中看到了文字something went wrong