2 回答
TA贡献1853条经验 获得超6个赞
我假设 exampleFunction 位于您不拥有的一些可怕的第三方代码中,否则有很多更好的选择。
你可以做什么:
import logging # make sure this is the FIRST import of logging
import horrible_third_party_lib
def catch_log(msg):
# do something when this is called
old_logging = logging.exception
try:
logging.exception=catch_log
horrible_third_party_lib.exampleFunction()
finally:
logging.exception=old_logging
然后,您可以在函数中执行任何您想做的事情。它对导入顺序既可怕又敏感,但我已经使用了它并且它有效(scikit learn 做了类似令人反感的事情......)
TA贡献1805条经验 获得超9个赞
问题:我正在尝试捕获异常
问题标题应重写为“我正在尝试重新引发异常”
阅读Python 文档
#raise 似乎有点双重工作,但你可以这样做:
def exampleFunction():
try:
x = 1 / 0
except Exception as e:
print("logging.exception({})".format(e))
raise
try:
exampleFunction()
except ZeroDivisionError as e:
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
添加回答
举报