V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
whnoob
V2EX  ›  Python

求助: Python 异常信息打印

  •  
  •   whnoob · 2021-05-27 17:09:11 +08:00 · 1616 次点击
    这是一个创建于 1065 天前的主题,其中的信息可能已经有所发展或是发生改变。

    1.场景

    目前项目里采用 flask 框架做服务,用 teardown_request 做了一个简单的全局接口请求完成后的处理,示例代码如下

    def teardown_request(exception):
        db_session = g.get("pg_db")
        if db_session:
            db_session.close()
        if exception is not None:
            logging.warn(exception)
    

    2.问题

    在 teardown 钩子函数里获取了一个 exception,但是打印的时候只会显示异常的信息。想要打印完整堆栈信息的时候应该怎么处理。traceback 模块结合 try catch 挺好用的,这种场景好像和直接打印效果一样,并没有完整的堆栈,如果我想要获取 exception 这个对象的完整堆栈的话需要怎么弄,求助各位大佬。
    
    6 条回复    2021-05-27 18:00:07 +08:00
    chenqh
        1
    chenqh  
       2021-05-27 17:10:14 +08:00
    logging.warn(exception,exc_info=True)
    chenqh
        2
    chenqh  
       2021-05-27 17:11:34 +08:00
    @chenqh 或者使用第三方库, 比如 stackprinter

    ```
    from stackprinter import formatting
    logging.info(formatting.format_exc_info(*exc_info, truncate_vals=1000))

    ```

    或者用 better_exceptions
    whnoob
        3
    whnoob  
    OP
       2021-05-27 17:28:57 +08:00
    @chenqh 好的,感谢,我再试试
    Wincer
        4
    Wincer  
       2021-05-27 17:39:12 +08:00
    logging.warn 替换成 logging.exception 即可,或者像 1 楼说的
    RandomAccess
        5
    RandomAccess  
       2021-05-27 17:56:50 +08:00 via iPhone   ❤️ 1
    from trackback import format_exc
    logger.error(format_exc())
    whnoob
        6
    whnoob  
    OP
       2021-05-27 18:00:07 +08:00
    感谢各位大佬 @Wincer @RandomAccess @chenqh 后来调试之后发现是代码返回问题,导致框架层面的异常信息打印了出来,并不是具体的业务代码问题,所以没有指到具体的业务代码。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2752 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 15:23 · PVG 23:23 · LAX 08:23 · JFK 11:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.