猿问

Python:捕获 logging.exception() 调用

我试图捕捉一个没有引发的异常,只是记录了。有没有办法做到这一点?


def exampleFunction():

    try:

        x = 1 / 0

    except Exception:

        logging.exception('divide by 0 error here.')


try:

    exampleFunction()

except <condition based on if logging.exception was called>

    print('there was a divide by 0 error when I called exampleFunction()')


神不在的星期二
浏览 351回答 2
2回答

墨色风雨

我假设 exampleFunction 位于您不拥有的一些可怕的第三方代码中,否则有很多更好的选择。你可以做什么:import logging # make sure this is the FIRST import of loggingimport horrible_third_party_libdef catch_log(msg):&nbsp; &nbsp;# do something when this is calledold_logging = logging.exceptiontry:&nbsp; &nbsp; logging.exception=catch_log&nbsp; &nbsp; horrible_third_party_lib.exampleFunction()finally:&nbsp; &nbsp; logging.exception=old_logging然后,您可以在函数中执行任何您想做的事情。它对导入顺序既可怕又敏感,但我已经使用了它并且它有效(scikit learn 做了类似令人反感的事情......)

Cats萌萌

问题:我正在尝试捕获异常问题标题应重写为“我正在尝试重新引发异常”阅读Python 文档#raise 似乎有点双重工作,但你可以这样做:def exampleFunction():&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; x = 1 / 0&nbsp; &nbsp; except Exception as e:&nbsp; &nbsp; &nbsp; &nbsp; print("logging.exception({})".format(e))&nbsp; &nbsp; &nbsp; &nbsp; raisetry:&nbsp; &nbsp; exampleFunction()except ZeroDivisionError as e:&nbsp; &nbsp; print('there was a divide by 0 error when I called exampleFunction()')输出:logging.exception(division by zero)there was a divide by 0 error when I called exampleFunction()用 Python 测试:3.5.3
随时随地看视频慕课网APP

相关分类

Python
我要回答