fix: single log file per startup - singleton handler shared across all modules

This commit is contained in:
2026-07-26 18:27:24 +08:00
parent cd2106dbf8
commit 9f009a02f5
+22 -17
View File
@@ -16,14 +16,29 @@ LOG_FORMAT = logging.Formatter(
MAX_LOG_FILES = 20
_root_handler: RotatingFileHandler | None = None
_console_handler: logging.StreamHandler | None = None
def _init_handlers():
global _root_handler, _console_handler
if _root_handler:
return
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"
log_file = LOG_DIR / f"turbosu_{ts}_{uid}.log"
_root_handler = RotatingFileHandler(
log_file, maxBytes=10 * 1024 * 1024, backupCount=20, encoding="utf-8"
)
_root_handler.setLevel(logging.DEBUG)
_root_handler.setFormatter(LOG_FORMAT)
_console_handler = logging.StreamHandler(sys.stdout)
_console_handler.setLevel(logging.INFO)
_console_handler.setFormatter(LOG_FORMAT)
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)
@@ -34,25 +49,15 @@ def _cleanup_old_logs():
def setup_logger(name: str, level: int = logging.DEBUG) -> logging.Logger:
_init_handlers()
logger = logging.getLogger(name)
logger.setLevel(level)
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"
)
fh.setLevel(logging.DEBUG)
fh.setFormatter(LOG_FORMAT)
logger.addHandler(fh)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
ch.setFormatter(LOG_FORMAT)
logger.addHandler(ch)
_cleanup_old_logs()
logger.addHandler(_root_handler)
logger.addHandler(_console_handler)
return logger