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

后端 未结 15 2338
天命终不由人
天命终不由人 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 14:12

    First, don't use prints for logging, there is astable, proven and well-thought out stdlib module to do that: logging. You definitely should use it instead.

    Second, don't be tempted to do a mess with unrelated tools when there is native and simple approach. Here it is:

    log = logging.getLogger(__name__)
    
    try:
        call_code_that_fails()
    except MyError:
        log.exception('Any extra info you want to see in your logs')
    

    That's it. You are done now.

    Explanation for anyone who is interested in how things work under the hood

    What log.exception is actually doing is just a call to log.error (that is, log event with level ERROR) and print traceback then.

    Why is it better?

    Well, here is some considerations:

    • it is just right;
    • it is straightforward;
    • it is simple.

    Why should nobody use traceback or call logger with exc_info=True or get their hands dirty with sys.exc_info?

    Well, just because! They all exist for different purposes. For example, traceback.print_exc's output is a little bit different from tracebacks produced by the interpreter itself. If you use it, you will confuse anyone who reads your logs, they will be banging their heads against them.

    Passing exc_info=True to log calls is just inappropriate. But, it is useful when catching recoverable errors and you want to log them (using, e.g INFO level) with tracebacks as well, because log.exception produces logs of only one level - ERROR.

    And you definitely should avoid messing with sys.exc_info as much as you can. It's just not a public interface, it's an internal one - you can use it if you definitely know what you are doing. It is not intended for just printing exceptions.

提交回复
热议问题