python logging TimedRotatingFileHandler backupCount不生效问题解决

背景

在 python 开发过程中使用 logging 记录日志是很常见的做法;

但在一些情况下,由于使用 TimedRotatingFileHandler 按时间分割日志文件时设置的频率太高,

会导致 log 文件过多,从而难以查询日志结果,所以使用 backupCount 参数控制日志文件的数量。

但有时即便使用了 suffix 和 extMatch 匹配 log 文件分割时的后缀格式, backupCount 依然会不生效。

以下将记录此问题的解决过程。

错误案例

python 复制代码
import logging.handlers
import re

import datetime as dt
import time

# 格式控制器
formatter = logging.Formatter(fmt="%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s")

# 定义日志处理器console_handler
console_handler = logging.StreamHandler()

# 3.设置处理器日志级别
console_handler.setLevel(logging.DEBUG)

# 给处理器传入格式器
console_handler.setFormatter(formatter)

# 添加TimedRotatingFileHandler
timed_handler = logging.handlers.TimedRotatingFileHandler(
    filename="log/nicole.log",
    when='S',  # S秒 M分 H时 D天 W周 按时间切割 测试选用S
    interval=30,
    backupCount=4,
    encoding="utf8"
)

# 设置后缀名称
timed_handler.suffix = "%Y-%m-%d_%H-%M-%S.log"
# 正则表达式 与 suffix 格式对应
timed_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}.log$")
timed_handler.setFormatter(formatter)

timed_handler.setLevel(logging.INFO)

# 创建一个日志记录器,就是一个logger对象
logger = logging.getLogger(__name__)

# 设置logger日志记录器的日志级别为DEBUG
logger.setLevel(logging.DEBUG)

# 把两个处理器添加到日志记录器中
logger.addHandler(console_handler)
logger.addHandler(timed_handler)

for i in range(1200):
    logger.info(dt.datetime.now())
    time.sleep(1)

在大部分使用过程中,会添加 console_handler 用于在控制台打印日志;添加 timed_handler 用于生产 .log 文件打印日志;

这里的重点是 timed_handler 对象的配置;

在一般情况下,为了 log 文件命名长度会使用 .suffix 配置后缀,然后使用 .extMatch 匹配需要控制数量的 .log 文件的后缀;

期望是 .extMatch 能删除数量超过 backupCount 的文件,但多次运行后,发现文件数量并没有被控制。

extMatch匹配验证

extMatch 正则表达式能够匹配到 生成后的日志后缀

修改后代码

python 复制代码
import logging.handlers
import re

import datetime as dt
import time

# 格式控制器
formatter = logging.Formatter(fmt="%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s")

# 定义日志处理器console_handler
console_handler = logging.StreamHandler()

# 3.设置处理器日志级别
console_handler.setLevel(logging.DEBUG)

# 给处理器传入格式器
console_handler.setFormatter(formatter)

# 添加TimedRotatingFileHandler
timed_handler = logging.handlers.TimedRotatingFileHandler(
    filename="log/nicole.log",
    when='S',  # S秒 M分 H时 D天 W周 按时间切割 测试选用S
    interval=30,
    backupCount=4,
    encoding="utf8"
)

# -- 修改位置 将 suffix 和 extMatch 中的 .log 去掉,并仍然保持匹配--
# 设置后缀名称
timed_handler.suffix = "%Y-%m-%d_%H-%M-%S"
# 正则表达式 与 suffix 格式对应
timed_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")

timed_handler.setFormatter(formatter)

timed_handler.setLevel(logging.INFO)

# 创建一个日志记录器,就是一个logger对象
logger = logging.getLogger(__name__)

# 设置logger日志记录器的日志级别为DEBUG
logger.setLevel(logging.DEBUG)

# 把两个处理器添加到日志记录器中
logger.addHandler(console_handler)
logger.addHandler(timed_handler)

for i in range(1200):
    logger.info(dt.datetime.now())
    time.sleep(1)

去掉 suffix 和 extMatch里面 .log 代码重新运行,能够查看到文件数量被控制在 backupCount 内。

相关推荐
孟健8 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞10 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽12 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程17 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪17 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook17 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python