Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(tray): 日志目录统一保留半年,按自然月切段

longmeidaofe06444605d2
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 1f143a2a5..72ca6ae7c 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -33,7 +33,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_interaction.py", "test_media.py", "test_previews.py",
"test_providers.py", "test_segments.py", "test_streaming.py",
"test_transcodes.py"),
- "sync": ("test_sync*.py", "test_platform.py", "test_mount.py", "test_tray.py",
+ "sync": ("test_sync*.py", "test_platform.py", "test_mount.py", "test_tray.py", "test_log_retention.py",
"test_mdns.py", "test_netwatch.py", "test_certs.py",
"test_review_mirror.py"),
"metadata": ("test_metadata*.py", "test_genre_taxonomy.py", "test_fc2*.py",
diff --git a/src/peach/log_retention.py b/src/peach/log_retention.py
new file mode 100644
index 000000000..3d154abd4
--- /dev/null
+++ b/src/peach/log_retention.py
@@ -0,0 +1,68 @@
+"""`<数据根>/logs` 里的日志统一保留半年,大小不设限。
+
+托盘子服务、首次扫描和源码同步都把 stdout 直接追加进各自的 `.log`,不经 `logging`,
+所以 `RotatingFileHandler` 用不上;这里只看文件本身的修改时间:
+
+- 半年没再写过的文件整份删掉——它里面没有一行是半年内的。
+- 还在写的文件按自然月切段:托盘启动时发现上次写入落在更早的月份,就把它改名成
+ `<名字>.until-<最后写入日期>.log`,下一次写入从空文件开始。切下来的段再等半年被第一条
+ 规则收走。
+
+只用修改时间,不用创建时间:Windows 上追加写的文件 `st_ctime` 是创建时间,macOS 是
+`st_birthtime`,Linux 常常两者都不可靠,而 `os.utime` 在三处都能改 mtime,测试才立得住。
+必须在任何子进程打开日志之前跑:Windows 上被别的进程占着的文件改不了名也删不掉。
+"""
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from pathlib import Path
+
+__all__ = ["RETENTION", "sweep"]
+
+#: 半年。
+RETENTION = timedelta(days=183)
+
+#: 切下来的段名里的标记;带它的文件不再二次切段。
+_SEGMENT_MARK = ".until-"
+
+
+def sweep(log_dir: Path, *, now: datetime | None = None) -> list[str]:
+ """按上面两条规则整理一个日志目录,返回做过的事(供日志与测试)。"""
+ if not log_dir.is_dir():
+ return []
+ moment = now or datetime.now()
+ actions: list[str] = []
+ for path in sorted(log_dir.glob("*.log")):
+ try:
+ modified = datetime.fromtimestamp(path.stat().st_mtime)
+ except OSError:
+ continue
+ if moment - modified > RETENTION:
+ try:
+ path.unlink()
+ except OSError as error:
+ actions.append(f"kept {path.name}: {error.strerror or error}")
+ continue
+ actions.append(f"deleted {path.name}")
+ continue
+ if _SEGMENT_MARK in path.name:
+ continue
+ if (modified.year, modified.month) < (moment.year, moment.month):
+ segment = path.with_name(f"{path.stem}{_SEGMENT_MARK}{modified:%Y%m%d}{path.suffix}")
+ if segment.exists():
+ # 同一天切过两次只会发生在同一秒内重启两遍;后来的这份并进去比覆盖安全。
+ try:
+ with segment.open("ab") as target, path.open("rb") as source:
+ target.write(source.read())
+ path.unlink()
+ except OSError as error:
+ actions.append(f"kept {path.name}: {error.strerror or error}")
+ continue
+ else:
+ try:
+ path.replace(segment)
+ except OSError as error:
+ actions.append(f"kept {path.name}: {error.strerror or error}")
+ continue
+ actions.append(f"rotated {path.name} -> {segment.name}")
+ return actions
diff --git a/src/peach/tray.py b/src/peach/tray.py
index 54f173fe2..ee25a0544 100644
--- a/src/peach/tray.py
+++ b/src/peach/tray.py
@@ -18,7 +18,7 @@ import httpx
import pystray
from PIL import Image
-from . import ledger_backups, onboarding, settings_file
+from . import ledger_backups, log_retention, onboarding, settings_file
from .appid import MACOS_LAUNCH_AGENT_LABEL
from .certs import ensure_certificate
from .distribution import standalone
@@ -1357,6 +1357,13 @@ def main(argv: list[str] | None = None) -> int:
return 0
try:
specs = build_setup_service_specs(config) if waiting else configured_service_specs(config)
+ # 日志按半年保留、按月切段,必须排在任何子进程打开日志之前:Windows 上被占着的
+ # 文件改不了名也删不掉。整理不了只记日志,不能因此不起托盘。
+ try:
+ for action in log_retention.sweep(config.directory("logs")):
+ logging.getLogger(__name__).info("日志整理:%s", action)
+ except Exception:
+ logging.getLogger(__name__).warning("日志整理失败", exc_info=True)
manager = ServiceManager(specs, log_dir=config.directory("logs"))
gate = SetupGate(manager, config, waiting=waiting)
if sys.platform == "darwin":
diff --git a/tests/test_log_retention.py b/tests/test_log_retention.py
new file mode 100644
index 000000000..96674f508
--- /dev/null
+++ b/tests/test_log_retention.py
@@ -0,0 +1,76 @@
+"""`peach.log_retention`:日志目录统一保留半年,按月切段,大小不设限。"""
+from __future__ import annotations
+
+import os
+import tempfile
+import unittest
+from datetime import datetime, timedelta
+from pathlib import Path
+
+from peach import log_retention
+
+NOW = datetime(2026, 9, 5, 12, 0, 0)
+
+
+def touch(path: Path, when: datetime, content: bytes = b"line\n") -> None:
+ path.write_bytes(content)
+ stamp = when.timestamp()
+ os.utime(path, (stamp, stamp))
+
+
+class SweepTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.logs = Path(self.tmp.name).resolve() / "logs"
+ self.logs.mkdir()
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def test_a_file_nobody_wrote_to_for_half_a_year_is_deleted_whole(self):
+ touch(self.logs / "tray-http.out.log", NOW - timedelta(days=184))
+ touch(self.logs / "tray-http.out.until-20260131.log", NOW - timedelta(days=200))
+ actions = log_retention.sweep(self.logs, now=NOW)
+ self.assertEqual(sorted(p.name for p in self.logs.iterdir()), [])
+ self.assertEqual(sorted(actions), ["deleted tray-http.out.log",
+ "deleted tray-http.out.until-20260131.log"])
+
+ def test_a_file_last_written_in_an_earlier_month_becomes_a_dated_segment(self):
+ touch(self.logs / "tray-https.err.log", datetime(2026, 8, 30, 23, 0), b"august\n")
+ actions = log_retention.sweep(self.logs, now=NOW)
+ self.assertEqual(actions, ["rotated tray-https.err.log -> tray-https.err.until-20260830.log"])
+ self.assertFalse((self.logs / "tray-https.err.log").exists(), "下一次写入从空文件开始")
+ self.assertEqual((self.logs / "tray-https.err.until-20260830.log").read_bytes(), b"august\n")
+
+ def test_a_file_written_this_month_stays_put(self):
+ touch(self.logs / "windows-source-sync.log", NOW - timedelta(days=3))
+ self.assertEqual(log_retention.sweep(self.logs, now=NOW), [])
+ self.assertTrue((self.logs / "windows-source-sync.log").exists())
+
+ def test_segments_are_never_cut_again_until_they_expire(self):
+ segment = self.logs / "tray-scan.out.until-20260731.log"
+ touch(segment, datetime(2026, 7, 31, 8, 0))
+ self.assertEqual(log_retention.sweep(self.logs, now=NOW), [])
+ self.assertTrue(segment.exists())
+ self.assertEqual(log_retention.sweep(self.logs, now=datetime(2027, 2, 1)),
+ ["deleted tray-scan.out.until-20260731.log"])
+
+ def test_a_second_cut_on_the_same_day_appends_instead_of_overwriting(self):
+ touch(self.logs / "tray-http.out.until-20260830.log", datetime(2026, 8, 30, 9, 0), b"first\n")
+ touch(self.logs / "tray-http.out.log", datetime(2026, 8, 30, 22, 0), b"second\n")
+ log_retention.sweep(self.logs, now=NOW)
+ self.assertEqual((self.logs / "tray-http.out.until-20260830.log").read_bytes(), b"first\nsecond\n")
+ self.assertFalse((self.logs / "tray-http.out.log").exists())
+
+ def test_only_log_files_are_touched_and_a_missing_directory_is_fine(self):
+ touch(self.logs / "peach-tray.lock", NOW - timedelta(days=400))
+ touch(self.logs / "notes.txt", NOW - timedelta(days=400))
+ self.assertEqual(log_retention.sweep(self.logs, now=NOW), [])
+ self.assertEqual(log_retention.sweep(self.logs / "absent", now=NOW), [])
+
+ def test_the_retention_is_half_a_year(self):
+ self.assertEqual(log_retention.RETENTION, timedelta(days=183))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_tray.py b/tests/test_tray.py
index c275d8f2a..9d11b9413 100644
--- a/tests/test_tray.py
+++ b/tests/test_tray.py
@@ -602,6 +602,16 @@ class SetupGateTests(unittest.TestCase):
popen.assert_not_called()
+class LogRetentionAtStartupTests(unittest.TestCase):
+ def test_the_log_sweep_runs_before_any_child_process_can_open_a_log(self):
+ """子进程以追加方式握着 `tray-*.log` 的句柄;先起服务再改名,Windows 上改名会失败,
+ POSIX 上则是段文件继续被写。所以整理必须排在 ServiceManager 之前,且失败只记警告。"""
+ source = inspect.getsource(tray_main)
+ sweep = source.index("log_retention.sweep(config.directory(\"logs\"))")
+ self.assertLess(sweep, source.index("ServiceManager(specs, log_dir="))
+ self.assertIn('warning("日志整理失败", exc_info=True)', source)
+
+
class SourceSyncTests(unittest.TestCase):
"""「同步开发进度」这条路径:拉到的代码要真的跑起来,托盘不能自己骗自己。"""