假设我正在设置一个脚本或库,该脚本或库具有一些依赖项,这些依赖项使用Python的标准库logging模块,但我希望使用loguru来捕获所有日志。我的第一次天真的尝试是完全失败的,但我不确定如何继续。
为了测试,我有两个文件
main.py
from loguru import logger
from base_log import test_func
if __name__ == "__main__":
logger.debug("In main")
test_func()和base_log.py
import logging
logger = logging.getLogger(__name__)
def test_func():
logger.warning("In test_func")如果我运行main.py (即python main.py),则会得到以下输出:
2020-12-16 10:57:48.269 | DEBUG | __main__:<module>:6 - In main
In test_func当我期望的时候:
2020-12-16 11:01:34.408 | DEBUG | __main__:<module>:6 - In main
2020-12-16 11:01:34.408 | WARNING | base_log:test_func:9 - In test_func发布于 2020-12-17 05:23:38
您可以使用自定义处理程序截获发送到您的Loguru接收器的标准日志记录消息,就像文档中记录的here一样。
然后,main.py将看起来像这样:
import logging
from loguru import logger
from base_log import test_func
class InterceptHandler(logging.Handler):
def emit(self, record):
try:
level = logger.level(record.levelname).name
except ValueError:
level = record.levelno
frame, depth = logging.currentframe(), 2
while frame.f_code.co_filename == logging.__file__:
frame = frame.f_back
depth += 1
logger.opt(depth=depth, exception=record.exc_info).log(
level, record.getMessage()
)
if __name__ == "__main__":
logging.basicConfig(handlers=[InterceptHandler()], level=0)
logger.debug("In main")
test_func()输出:
2020-12-16 22:15:55.337 | DEBUG | __main__:<module>:26 - In main
2020-12-16 22:15:55.337 | WARNING | base_log:test_func:7 - In test_func这应该适用于所有行为良好的库,这些库不会向库的记录器中添加除NullHandler之外的任何处理程序。其余的可能需要extra work.
https://stackoverflow.com/questions/65329555
复制相似问题