feat: timestamped log files per startup, auto-cleanup to 20 max

This commit is contained in:
2026-07-26 18:22:22 +08:00
parent 16ada23d61
commit 5d5af6b6a7
3 changed files with 29306 additions and 4 deletions
+24 -2
View File
@@ -1,18 +1,37 @@
import logging
import os
import sys
import uuid
from datetime import datetime
from logging.handlers import RotatingFileHandler
from pathlib import Path
LOG_DIR = Path(__file__).resolve().parent.parent / "logs"
LOG_DIR.mkdir(exist_ok=True)
LOG_FILE = LOG_DIR / "turbosu.log"
LOG_FORMAT = logging.Formatter(
"[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
MAX_LOG_FILES = 20
def _new_log_path() -> Path:
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
uid = uuid.uuid4().hex[:6]
return LOG_DIR / f"turbosu_{ts}_{uid}.log"
def _cleanup_old_logs():
logs = sorted(LOG_DIR.glob("turbosu_*.log*"), key=lambda p: p.stat().st_mtime)
while len(logs) > MAX_LOG_FILES:
oldest = logs.pop(0)
try:
oldest.unlink()
except OSError:
pass
def setup_logger(name: str, level: int = logging.DEBUG) -> logging.Logger:
logger = logging.getLogger(name)
@@ -20,8 +39,9 @@ def setup_logger(name: str, level: int = logging.DEBUG) -> logging.Logger:
logger.propagate = False
if not logger.handlers:
log_file = _new_log_path()
fh = RotatingFileHandler(
LOG_FILE, maxBytes=10 * 1024 * 1024, backupCount=20, encoding="utf-8"
log_file, maxBytes=10 * 1024 * 1024, backupCount=20, encoding="utf-8"
)
fh.setLevel(logging.DEBUG)
fh.setFormatter(LOG_FORMAT)
@@ -32,6 +52,8 @@ def setup_logger(name: str, level: int = logging.DEBUG) -> logging.Logger:
ch.setFormatter(LOG_FORMAT)
logger.addHandler(ch)
_cleanup_old_logs()
return logger