refactor(gui): 抽 ThreadSafeLogWriter 到 components/log_writer (5649 → 5537)

gui_app.py 的 ThreadSafeLogWriter 类(109 行)是自包含的日志文件写入器:
threading.Lock 保护、按日期分割、配置开关、PermissionError/Exception 兜底。

抽到 gui/components/log_writer.py,原 gui_app 中的 109 行类定义 + 1 行实例化
替换为 3 行导入 + 实例化。read_config 通过 staticmethod _read_config 延迟导入,
避免循环依赖。

新增 15 个单元测试覆盖:
- __init__:默认 log_dir / 配置开关 / dated_logs / 相对路径解析 / 配置异常兜底
- write:正常写 / 禁用跳过 / 空行跳过 / 时间戳前缀 / 已格式化行原样写
- 100 线程 × 10 行的并发安全测试(确认 1000 行无丢失)
- PermissionError / 通用异常下不抛 + warn 一次

1408 passed (+15)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-23 03:29:25 +08:00
1 parent 230c0d4049
commit fb35670032
3 files changed
+369 -112

No files matched your search

+2 -112
View File
@@ -124,118 +124,8 @@ def main():
q: queue.Queue[str] = queue.Queue()
# ========== 线程安全的日志文件写入器 ==========
class ThreadSafeLogWriter:
"""线程安全的日志文件写入器,确保日志能稳定写入文件"""
def __init__(self, log_dir: str | None = None):
self._lock = threading.Lock()
self._log_dir = log_dir or get_logs_dir()
self._log_file_path: str = ""
self._log_file_enabled: bool = True
self._init_log_file()
self._write_error_warned = False
def _init_log_file(self) -> None:
"""初始化日志文件路径(按日期)"""
try:
# 确保日志目录存在
os.makedirs(self._log_dir, exist_ok=True)
# 读取配置,检查是否启用日志文件
cfg = read_config()
self._log_file_enabled = bool(cfg.get("log_unified_enabled", True))
# 获取日志文件路径配置
log_path = cfg.get("log_unified_path") or "logs/unified.log"
if not os.path.isabs(log_path):
from douyin.core.path_config import PROJECT_ROOT
log_path = os.path.join(PROJECT_ROOT, log_path)
# 如果配置了按日期分割,使用日期后缀
use_dated_logs = cfg.get("logging", {}).get("use_dated_logs", True)
if use_dated_logs:
# 提取基础文件名(移除扩展名)
base_name = os.path.splitext(log_path)[0]
today = datetime.now().strftime("%Y-%m-%d")
self._log_file_path = f"{base_name}_{today}.log"
else:
self._log_file_path = log_path
except Exception as e:
# 如果配置读取失败,使用默认路径
today = datetime.now().strftime("%Y-%m-%d")
self._log_file_path = os.path.join(
self._log_dir, f"unified_{today}.log"
)
if not self._write_error_warned:
_LOGGER.warning("[GUI日志] 配置读取失败,使用默认路径: %s", e)
def write(self, line: str) -> None:
"""线程安全地写入日志行到文件"""
if not self._log_file_enabled:
return
if not line or not line.strip():
return
with self._lock:
try:
# 检查日期是否变化(如果使用日期日志)
cfg = read_config()
use_dated_logs = cfg.get("logging", {}).get("use_dated_logs", True)
if use_dated_logs:
today = datetime.now().strftime("%Y-%m-%d")
current_base = os.path.splitext(self._log_file_path)[0]
if not current_base.endswith(today):
# 日期变化,更新文件路径
base_name = (
current_base.rsplit("_", 1)[0]
if "_" in os.path.basename(current_base)
else current_base
)
self._log_file_path = f"{base_name}_{today}.log"
# 确保目录存在
log_dir = os.path.dirname(self._log_file_path)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
# 写入文件(追加模式,UTF-8编码,带BOM避免Windows乱码)
with open(
self._log_file_path, "a", encoding="utf-8-sig", errors="replace"
) as f:
# 如果行已经包含时间戳(格式:YYYY-MM-DD HH:MM:SS),直接写入
# 否则添加时间戳
if line.strip() and not (line[0].isdigit() and " - [" in line):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[
:-3
]
formatted_line = f"{timestamp} - [GUI] - {line}\n"
else:
formatted_line = f"{line}\n"
f.write(formatted_line)
f.flush() # 立即刷新缓冲区,确保日志及时写入磁盘
except PermissionError as e:
if not self._write_error_warned:
_LOGGER.error(
"[GUI日志] 权限错误,无法写入日志文件: %s | %s",
self._log_file_path,
e,
)
self._write_error_warned = True
except Exception as e:
if not self._write_error_warned:
_LOGGER.error(
"[GUI日志] 写入日志文件失败: %s | %s",
self._log_file_path,
e,
)
self._write_error_warned = True
# 创建日志写入器实例
# 线程安全的日志文件写入器(已抽到 gui/components/log_writer)
from gui.components.log_writer import ThreadSafeLogWriter
log_writer = ThreadSafeLogWriter()
# 日志格式化已移至模块级别函数 format_gui_log_line()