如何记录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.

其他回答

我要找的是:

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

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

例子

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

./test.py 2>> mylog.log

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

./test.py &> mylog.log

我就是这么做的。

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.

您可以使用记录器在任何级别(DEBUG, INFO,…)获得跟踪。注意使用日志记录。异常时,级别为ERROR。

# test_app.py
import sys
import logging

logging.basicConfig(level="DEBUG")

def do_something():
    raise ValueError(":(")

try:
    do_something()
except Exception:
    logging.debug("Something went wrong", exc_info=sys.exc_info())
DEBUG:root:Something went wrong
Traceback (most recent call last):
  File "test_app.py", line 10, in <module>
    do_something()
  File "test_app.py", line 7, in do_something
    raise ValueError(":(")
ValueError: :(

编辑:

这也可以(使用python 3.6)

logging.debug("Something went wrong", exc_info=True)

下面是一个使用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