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

Python3.6使用logging.config.fileConfig()报错,Python3.8可正常运行

Python3.6中logging配置加载报错KeyError: 'args'

相关代码

init.py

from logging import getLogger, config

def create_app():
    config.fileConfig("logging.ini")
    logger = getLogger("app")
    ...

run.py

from api import create_app

app = create_app()

错误信息

Traceback (most recent call last):
  File "run.py", line 12, in <module>
    app = create_app()
  File "/srv/appz/cw_tracking_v40/api/__init__.py", line 6, in create_app
    config.fileConfig("logging.ini")
  File "/usr/lib64/python3.6/logging/config.py", line 84, in fileConfig
    handlers = _install_handlers(cp, formatters)
  File "/usr/lib64/python3.6/logging/config.py", line 146, in _install_handlers
    args = section["args"]
  File "/usr/lib64/python3.6/configparser.py", line 1233, in __getitem__
    raise KeyError(key)
KeyError: 'args'

配置文件logging.ini

[loggers]
keys=root

[handlers]
keys=file

[formatters]
keys=concise

[logger_root]
level=DEBUG
handlers=file

[handler_file]
class=logging.handlers.RotatingFileHandler
level=DEBUG
formatter=concise
kwargs={"filename":"log/api.log","maxBytes":50_000_000,"backupCount":5}

[formatter_concise]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

问题原因

Python3.6的logging.config.fileConfig不支持kwargs配置项,该特性在Python3.7及以上版本才被引入;同时Python3.6也不支持数字的下划线分隔写法(如50_000_000)。

解决方案

修改logging.ini中的handler_file配置,将kwargs替换为args,并调整参数格式:

[handler_file]
class=logging.handlers.RotatingFileHandler
level=DEBUG
formatter=concise
args=("log/api.log", "a", 50000000, 5)

参数说明

args是位置参数元组,对应RotatingFileHandler的参数:

  • 第一个值:日志文件路径
  • 第二个值:文件打开模式(默认"a",可省略)
  • 第三个值:单个日志文件最大字节数
  • 第四个值:保留的备份日志文件数量

如果偏好关键字参数的写法,可改用dictConfig加载配置——将原ini配置转换为字典格式后传入config.dictConfig(),这种方式在Python3.6及以上版本都兼容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 07:52:25