python flask 如何记录500错误日志

生产环境配置
app.config['DEBUG'] = False

开发环境配置
app.config['DEBUG'] = True

如果生产环境发生bug,页面直接显示500错误页面了,无法像开发环境看到错误明细,定位到错误语句。

请问有什么方式可以查到出现错误的语句呢?

网上有一个方法,https://www.cnpython.com/qa/31281,但需要在每个视图中加try,对于大型网站,不实用。

下面的方法试过吗?
You want to save exception and return error page for every view. It is a lot of work to write this code everywhere. Flask provides a method to do this. Define an errorhandler method like this.

    @app.errorhandler(500)
    def internal_error(exception):
        app.logger.error(exception)
        return render_template('500.html'), 500

Whenever a view raises an exception, this method will be called and passed the exception as argument. Python logging provides exception method that is used to save full traceback of the exception.

https://stackoverflow.com/questions/14037975/how-do-i-write-flasks-excellent-debug-log-message-to-a-file-in-production

程序中对异常做处理,并将异常信息写入日志文件中,线上通过查看日志文件中的内容来排查问题。

from flask_sqlalchemy import get_debug_queries
app.config['DEBUG'] = True
queries = get_debug_queries()
for query in queries:
    print(query)
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632