如何配置Loguru为Alembic日志处理器解决控制台日志混打问题
Alembic配置Loguru作为日志处理器的实现方案
可行性说明
该需求完全可实现。你遇到的日志混叠问题,本质是Alembic默认使用Python标准logging模块输出日志,与Loguru为两套独立的日志输出体系,未做统一转发时就会出现格式不一致的混叠输出。
具体操作步骤
- 第一步:修改
alembic.ini配置,禁用Alembic默认日志初始化
找到配置文件中[alembic]配置段,添加如下配置,同时注释掉文件中所有loggers、handlers、formatters开头的默认日志相关配置:configure_logger = False - 第二步:编写标准logging到Loguru的转发处理器
新增如下Python代码,可放在项目公共工具模块,或直接写入Alembic的env.py文件开头:import logging from loguru import logger class InterceptHandler(logging.Handler): def emit(self, record): # 匹配对应Loguru日志级别 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()) - 第三步:根据使用场景配置日志转发
如果你是在业务代码中调用Alembic能力,在项目入口初始化日志时添加如下配置即可:
如果你是直接使用# 将标准logging的所有输出转发到Loguru logging.basicConfig(handlers=[InterceptHandler()], level=0)alembic命令行执行迁移操作,需要将如下配置添加到Alembic的env.py文件中:# 替换标准logging的默认处理器 logging.root.handlers = [InterceptHandler()] # 统一所有第三方库的日志传播规则,全部走转发到Loguru的链路 for logger_name in logging.root.manager.loggerDict.keys(): lib_logger = logging.getLogger(logger_name) lib_logger.handlers = [] lib_logger.propagate = True
效果验证
配置完成后所有日志都会统一使用Loguru的格式输出,不会再出现两种格式混叠的问题,示例输出如下:
2021-10-25 23:12:59.484 | DEBUG | __main__:main:19 - program started 2021-10-25 23:12:59.484 | INFO | alembic.runtime.migration:<module>:xx - Context impl SQLiteImpl. 2021-10-25 23:12:59.484 | INFO | alembic.runtime.migration:<module>:xx - Will assume non-transactional DDL. 2021-10-25 23:12:59.484 | DEBUG | __main__:main:19 - Hello World! 2021-10-25 23:12:59.484 | DEBUG | __main__:main:19 - program ended
内容的提问来源于stack exchange,提问作者A.B.
相关产品推荐
相关产品推荐

