在 Python 中记录未捕获的异常 [英] Logging uncaught exceptions in Python

查看:24
本文介绍了在 Python 中记录未捕获的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我意识到最好的方法是:

尝试:raise Exception, '抛出一个无聊的异常'除了例外,e:logging.exception(e)

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

解决方案

正如 Ned 指出的那样,每次引发和未捕获异常时都会调用 sys.excepthook.这样做的实际含义是,在您的代码中,您可以覆盖 sys.excepthook 的默认行为以执行您想要的任何操作(包括使用 logging.exception).

以稻草人为例:

导入系统def foo(exctype, value, tb):print('我的错误信息')打印('类型:',exctype)打印('值:',值)打印('回溯:',tb)

覆盖sys.excepthook:

<预><代码>>>>sys.excepthook = foo

提交明显的语法错误(去掉冒号)并返回自定义错误信息:

<预><代码>>>>def bar(a, b)我的错误信息类型:值:无效语法(,第 1 行)追溯:无

有关 sys.excepthook 的更多信息,请阅读 文档.

How do you cause uncaught exceptions to output via the logging module rather than to stderr?

I realize the best way to do this would be:

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

But my situation is such that it would be really nice if logging.exception(...) were invoked automatically whenever an exception isn't caught.

解决方案

As Ned pointed out, sys.excepthook is invoked every time an exception is raised and uncaught. The practical implication of this is that in your code you can override the default behavior of sys.excepthook to do whatever you want (including using logging.exception).

As a straw man example:

import sys
def foo(exctype, value, tb):
    print('My Error Information')
    print('Type:', exctype)
    print('Value:', value)
    print('Traceback:', tb)

Override sys.excepthook:

>>> sys.excepthook = foo

Commit obvious syntax error (leave out the colon) and get back custom error information:

>>> def bar(a, b)
My Error Information
Type: <type 'exceptions.SyntaxError'>
Value: invalid syntax (<stdin>, line 1)
Traceback: None

For more information about sys.excepthook, read the docs.

这篇关于在 Python 中记录未捕获的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆