How to print an exception in Python 3?

前端 未结 7 2110
有刺的猬
有刺的猬 2021-01-31 13:48

Right now, I catch the exception in the except Exception: clause, and do print(exception). The result provides no information since it always prints

7条回答
  •  深忆病人
    2021-01-31 14:41

    Here is the way I like that prints out all of the error stack.

    import logging
    
    try:
        1 / 0
    except Exception as _e:
        # any one of the follows:
        # print(logging.traceback.format_exc())
        logging.error(logging.traceback.format_exc())
    

    The output looks as the follows:

    ERROR:root:Traceback (most recent call last):
      File "/PATH-TO-YOUR/filename.py", line 4, in 
        1 / 0
    ZeroDivisionError: division by zero
    

    LOGGING_FORMAT :

    LOGGING_FORMAT = '%(asctime)s\n  File "%(pathname)s", line %(lineno)d\n  %(levelname)s [%(message)s]'
    

提交回复
热议问题