我正在尝试在我的代码中实现以下功能:
但是,在MWE中,我无法让它工作:无论我如何设置标志,我抛出的异常都没有被重新引发。
这会产生以下输出结果:
- 记录信息、错误消息和异常到控制台和/或文件,而不中断程序流程(即,吞噬异常,某种“运行模式”)
- 通过设置
develop=True
标志进入开发模式,在此模式下将引发异常
logging
模块,该模块(根据此文档)应内置了这个功能。然后标志是logging.raiseExceptions = True
。但是,在MWE中,我无法让它工作:无论我如何设置标志,我抛出的异常都没有被重新引发。
# mwe.py
import logging
import logging.config
if __name__ == '__main__':
# Configure logging and set flag to raise exceptions
logging.config.fileConfig('log.conf')
logging.raiseExceptions = True
logger = logging.getLogger('root')
logger.info('Started')
# Test whether exceptions get raised
try:
raise RuntimeError("Ooops.")
except RuntimeError:
try:
logger.exception('There was an oops.')
# which is the same as logger.error('...', exc_info=True)
except:
print("GOTCHA! Exception was re-raised.")
logger.info('Finished')
相应的配置文件:
# log.conf
[loggers]
keys=root
[handlers]
keys=consoleHandler
[formatters]
keys=consoleFormatter
[logger_root]
handlers=consoleHandler
level=DEBUG
[handler_consoleHandler]
class=logging.StreamHandler
formatter=consoleFormatter
args=(sys.stdout,)
[formatter_consoleFormatter]
format=%(filename)s (%(lineno)d) %(levelname)-8s - %(message)s
这会产生以下输出结果:
mwe.py (12) INFO - Started
mwe.py (19) ERROR - There was an oops.
Traceback (most recent call last):
File "mwe.py", line 16, in <module>
raise RuntimeError("Ooops.")
RuntimeError: Ooops.
mwe.py (24) INFO - Finished
为什么我没有进入“GOTCHA”部分,尽管raiseExceptions
的默认值为True
,而且我还将其设置为True
?我的配置有什么问题吗?
或者我对使用logging
有一些误解吗?
(小奖励问题:是否有一种方法在log.conf
文件中配置raiseException
标志?)
sys.excepthook
)...我有点困惑。 :/ - blsqrtry...except
块中使用,无需在except块中重新引发它。自定义异常也可以。 - ElmoVanKielmo