kanban_worker_log.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """Per-task worker log rotation, split out of ``hermes_cli.kanban_db_dispatch``."""
  2. from __future__ import annotations
  3. import contextlib
  4. from pathlib import Path
  5. from typing import Optional
  6. DEFAULT_LOG_ROTATE_BYTES = 2 * 1024 * 1024 # 2 MiB
  7. DEFAULT_LOG_BACKUP_COUNT = 1
  8. def worker_log_rotation_config(kanban_cfg: Optional[dict] = None) -> tuple[int, int]:
  9. """Return ``(rotate_bytes, backup_count)`` for worker log rotation.
  10. Defaults: rotate at 2 MiB, keep one backup (``.log.1``); both overridable
  11. from ``config.yaml``.
  12. """
  13. if kanban_cfg is None:
  14. try:
  15. from hermes_cli.config import load_config
  16. kanban_cfg = (load_config().get("kanban") or {})
  17. except Exception:
  18. kanban_cfg = {}
  19. kanban_cfg = kanban_cfg or {}
  20. from hermes_cli.kanban_db_dispatch import _positive_int
  21. max_bytes = _positive_int(kanban_cfg.get("worker_log_rotate_bytes"), DEFAULT_LOG_ROTATE_BYTES, minimum=1)
  22. backup_count = _positive_int(kanban_cfg.get("worker_log_backup_count"), DEFAULT_LOG_BACKUP_COUNT, minimum=0)
  23. return max_bytes, backup_count
  24. def _rotated_log_path(log_path: Path, generation: int) -> Path:
  25. return log_path.with_suffix(log_path.suffix + f".{generation}")
  26. def rotate_worker_log(
  27. log_path: Path,
  28. max_bytes: int,
  29. backup_count: int = DEFAULT_LOG_BACKUP_COUNT,
  30. ) -> None:
  31. """Rotate ``<log>`` when it exceeds ``max_bytes``: ``<log>`` → ``<log>.1``,
  32. older generations shift up to ``backup_count``.
  33. """
  34. try:
  35. if not log_path.exists() or log_path.stat().st_size <= max_bytes:
  36. return
  37. from hermes_cli.kanban_db_dispatch import _positive_int
  38. backup_count = _positive_int(backup_count, DEFAULT_LOG_BACKUP_COUNT, minimum=0)
  39. if backup_count == 0:
  40. log_path.unlink()
  41. return
  42. oldest = _rotated_log_path(log_path, backup_count)
  43. with contextlib.suppress(OSError):
  44. if oldest.exists():
  45. oldest.unlink()
  46. for generation in range(backup_count - 1, 0, -1):
  47. src = _rotated_log_path(log_path, generation)
  48. if not src.exists():
  49. continue
  50. with contextlib.suppress(OSError):
  51. src.rename(_rotated_log_path(log_path, generation + 1))
  52. log_path.rename(_rotated_log_path(log_path, 1))
  53. except OSError:
  54. pass