【问题标题】:in python, how ensure any exceptions are logged with logger?在 python 中,如何确保使用记录器记录任何异常?
【发布时间】:2016-01-26 22:24:16
【问题描述】:

在 python 应用程序中,我如何确保 stderr 的任何内容也发送到 logger,因此,例如,如果应用程序因未捕获的异常而崩溃,我可以在日志中看到?

我当前的日志记录设置是:

logger = logging.getLogger('myapp logger')
logger.setLevel(logging.INFO)
file_log_handler = logging.FileHandler('myapp.log')
logger.addHandler(file_log_handler)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_log_handler.setFormatter(formatter)
logger.addHandler(file_log_handler)

在 python 日志记录文档中,除了如何将标准错误发送到日志文件之外,我几乎看到了所有内容。

我知道我可以将 stderr 重定向到这样的文件:

sys.stderr = open('./myapp_errors.log', 'w')

但是,我希望使用logger 记录异常,以便 (a) 格式一致,并且 (b) 我可以将异常记录到同一个文件中。

【问题讨论】:

标签: python logging stderr


【解决方案1】:

您可以覆盖sys.excepthook 成为您自己的处理程序。然后,您可以根据需要登录到自己的记录器:

import sys

def _excepthook(exctype, exc, tb):
    logger.error("An unhandled exception occurred.", exc_info=(exctype, exc, tb))

sys.excepthook = _excepthook

其实写入stderr的默认行为来自sys.excepthook的默认值。

【讨论】:

    猜你喜欢
    • 2015-11-30
    • 2013-03-26
    • 2011-05-29
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 2015-01-28
    相关资源
    最近更新 更多