让我们创建一个非常复杂的stacktrace,以演示我们得到了完整的stacktrace:def raise_error():
raise RuntimeError('something bad happened!')
def do_something_that_might_error():
raise_error()
记录完整的stacktrace
最佳实践是为模块设置记录器。它将知道模块的名称并能够更改级别(以及其他属性,如处理程序)import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
我们可以使用此记录器获取错误:try:
do_something_that_might_error()
except Exception as error:
logger.exception(error)
哪些日志:ERROR:__main__:something bad happened!
Traceback (most recent call last):
File "", line 2, in
File "", line 2, in do_something_that_might_error
File "", line 2, in raise_error
RuntimeError: something bad happened!
因此,我们得到的输出与出现错误时相同:>>> do_something_that_might_error()
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in do_something_that_might_error
File "", line 2, in raise_error
RuntimeError: something bad happened!
只得到绳子
如果您真的只需要字符串,请改用traceback.format_exc函数,演示如何在此处记录字符串:import traceback
try:
do_something_that_might_error()
except Exception as error:
just_the_string = traceback.format_exc()
logger.debug(just_the_string)
哪些日志:DEBUG:__main__:Traceback (most recent call last):
File "", line 2, in
File "", line 2, in do_something_that_might_error
File "", line 2, in raise_error
RuntimeError: something bad happened!