"""gui/components/log_writer - 线程安全的日志文件写入器 从 gui_app.py 抽出的 ThreadSafeLogWriter 类(109 行)。把 GUI 接收到的日志 行写到磁盘文件(按日期分割),用 threading.Lock 保护,配置走 read_config() / path_config / get_logs_dir。 入口:ThreadSafeLogWriter(log_dir=None),调用 .write(line) 即可。 """ from __future__ import annotations import logging import os import threading from datetime import datetime from typing import Optional from douyin.core.path_config import get_logs_dir _LOGGER = logging.getLogger("gui.components.log_writer") class ThreadSafeLogWriter: """线程安全的日志文件写入器,确保日志能稳定写入文件。 写入策略: - 配置读取走 gui.gui_core_pkg.config.read_config(避免循环依赖时延迟导入) - 日志路径默认 logs/unified.log,可配置 log_unified_path - 启用 use_dated_logs 时按 YYYY-MM-DD 后缀分割 - 每次 write() 时检查日期是否变化,自动滚动到新文件 - 行已含时间戳前缀(数字开头 + " - [" 模式)就原样写,否则补 [GUI] 前缀 """ def __init__(self, log_dir: Optional[str] = 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 @staticmethod def _read_config() -> dict: """延迟导入 read_config 避免在 gui_app 启动时形成循环依赖。""" try: from gui.gui_core_pkg.config import read_config cfg = read_config() or {} return cfg if isinstance(cfg, dict) else {} except Exception: return {} def _init_log_file(self) -> None: """初始化日志文件路径(按日期)。""" try: os.makedirs(self._log_dir, exist_ok=True) cfg = self._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" ) _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 = self._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) with open( self._log_file_path, "a", encoding="utf-8-sig", errors="replace" ) as f: # 行已包含时间戳前缀就原样写 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