62 lines
1.5 KiB
Python
62 lines
1.5 KiB
Python
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_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)
|
|
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()
|
|
|
|
return logger
|
|
|
|
|
|
def get_logger(name: str) -> logging.Logger:
|
|
return setup_logger(name)
|