Python库中使用structlog并兼容标准库logging配置的实现咨询
Python库中使用structlog并兼容标准库logging配置的实现咨询
我正在开发一个Python库,打算用structlog来处理日志,但又想让它能自动适配宿主应用已经配置好的标准库logging设置,具体来说有两个核心需求:
- 要是宿主应用通过
logging.basicConfig之类的方式设置了日志级别,我的库得能遵守这个级别 - 要支持
pytest的标准logging fixture(包括它配置好的日志级别)
不过因为这是个库,直接修改structlog或者logging的全局配置肯定不合适。
目前我能想到的最佳方案是暴露一个公开API,大概是这样的:
import logging import structlog.stdlib def use_stdlib_logging(log_level: int|None = logging.INFO): """Configure SDK logging to use stdlib logging with the given log level. Note: this alters the default global structlog configuration. """ structlog.stdlib.recreate_defaults(log_level=log_level)
但这个方案有个问题——每个用到我这个库的应用都得记得主动调用这个API才行,如果不调用的话,我的库默认就完全无视标准库的logging配置了,这显然不够友好。
备注:内容来源于stack exchange,提问作者ncoghlan
相关产品推荐
相关产品推荐

