diff --git a/gui/components/log_writer.py b/gui/components/log_writer.py new file mode 100644 index 0000000..4a3de60 --- /dev/null +++ b/gui/components/log_writer.py @@ -0,0 +1,134 @@ +"""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 diff --git a/gui/gui_app.py b/gui/gui_app.py index 8da2544..731f9ac 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -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() diff --git a/tests/test_log_writer.py b/tests/test_log_writer.py new file mode 100644 index 0000000..131cf03 --- /dev/null +++ b/tests/test_log_writer.py @@ -0,0 +1,233 @@ +"""gui/components/log_writer 单元测试。 + +ThreadSafeLogWriter 写日志文件 + 配置开关 + 日期分割。 +所有测试用 tmp_path 隔离,避免污染真实 logs/ 目录。 +""" +from __future__ import annotations + +import os +import threading +from datetime import datetime +from pathlib import Path +from unittest.mock import patch + +import pytest + +from gui.components.log_writer import ThreadSafeLogWriter + + +def _patch_config(monkeypatch, cfg): + """让 _read_config 返回指定 cfg。""" + monkeypatch.setattr( + ThreadSafeLogWriter, "_read_config", staticmethod(lambda: cfg) + ) + + +# ============================================================ +# __init__ / _init_log_file +# ============================================================ + +class TestInit: + def test_default_log_dir_used_when_none(self, tmp_path, monkeypatch): + _patch_config(monkeypatch, {"log_unified_enabled": True}) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + assert writer._log_dir == str(tmp_path) + assert writer._log_file_enabled is True + + def test_log_unified_enabled_false(self, tmp_path, monkeypatch): + _patch_config(monkeypatch, {"log_unified_enabled": False}) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + assert writer._log_file_enabled is False + + def test_dated_logs_default_appends_today(self, tmp_path, monkeypatch): + _patch_config(monkeypatch, { + "log_unified_path": str(tmp_path / "test.log"), + "logging": {"use_dated_logs": True}, + }) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + today = datetime.now().strftime("%Y-%m-%d") + assert writer._log_file_path.endswith(f"_{today}.log") + + def test_dated_logs_disabled_keeps_path(self, tmp_path, monkeypatch): + path = str(tmp_path / "test.log") + _patch_config(monkeypatch, { + "log_unified_path": path, + "logging": {"use_dated_logs": False}, + }) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + assert writer._log_file_path == path + + def test_relative_path_resolved_to_project_root(self, tmp_path, monkeypatch): + _patch_config(monkeypatch, { + "log_unified_path": "logs/relative.log", + "logging": {"use_dated_logs": False}, + }) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + # 路径应该是绝对的(拼到 PROJECT_ROOT) + assert os.path.isabs(writer._log_file_path) + assert "relative.log" in writer._log_file_path + + def test_config_read_failure_falls_back_to_default(self, tmp_path, monkeypatch): + """模拟配置读取抛异常,仍能初始化(用兜底路径)。""" + def broken_config(): + raise RuntimeError("config broken") + monkeypatch.setattr( + ThreadSafeLogWriter, "_read_config", + staticmethod(broken_config), + ) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + # 应该用兜底路径,包含 unified_<日期>.log + today = datetime.now().strftime("%Y-%m-%d") + assert f"unified_{today}.log" in writer._log_file_path + + +# ============================================================ +# write +# ============================================================ + +class TestWrite: + def test_write_appends_to_file(self, tmp_path, monkeypatch): + _patch_config(monkeypatch, { + "log_unified_enabled": True, + "log_unified_path": str(tmp_path / "test.log"), + "logging": {"use_dated_logs": False}, + }) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + writer.write("hello") + writer.write("world") + with open(writer._log_file_path, "r", encoding="utf-8-sig") as f: + content = f.read() + assert "hello" in content + assert "world" in content + + def test_write_disabled_skips(self, tmp_path, monkeypatch): + _patch_config(monkeypatch, { + "log_unified_enabled": False, + "log_unified_path": str(tmp_path / "test.log"), + "logging": {"use_dated_logs": False}, + }) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + writer.write("should not appear") + assert not os.path.exists(writer._log_file_path) + + def test_write_empty_line_skipped(self, tmp_path, monkeypatch): + _patch_config(monkeypatch, { + "log_unified_enabled": True, + "log_unified_path": str(tmp_path / "test.log"), + "logging": {"use_dated_logs": False}, + }) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + writer.write("") + writer.write(" ") + # 文件可能根本没创建,或者创建了但空(tolerate both) + if os.path.exists(writer._log_file_path): + with open(writer._log_file_path, "r", encoding="utf-8-sig") as f: + content = f.read() + assert content.strip() == "" + + def test_write_adds_timestamp_prefix(self, tmp_path, monkeypatch): + _patch_config(monkeypatch, { + "log_unified_enabled": True, + "log_unified_path": str(tmp_path / "test.log"), + "logging": {"use_dated_logs": False}, + }) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + writer.write("plain message") + with open(writer._log_file_path, "r", encoding="utf-8-sig") as f: + content = f.read() + # 应含 [GUI] 前缀和时间戳 + assert "[GUI]" in content + assert "plain message" in content + + def test_write_preserves_existing_timestamp(self, tmp_path, monkeypatch): + """已含 'YYYY-MM-DD HH:MM:SS - [' 前缀的行应原样写。""" + _patch_config(monkeypatch, { + "log_unified_enabled": True, + "log_unified_path": str(tmp_path / "test.log"), + "logging": {"use_dated_logs": False}, + }) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + # 行以数字开头 + " - [" 模式 → 不再加前缀 + writer.write("2026-05-22 12:00:00 - [INFO] - already formatted") + with open(writer._log_file_path, "r", encoding="utf-8-sig") as f: + content = f.read() + # [GUI] 不应出现 + assert "[GUI]" not in content + assert "[INFO] - already formatted" in content + + +# ============================================================ +# 线程安全 +# ============================================================ + +class TestThreadSafety: + def test_concurrent_writes_no_loss(self, tmp_path, monkeypatch): + """100 线程并发写各 10 行,最终文件应有 1000 行。""" + _patch_config(monkeypatch, { + "log_unified_enabled": True, + "log_unified_path": str(tmp_path / "concurrent.log"), + "logging": {"use_dated_logs": False}, + }) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + + def worker(thread_id: int): + for i in range(10): + writer.write(f"thread-{thread_id}-line-{i}") + + threads = [threading.Thread(target=worker, args=(i,)) for i in range(100)] + for t in threads: + t.start() + for t in threads: + t.join() + + with open(writer._log_file_path, "r", encoding="utf-8-sig") as f: + content = f.read() + # 1000 行(每个非空) + non_empty_lines = [ln for ln in content.splitlines() if ln.strip()] + assert len(non_empty_lines) == 1000 + + +# ============================================================ +# 错误兜底 +# ============================================================ + +class TestErrorHandling: + def test_permission_error_does_not_crash(self, tmp_path, monkeypatch, caplog): + _patch_config(monkeypatch, { + "log_unified_enabled": True, + "log_unified_path": str(tmp_path / "test.log"), + "logging": {"use_dated_logs": False}, + }) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + + with patch("builtins.open", side_effect=PermissionError("no perms")): + # 不应抛 + writer.write("hello") + assert writer._write_error_warned is True + + def test_generic_exception_does_not_crash(self, tmp_path, monkeypatch): + _patch_config(monkeypatch, { + "log_unified_enabled": True, + "log_unified_path": str(tmp_path / "test.log"), + "logging": {"use_dated_logs": False}, + }) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + + with patch("builtins.open", side_effect=RuntimeError("disk full")): + writer.write("hello") + assert writer._write_error_warned is True + + def test_error_only_warns_once(self, tmp_path, monkeypatch): + """重复出错时 _write_error_warned 永久 True,避免日志噪音。""" + _patch_config(monkeypatch, { + "log_unified_enabled": True, + "log_unified_path": str(tmp_path / "test.log"), + "logging": {"use_dated_logs": False}, + }) + writer = ThreadSafeLogWriter(log_dir=str(tmp_path)) + writer._write_error_warned = True + + with patch("builtins.open", side_effect=PermissionError): + writer.write("hello") + # 仍是 True + assert writer._write_error_warned is True