gpt4 book ai didi

python 日志记录仅在调试时打印回溯

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:38 26 4
gpt4 key购买 nike

我目前正在像这样加载 python 记录器:

import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("myprogram")

并使用它G。像这样:

[...]
except FileNotFoundError:
log.exception("could not open configuration file")
sys.exit(1)

但是,这将始终打印回溯以及错误消息:

ERROR:myprogram:could not open configuration file
Traceback (most recent call last):
[...]
FileNotFoundError: [Errno 2] No such file or directory:
'not/existing/file.yml'

我不想在正常的错误输出中回溯。相反,它应该只打印我的错误消息和异常信息(“没有这样的文件...”)。

仅当日志级别设置为 logging.DEBUG 时,推荐的显示回溯的方法是什么?

最佳答案

改为在 DEBUG 级别记录异常并设置 exc_info=Truelogger.exception() 本质上是一个 logger.error(..., exc_info=True) 调用,但您可以在任何级别记录异常回溯:

log.debug("could not open configuration file", exc_info=True)

重要的是 exc_info 选项;来自 documentation :

If exc_info does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) or an exception instance is provided, it is used; otherwise, sys.exc_info() is called to get the exception information.

您可能想使用打印(到 stdout 或 stderr)与最终用户通信:

except FileNotFoundError as e:
log.debug("could not open configuration file", exc_info=True)
print("Could not open configuration file:", e.strerror, file=sys.stderr)
sys.exit(1)

我包括了 system error message在没有 FileNotFoundError(...) 表示的打印输出中。

如果您使用命令行参数解析器,如 argparseclick,请务必使用他们的用户反馈 API(通常也包括退出)。

可以让日志记录模块也产生用户级消息,但是如果您希望单个记录器调用在文件中产生便于调试的回溯并在控制台上产生便于用户使用的输出,您必须使用自定义 Formatter() class 使用控制台处理程序为这些用例配置单独的处理程序至 override the formatException() method改变异常的显示方式。将日志记录和最终用户通信分开会更容易、更清晰。

关于python 日志记录仅在调试时打印回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52465963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com