[英]Python logging. Use formatter with logging.exception()
[英]Python: Catching a logging.exception() call
我试图捕捉一个没有引发的异常,只是记录了。 有没有办法做到这一点?
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()')
我假设 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 做了类似令人反感的事情......)
问题:我正在尝试捕获异常
问题标题应改写为“我正在尝试重新提出例外”
阅读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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.