fix: single log file per startup - singleton handler shared across all modules
This commit is contained in:
+22
-17
@@ -16,14 +16,29 @@ LOG_FORMAT = logging.Formatter(
|
|||||||
|
|
||||||
MAX_LOG_FILES = 20
|
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")
|
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
uid = uuid.uuid4().hex[:6]
|
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)
|
logs = sorted(LOG_DIR.glob("turbosu_*.log*"), key=lambda p: p.stat().st_mtime)
|
||||||
while len(logs) > MAX_LOG_FILES:
|
while len(logs) > MAX_LOG_FILES:
|
||||||
oldest = logs.pop(0)
|
oldest = logs.pop(0)
|
||||||
@@ -34,25 +49,15 @@ def _cleanup_old_logs():
|
|||||||
|
|
||||||
|
|
||||||
def setup_logger(name: str, level: int = logging.DEBUG) -> logging.Logger:
|
def setup_logger(name: str, level: int = logging.DEBUG) -> logging.Logger:
|
||||||
|
_init_handlers()
|
||||||
|
|
||||||
logger = logging.getLogger(name)
|
logger = logging.getLogger(name)
|
||||||
logger.setLevel(level)
|
logger.setLevel(level)
|
||||||
logger.propagate = False
|
logger.propagate = False
|
||||||
|
|
||||||
if not logger.handlers:
|
if not logger.handlers:
|
||||||
log_file = _new_log_path()
|
logger.addHandler(_root_handler)
|
||||||
fh = RotatingFileHandler(
|
logger.addHandler(_console_handler)
|
||||||
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()
|
|
||||||
|
|
||||||
return logger
|
return logger
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user