CodeWalk

logging.config配置实战:YAML/JSON配置与日志轮转

作者:苦行僧 · 2026-05-30 12:55

请详细介绍Python logging模块的高级配置方式,包括使用logging.config.dictConfig()加载YAML/JSON配置文件的完整示例,以及日志轮转策略(RotatingFileHandler/TimeRotatingFileHandler)的配置方法。

回答

苦行僧

字典配置(dictConfig)

最灵活的方式,可加载YAML/JSON文件:

YAML配置示例 (logging.yaml):

version: 1
formatters:
  detailed:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
  simple:
    format: '%(levelname)s: %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout
  file:
    class: logging.handlers.RotatingFileHandler
    level: INFO
    formatter: detailed
    filename: app.log
    maxBytes: 10485760  # 10MB
    backupCount: 5
    encoding: utf-8
loggers:
  myapp:
    level: DEBUG
    handlers: [console, file]
    propagate: no
root:
  level: WARNING
  handlers: [console]

加载配置

import yaml
import logging.config

with open('logging.yaml') as f:
    config = yaml.safe_load(f)
logging.config.dictConfig(config)

JSON版本同理

import json
with open('logging.json') as f:
    config = json.load(f)
logging.config.dictConfig(config)

日志轮转策略

1. RotatingFileHandler(按大小轮转)

  • maxBytes: 单个日志文件最大字节数
  • backupCount: 保留的备份文件数
  • 轮转时:app.logapp.log.1app.log.2 → ...

2. TimedRotatingFileHandler(按时间轮转)

from logging.handlers import TimedRotatingFileHandler

handler = TimedRotatingFileHandler(
    'app.log',
    when='midnight',   # 'S':秒, 'M':分, 'H':时, 'D':天, 'midnight':午夜
    interval=1,
    backupCount=30,    # 保留30天
    encoding='utf-8'
)

混合策略:同时使用大小和时间的轮转(自定义Handler或手动双重Handler)。