【问题标题】:logging exceptions in Python 3在 Python 3 中记录异常
【发布时间】:2019-04-09 07:26:15
【问题描述】:

我有以下:

### running with Python 3 
import logging 
logger = logging.getLogger(__name__)                                                                                                              
logger.setLevel('DEBUG')                                                                           
logger.exception('this is an exception')                                  

输出是:

this is an exception
NoneType: None

我需要做什么才能摆脱“NoneType: None”输出?

【问题讨论】:

  • logging.exception,根据the docs“只能从异常处理程序中调用。” 您要记录什么异常?
  • @jonrsharpe 呵呵,这里的文档实际上有点错误。支持使用 logging.exceptionlogging.error 传入异常实例(或元组),但他们没有记录。看起来在 Python 3 中添加了支持,但文档没有从 2.7 版本更新。

标签: python-3.x logging


【解决方案1】:

stdlib logging is trying to append the exception info,但您没有任何异常信息,因为您没有从 except: 块内登录。 NoneType: None 最终来自 sys.exc_info() 调用的结果,日志记录不会检查它们是否有效。

蹩脚的解决方法:

logger.exception('this is an exception', exc_info=False)

稍微不那么蹩脚:

logger.error('this is an exception...haha not really')

最佳:

try:
    # risky code
except Exception:
    logger.exception('this is an exception')

如果您有一个之前捕获的异常instance,并且您想要记录它,并且您不在 except 块中,那么这将做正确的事情:

logger.exception('this is an exception', exc_info=myerror)

【讨论】:

    猜你喜欢
    • 2012-07-05
    • 2014-09-11
    • 2011-10-23
    • 2011-09-08
    • 2010-12-03
    • 2020-02-27
    • 2011-03-30
    • 1970-01-01
    • 2020-12-31
    相关资源
    最近更新 更多