Python 标准库日志记录加loguru

Python 标准库日志记录加loguru,python,logging,Python,Logging,假设我正在设置一个脚本或库,它有一些依赖项,这些依赖项使用Python的标准库logging模块,但我想使用loguru捕获所有日志。我第一次天真的尝试完全失败了,但我不知道如何继续 为了测试,我有两个文件 main.py: from loguru import logger from base_log import test_func if __name__ == "__main__": logger.debug("In main")

假设我正在设置一个脚本或库,它有一些依赖项,这些依赖项使用Python的标准库
logging
模块,但我想使用
loguru
捕获所有日志。我第一次天真的尝试完全失败了,但我不知道如何继续

为了测试,我有两个文件

main.py

from loguru import logger

from base_log import test_func

if __name__ == "__main__":
    logger.debug("In main")
    test_func()
import logging

logger = logging.getLogger(__name__)


def test_func():
    logger.warning("In test_func")
base_log.py

from loguru import logger

from base_log import test_func

if __name__ == "__main__":
    logger.debug("In main")
    test_func()
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 10:57:48.269调试主站中
在测试函数中
当我期待:

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-16 11:01:34.408调试主站中
2020-12-16 11:01:34.408警告基本日志:测试功能:9-在测试功能中

您可以使用自定义处理程序截取指向Loguru接收器的标准日志消息,如文档所示

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
2020-12-16 22:15:55.337调试主站中
2020-12-16 22:15:55.337警告基本日志:测试功能:7-在测试功能中
这应该适用于所有行为良好的库,这些库不向库的记录器添加除NullHandler之外的任何处理程序。其余的可能需要