Log exception with traceback

后端 未结 11 1181
失恋的感觉
失恋的感觉 2020-12-02 04:25

How can I log my Python errors?

try:
    do_something()
except:
    # How can I log my exception here, complete with its traceback?
11条回答
  •  悲哀的现实
    2020-12-02 05:04

    You can get the traceback using a logger, at any level (DEBUG, INFO, ...). Note that using logging.exception, the level is ERROR.

    # test_app.py
    import sys
    import logging
    
    logging.basicConfig(level="DEBUG")
    
    def do_something():
        raise ValueError(":(")
    
    try:
        do_something()
    except Exception:
        logging.debug("Something went wrong", exc_info=sys.exc_info())
    
    DEBUG:root:Something went wrong
    Traceback (most recent call last):
      File "test_app.py", line 10, in 
        do_something()
      File "test_app.py", line 7, in do_something
        raise ValueError(":(")
    ValueError: :(
    

    EDIT:

    This works too (using python 3.6)

    logging.debug("Something went wrong", exc_info=True)
    

提交回复
热议问题