让我们创建一个相当复杂的堆栈跟踪,以证明我们获得了完整的堆栈跟踪:
def raise_error():
raise RuntimeError('something bad happened!')
def do_something_that_might_error():
raise_error()
记录完整的堆栈跟踪
最佳做法是为模块设置一个记录器。它将知道模块的名称,并能够更改级别(在其他属性(例如处理程序)中)
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 "<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!
仅获取字符串
如果您真的只想要字符串,请改用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 "<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!
log_error(err)
函数。