feat: логирование вебхука до БД + файловый лог с ротацией
All checks were successful
CI / test (push) Successful in 47s

- Каждый входящий POST /ingress/grafana: INFO-строка (status, кол-во алертов,
  первые лейблы) и DEBUG-блок с полным JSON телом (до 8КБ)
  — видно даже если БД упала с 500
- LOG_FILE в .env / env: RotatingFileHandler 10MB×5 файлов
- LOG_LEVEL=debug теперь показывает полные тела вебхуков
- basicConfig уровень DEBUG (uvicorn.access / asyncio приглушены)

Made-with: Cursor
This commit is contained in:
Alexandr
2026-04-03 15:59:17 +03:00
parent 80645713a0
commit c9b97814a5
5 changed files with 86 additions and 8 deletions

View File

@ -78,14 +78,42 @@ class RingBufferHandler(logging.Handler):
self.handleError(record)
def install_log_handler(loop: asyncio.AbstractEventLoop) -> None:
def install_log_handler(
loop: asyncio.AbstractEventLoop,
log_file: str = "",
) -> None:
"""Вызывается один раз при старте: регистрирует handler на корневом логгере."""
set_event_loop(loop)
handler = RingBufferHandler()
handler.setFormatter(
logging.Formatter("%(name)s %(message)s")
fmt = logging.Formatter(
"%(asctime)s %(levelname)-8s %(name)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
handler.setLevel(logging.DEBUG)
root = logging.getLogger()
# Кольцевой буфер (SSE-страница логов)
if not any(isinstance(h, RingBufferHandler) for h in root.handlers):
root.addHandler(handler)
ring_h = RingBufferHandler()
ring_h.setFormatter(logging.Formatter("%(name)s %(message)s"))
ring_h.setLevel(logging.DEBUG)
root.addHandler(ring_h)
# Файл с ротацией (если задан LOG_FILE)
if log_file.strip():
import os
from logging.handlers import RotatingFileHandler
log_path = log_file.strip()
os.makedirs(os.path.dirname(log_path) if os.path.dirname(log_path) else ".", exist_ok=True)
if not any(isinstance(h, RotatingFileHandler) for h in root.handlers):
file_h = RotatingFileHandler(
log_path,
maxBytes=10 * 1024 * 1024, # 10 МБ
backupCount=5,
encoding="utf-8",
)
file_h.setFormatter(fmt)
file_h.setLevel(logging.DEBUG)
root.addHandler(file_h)
logging.getLogger("onguard24").info(
"file logging enabled: %s (rotate 10MB×5)", log_path
)