尽早设置日志记录:在导入过程中捕获警告 [英] Set up logging early: Catch warnings emmited during importing

查看:71
本文介绍了尽早设置日志记录:在导入过程中捕获警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望通过处理日志的方式来处理所有警告.甚至这些都是在导入库时发出的.

I want all warnings to be handled by the way I want logs to be handled. Even these emitted during importing libraries.

这意味着必须在导入库之前完成日志记录的配置.

This means the configuration of the logging must be done before importing libraries.

经过一段时间的搜索,我认为在自定义sitecustomize.py中配置日志记录可能是一种解决方案.

After searching some time I think configuring logging in a custom sitecustomize.py could be a solution.

但是sitecustomize.py是黑魔法,只有很少的人知道它,甚至更少的人使用它.

But sitecustomize.py is somehow black magic only few people know it, and even less people use it.

有没有更明显的方法来确保在导入库之前完成我的日志记录配置?

Is there a more obvious way to ensure that my logging config is done before libraries get imported?

不幸的是,似乎没有办法通过环境变量配置日志记录.

Unfortunately there seems to be no way to configure logging via environment variables.

更新

根据我的观点,我没有任何可以接受的答案.我认为您需要将日志记录分为两个职责范围:​​

I got no answer which is acceptable according to my point of view. I think you need to split logging into two areas of responsibility:

  • 环境:设置日志记录:哪种格式,哪些文件...
  • 代码:使用日志记录.确实会发出信息,警告和错误消息.

第一行代码被python解释器执行后,环境"区域将负责代码.现在进行任何配置为时已晚.我希望看到将日志记录设置为调用python解释器的一部分.

As soon as the first line of code gets executed by the python interpreter, the area "environment" has given the responsibility to the code. Now it is too late to do any configuration. I would like to see setting up the logging to be a part of calling the python interpreter.

一个解决方案可能是环境变量:

One solution could be an environment variable:

PYTHON_LOGGING_CONFIG=/path-to-env/etc/config.yaml

或解释器的参数:

python --logging-config=path-to-env/etc/config.yaml script.py

推荐答案

如果想通过日志记录来涵盖导入,显然无法在导入其他任何内容之前显式配置日志记录.

There is apparently no way around explicitly configuring logging before importing anything else if you want logging to cover the imports.

但是,如果您希望日志记录配置更加明显,可以使用多种技巧来实现.例如,您的 main 脚本可能会这么短,只是为了强调特殊情况:

However, if you want logging configuration to be more obvious, there are various tricks that will help you do that. For example, your main script could be as short as this, just to emphesize the special case:

import siteconfiguration
siteconfiguration.configure_site()  # This must be done before any other import

import application


if __name__ == "__main__":
    application.run()

这仍然违反了将所有进口都放在首位的规则,但也清楚说明了这样做的原因.使用该代码的每个人都会理解您的意图.

That still breaks the rule of having all imports at the top, but it also clearly states why that is done. Everyone working with that code will understand your intentions.

特殊情况还不足以打破规则.

Special cases aren't special enough to break the rules.

尽管实用性胜过纯度.

(Tim Peters撰写的《 Python的禅宗》)

这篇关于尽早设置日志记录:在导入过程中捕获警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆