feat: timestamped log files per startup, auto-cleanup to 20 max
This commit is contained in:
+1
-2
@@ -34,8 +34,7 @@ Desktop.ini
|
||||
.directory
|
||||
|
||||
# Logs
|
||||
logs/*.log
|
||||
logs/*.log.*
|
||||
logs/turbosu_*.log*
|
||||
|
||||
# Runtime data
|
||||
data/config.json
|
||||
|
||||
+29281
File diff suppressed because it is too large
Load Diff
+24
-2
@@ -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
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user