python堆栈的描述_获取导致异常的异常描述和堆栈跟踪,全部为字符串

让我们创建一个非常复杂的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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值