如何记录Python异常?

try:
    do_something()
except:
    # How can I log my exception here, complete with its traceback?

当前回答

我就是这么做的。

try:
    do_something()
except:
    # How can I log my exception here, complete with its traceback?
    import traceback
    traceback.format_exc() # this will print a complete trace to stout.

其他回答

我就是这么做的。

try:
    do_something()
except:
    # How can I log my exception here, complete with its traceback?
    import traceback
    traceback.format_exc() # this will print a complete trace to stout.

使用exc_info选项可能更好,保留警告或错误标题:

try:
    # coode in here
except Exception as e:
    logging.error(e, exc_info=True)

要关闭其他可能在这里丢失的内容,在日志中捕获它的最佳方法是使用traceback.format_exc()调用,然后将该字符串拆分为每行,以便在生成的日志文件中捕获:

import logging
import sys
import traceback

try:
  ...
except Exception as ex:
  # could be done differently, just showing you can split it apart to capture everything individually
  ex_t = type(ex).__name__
  err = str(ex)
  err_msg = f'[{ex_t}] - {err}'
  logging.error(err_msg)

  # go through the trackback lines and individually add those to the log as an error
  for l in traceback.format_exc().splitlines():
    logging.error(l)

下面是一个使用sys.excepthook的版本

import traceback
import sys

logger = logging.getLogger()

def handle_excepthook(type, message, stack):
     logger.error(f'An unhandled exception occured: {message}. Traceback: {traceback.format_tb(stack)}')

sys.excepthook = handle_excepthook

我要找的是:

import sys
import traceback

exc_type, exc_value, exc_traceback = sys.exc_info()
traceback_in_var = traceback.format_tb(exc_traceback)

看到的:

https://docs.python.org/3/library/traceback.html