如何记录Python异常?

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

当前回答

要关闭其他可能在这里丢失的内容,在日志中捕获它的最佳方法是使用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)

其他回答

我要找的是:

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

我就是这么做的。

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)

也许没有那么时尚,但更简单:

#!/bin/bash
log="/var/log/yourlog"
/path/to/your/script.py 2>&1 | (while read; do echo "$REPLY" >> $log; done)

未捕获的异常消息将发送到STDERR,因此,您可以使用任何用于运行Python脚本的shell将STDERR发送到文件中,而不是在Python中实现日志记录。在Bash脚本中,您可以使用输出重定向来实现这一点,如Bash指南中所述。

例子

附加错误文件,其他输出到终端:

./test.py 2>> mylog.log

覆盖交错的STDOUT和STDERR输出文件:

./test.py &> mylog.log