python - 在 Python 中记录未捕获的异常

如何使未捕获的异常通过 logging 模块而不是 stderr 输出?

我意识到最好的方法是:

try:
    raise Exception, 'Throwing a boring exception'
except Exception, e:
    logging.exception(e)

但我的情况是,如果 logging.exception(...) 在没有捕获到异常时自动调用,那将是非常好的

最佳答案

这是一个完整的小示例,其中还包含一些其他技巧:

import sys
import logging
logger = logging.getLogger(__name__)
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

sys.excepthook = handle_exception

if __name__ == "__main__":
    raise RuntimeError("Test unhandled")
  • 忽略键盘中断,以便控制台 python 程序可以使用 Ctrl + C 退出。

  • 完全依赖 python 的日志记录模块来格式化异常。

  • 使用带有示例处理程序的自定义记录器。这个将未处理的异常更改为转到 stdout 而不是 stderr,但您可以将相同样式的各种处理程序添加到记录器对象。

https://stackoverflow.com/questions/6234405/

相关文章:

python - boto3 客户端 NoRegionError : You must specif

python - 在 Python 中构建完整路径文件名

linux - 如何让maven构建平台独立?

linux - 亚马逊 Linux : "apt-get: command not found"

python - 从python pandas中的列名获取列索引

python - 如何检查字符串中的特定字符?

python - 如何前向声明一个函数以避免后面定义的函数出现 `NameError` s?

python - Python 3's "函数注释有什么用?

linux - 检查目录是否用 bash 挂载

linux - 如何将后台应用程序的输出重定向到/dev/null