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
+1 -2
View File
@@ -34,8 +34,7 @@ Desktop.ini
.directory .directory
# Logs # Logs
logs/*.log logs/turbosu_*.log*
logs/*.log.*
# Runtime data # Runtime data
data/config.json data/config.json
+29281
View File
File diff suppressed because it is too large Load Diff
+24 -2
View File
@@ -1,18 +1,37 @@
import logging import logging
import os import os
import sys import sys
import uuid
from datetime import datetime
from logging.handlers import RotatingFileHandler from logging.handlers import RotatingFileHandler
from pathlib import Path from pathlib import Path
LOG_DIR = Path(__file__).resolve().parent.parent / "logs" LOG_DIR = Path(__file__).resolve().parent.parent / "logs"
LOG_DIR.mkdir(exist_ok=True) LOG_DIR.mkdir(exist_ok=True)
LOG_FILE = LOG_DIR / "turbosu.log"
LOG_FORMAT = logging.Formatter( LOG_FORMAT = logging.Formatter(
"[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s", "[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%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: def setup_logger(name: str, level: int = logging.DEBUG) -> logging.Logger:
logger = logging.getLogger(name) logger = logging.getLogger(name)
@@ -20,8 +39,9 @@ def setup_logger(name: str, level: int = logging.DEBUG) -> logging.Logger:
logger.propagate = False logger.propagate = False
if not logger.handlers: if not logger.handlers:
log_file = _new_log_path()
fh = RotatingFileHandler( 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.setLevel(logging.DEBUG)
fh.setFormatter(LOG_FORMAT) fh.setFormatter(LOG_FORMAT)
@@ -32,6 +52,8 @@ def setup_logger(name: str, level: int = logging.DEBUG) -> logging.Logger:
ch.setFormatter(LOG_FORMAT) ch.setFormatter(LOG_FORMAT)
logger.addHandler(ch) logger.addHandler(ch)
_cleanup_old_logs()
return logger return logger