You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

加载logging.ini配置时触发KeyError: 'formatters'问题求助

问题分析

KeyError: 'formatters'本质是logging.config.fileConfig未正确加载到目标logging.ini文件,或加载的文件内容不符合logging配置规范。核心诱因分为两类:路径计算错误导致加载无效文件,或配置文件本身格式违规。

解决方案

1. 修正配置文件路径计算逻辑

你的start_logger方法路径推导错误,导致跳出项目根目录寻找配置文件,修正如下:

def start_logger(self):
    # 获取src目录的父目录(即项目根目录)
    project_root = Path('src').resolve().parent
    # 拼接正确的配置文件路径
    config_path = project_root.joinpath('data/files/logging.ini').as_posix()
    self.setup_logger(config_path)
    self.create_log_entry(level=logging.CRITICAL, message='Starting logger')

验证方式:在setup_logger调用前添加print(config_path),确认路径指向真实存在的logging.ini文件。

2. 修复logging.ini格式错误

[handlers] section不允许存在level=DEBUG配置(该属性属于具体handler子项),移除该行:

[handlers]
keys=file, console  # 删除多余的level=DEBUG

3. 可选:添加文件存在校验

在setup_logger中增加文件存在性检查,提前捕获无效路径问题:

def setup_logger(self, config_path):
    config_file = Path(config_path)
    if not config_file.exists():
        raise FileNotFoundError(f"日志配置文件不存在:{config_file.resolve()}")
    logging.config.fileConfig(fname=config_path)
    self.main_logger = logging.getLogger('root')
排查思路
  • 优先验证路径:打印配置文件路径,手动确认文件存在且内容正确;
  • 检查配置格式:确保[loggers]/[handlers]/[formatters]主section仅包含keys字段,具体配置放在各自子section中;
  • 梳理调用顺序:确认create_log_entry调用前,start_logger已完成日志器初始化。

内容的提问来源于stack exchange,提问作者NRM_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 14:45:12