问题描述
我有一个python控制台脚本,我不想修改该源.
I have a python console script, which source I don't want to modify.
但是我想修改由脚本及其库完成的日志记录.
But I want to modify the logging which is done by the script and its libraries.
示例:
- 我希望将错误级别为ERROR的邮件邮寄到[email protected]
- 我希望忽略文件foo.py的INFO消息.
- 我想在日志消息中包含PID.
该脚本使用此记录器:
import logging
logger=logging.getLogger(__name__)
del(logging)
如果我不想修改控制台脚本的源代码,该如何配置日志记录?
How can I configure the logging, if I don't want to modify the sources of the console script?
推荐答案
您可以使用包装脚本来加载它.在包装器中,根据需要设置日志记录配置(例如logging.basicConfig()
或根据需要添加日志记录处理程序),然后运行脚本.如果脚本具有主要功能(在脚本中查找if __name__ == "__main__":
),则只需导入文件并运行该功能:
You can load it using a wrapper script. In the wrapper, set the logging configuration as desired (e.g. logging.basicConfig()
, or add logging handlers as desired), and then run the script.
If the script has a main function (look for if __name__ == "__main__":
in the script), you can simply import the file and run the function:
import sys
import logging
logging.basicConfig(...)
import my_console_script
sys.exit(my_console_script.main())
如果它没有这样的功能,则只需将其导入即可运行其内容(您可以省略sys.exit()
调用).
If it doesn't have such a function, then simply importing it will run its contents (you can omit the sys.exit()
call).
这篇关于设置控制台脚本中的日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!