如何在不停止程序的情况下打印完整的回溯?
当您不想因错误而停止程序时,您需要使用 try/except 来处理该错误:
try:
do_something_that_might_error()
except Exception as error:
handle_the_error(error)
为了提取完整的回溯,我们将使用traceback
标准库中的模块:
import traceback
并创建一个相当复杂的堆栈跟踪来证明我们获得了完整的堆栈跟踪:
def raise_error():
raise RuntimeError('something bad happened!')
def do_something_that_might_error():
raise_error()
印刷
要打印完整的回溯,请使用以下traceback.print_exc
方法:
try:
do_something_that_might_error()
except Exception as error:
traceback.print_exc()
哪个打印:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
比打印、日志记录更好:
但是,最佳实践是为您的模块设置一个记录器。它将知道模块的名称并能够更改级别(以及其他属性,例如处理程序)
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
在这种情况下,您将需要该logger.exception
函数:
try:
do_something_that_might_error()
except Exception as error:
logger.exception(error)
哪些日志:
ERROR:__main__:something bad happened!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
或者您可能只需要字符串,在这种情况下,您将需要该traceback.format_exc
函数:
try:
do_something_that_might_error()
except Exception as error:
logger.debug(traceback.format_exc())
哪些日志:
DEBUG:__main__:Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
结论
对于所有三个选项,我们看到我们得到与出现错误时相同的输出:
>>> do_something_that_might_error()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in do_something_that_might_error
File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
使用哪个
性能问题在这里并不重要,因为 IO 通常占主导地位。我更喜欢,因为它以向前兼容的方式精确地完成了请求:
logger.exception(error)
可以调整记录级别和输出,无需触摸代码即可轻松关闭。通常做直接需要的事情是最有效的方法。