Files
douyin_guaji-main/douyin/logging/douyin_logging_pkg/handlers.py
T
CodexandClaude Opus 4.7 9d1b0c1e36 拆分 douyin_logging (1412 → 5 个子模块 + 46 行 shim)
把 douyin/logging/douyin_logging.py 按职责拆成
douyin/logging/douyin_logging_pkg/ 子包:

- _common (21)     共享全局状态:_logging_configured / _logger_cache / _log_monitor
- handlers (206)   自定义 handler:RotatingDatedFileHandler / DatedFileHandler
- cleanup (282)    日志压缩与清理:compress_log_file / cleanup_old_logs / _load_*_policy
- monitor (337)    轮转监控:LogRotationMonitor / start/stop_log_monitor / get_log_stats
- config (652)     主配置入口:get_logger / configure_logging / log_function_call /
                   LogContext / get_caller_info / format_exception_info

原文件改为 46 行 re-export shim,15 个公共符号全部保留。
全局变量统一搬到 _common,子模块通过 ``from . import _common as _state``
访问 _state.X 形式(global 不能跨模块)。

子包名 douyin_logging_pkg 是为了避免与同目录下的 shim 文件
douyin_logging.py 冲突(同名包 vs 模块在 Python 中不能并存)。

回归:
- 6 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped(含 unified_logger MDC 13 个用例)
- 旧 import 路径与新子包路径返回同一函数对象
- get_logger 缓存机制(第二次调用返回同一对象)正常工作

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 17:13:34 +08:00

207 lines
7.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""douyin_logging_pkg.handlers - 自定义日志 handler。
- RotatingDatedFileHandler 按日期 + 大小双轮转、自动压缩
- DatedFileHandler 按日期分割(兼容包装)
"""
from __future__ import annotations
import logging
import logging.handlers
import os
import threading
from datetime import datetime
from typing import Optional
class RotatingDatedFileHandler(logging.FileHandler):
"""增强的日志处理器:支持日期+大小轮转和压缩
特性:
1. 按日期分割日志文件(每天一个新文件)
2. 当文件超过大小限制时,在日期内创建序号文件(如 unified_2024-01-15.1.log)
3. 自动压缩超过保留天数的旧日志文件
4. 智能清理策略:按时间、大小、数量三重限制
"""
def __init__(
self,
base_filename: str,
date_format: str = "%Y-%m-%d",
max_bytes: int = 10 * 1024 * 1024, # 10MB
backup_count: int = 5, # 同一日期内最多保留的文件数
per_run: bool = False, # 是否为每次运行生成独立文件(包含运行时间戳)
encoding: str = "utf-8-sig",
mode: str = "a",
errors: str = "replace",
compress_old: bool = True, # 是否压缩旧日志
):
"""
参数:
base_filename: 基础文件名(不含日期和扩展名),如 "logs/unified"
date_format: 日期格式,默认 "%Y-%m-%d"
max_bytes: 单个日志文件最大大小(字节),默认100MB
backup_count: 同一日期内保留的备份文件数量,默认10
encoding: 文件编码,默认 "utf-8-sig"
mode: 打开模式,默认 "a"
errors: 错误处理,默认 "replace"
compress_old: 是否压缩旧日志,默认True
"""
self.base_filename = base_filename
self.date_format = date_format
self.max_bytes = max_bytes
self.backup_count = backup_count
self.compress_old = compress_old
self.per_run = per_run
self.current_date = datetime.now().strftime(date_format)
self.current_filename = self._get_filename_for_date(self.current_date)
self.current_sequence = 0 # 当前文件序号
self.per_run = per_run
# 确保目录存在
log_dir = os.path.dirname(self.current_filename)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
super().__init__(
self.current_filename,
mode=mode,
encoding=encoding,
errors=errors,
)
# 优化:缓存日期检查
self._date_check_counter = 0
self._last_date_check_time = datetime.now()
def _get_filename_for_date(self, date_str: str, sequence: int = 0) -> str:
"""根据日期和序号生成文件名"""
if self.per_run:
# 每次运行的文件名不再包含额外的日期字段(base_filename 已带运行时间戳)
if sequence == 0:
return f"{self.base_filename}.log"
else:
return f"{self.base_filename}.{sequence}.log"
else:
if sequence == 0:
return f"{self.base_filename}_{date_str}.log"
else:
return f"{self.base_filename}_{date_str}.{sequence}.log"
def _get_next_filename(self, date_str: str) -> str:
"""获取下一个可用的文件名"""
# 首先检查序号0的文件
filename = self._get_filename_for_date(date_str, 0)
if not os.path.exists(filename) or os.path.getsize(filename) < self.max_bytes:
return filename
# 如果序号0的文件已满,查找可用的序号
for sequence in range(1, self.backup_count + 1):
filename = self._get_filename_for_date(date_str, sequence)
if (
not os.path.exists(filename)
or os.path.getsize(filename) < self.max_bytes
):
return filename
# 如果所有序号都满了,返回最后一个(会触发覆盖最旧的)
return self._get_filename_for_date(date_str, self.backup_count)
def _rotate_file(self, date_str: str) -> None:
"""轮转到新文件"""
self.close()
# 获取新的文件名
new_filename = self._get_next_filename(date_str)
# 如果文件已存在且已满,删除最旧的文件
if (
os.path.exists(new_filename)
and os.path.getsize(new_filename) >= self.max_bytes
):
try:
os.remove(new_filename)
except Exception:
pass
self.current_filename = new_filename
# 重新初始化文件流
self.baseFilename = self.current_filename
self.stream = self._open()
def emit(self, record: logging.LogRecord) -> None:
"""发送日志记录,支持日期和大小轮转"""
# 检查是否需要日期轮转
self._check_date_rotation()
# 检查是否需要大小轮转
if self.stream and hasattr(self.stream, "tell"):
try:
current_size = self.stream.tell()
if current_size >= self.max_bytes:
self._rotate_file(self.current_date)
except Exception:
pass
super().emit(record)
def _check_date_rotation(self) -> None:
"""检查日期轮转(优化版本)"""
# 每100条记录或每1秒检查一次日期
self._date_check_counter += 1
should_check_date = (
self._date_check_counter >= 100
or (datetime.now() - self._last_date_check_time).total_seconds() >= 1.0
)
if should_check_date:
today = datetime.now().strftime(self.date_format)
self._last_date_check_time = datetime.now()
if not self.per_run and today != self.current_date:
# 日期变化,轮转到新日期(per_run 模式下不按日期轮转)
self.close()
self.current_date = today
self.current_filename = self._get_filename_for_date(self.current_date)
# 确保目录存在
log_dir = os.path.dirname(self.current_filename)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
# 重新初始化文件流
self.baseFilename = self.current_filename
self.stream = self._open()
# 重置计数器
self._date_check_counter = 0
class DatedFileHandler(RotatingDatedFileHandler):
"""兼容性类:保留原DatedFileHandler接口"""
def __init__(
self,
base_filename: str,
date_format: str = "%Y-%m-%d",
encoding: str = "utf-8-sig",
mode: str = "a",
errors: str = "replace",
):
# 为了兼容,设置较大的max_bytes(1GB)以基本只按日期分割
super().__init__(
base_filename=base_filename,
date_format=date_format,
max_bytes=1024 * 1024 * 1024, # 1GB
backup_count=1,
encoding=encoding,
mode=mode,
errors=errors,
compress_old=True,
)