How to catch and print the full exception traceback without halting/exiting the program?

后端 未结 15 2336
天命终不由人
天命终不由人 2020-11-22 13:46

I want to catch and log exceptions without exiting, e.g.,

try:
    do_stuff()
except Exception, err:
    print(Exception, err)
    # I want to print the entir         


        
15条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 13:59

    This is my solution to write the error in a log file and also on console:

    import logging, sys
    import traceback
    logging.basicConfig(filename='error.log', level=logging.DEBUG)
    
    def handle_exception(exc_type, exc_value, exc_traceback):
        import sys
        if issubclass(exc_type, KeyboardInterrupt):
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return
        exc_info=(exc_type, exc_value, exc_traceback)
        logging.critical("\nDate:" + str(datetime.datetime.now()), exc_info=(exc_type, exc_value, exc_traceback))
        print("An error occured, check error.log to see the error details")
        traceback.print_exception(*exc_info)
    
    
    sys.excepthook = handle_exception
    

提交回复
热议问题