feat(logging): добавь файл ошибок с ротацией
Warning/error/critical дублируются в JSON-файл. Включается через ERROR_LOG_ENABLED, путь и минимальный уровень задаются в .env. Размер файла ограничен, старые файлы ротируются.
This commit is contained in:
1 parent
a3593e2cf1
commit
271befebbc
5 files changed
+237
-10
No files matched your search
+70
-1
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import signal
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
@@ -10,7 +11,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
import structlog
|
||||
|
||||
from src.main import _run_with_shutdown, configure_logging, main, run
|
||||
from src.main import _ErrorFileSink, _run_with_shutdown, configure_logging, main, run
|
||||
|
||||
# =========================================================================
|
||||
# Тесты configure_logging
|
||||
@@ -59,6 +60,54 @@ def test_configure_logging_processors(mocker):
|
||||
assert call_kwargs["cache_logger_on_first_use"] is True
|
||||
|
||||
|
||||
def test_configure_logging_error_file_disabled(mocker):
|
||||
configure_mock = mocker.patch("structlog.configure")
|
||||
|
||||
configure_logging(error_log_enabled=False)
|
||||
|
||||
processors = configure_mock.call_args.kwargs["processors"]
|
||||
assert not any(isinstance(processor, _ErrorFileSink) for processor in processors)
|
||||
|
||||
|
||||
def test_configure_logging_error_file_enabled(mocker, tmp_path):
|
||||
configure_mock = mocker.patch("structlog.configure")
|
||||
log_path = tmp_path / "nested" / "errors.log"
|
||||
|
||||
configure_logging(error_log_enabled=True, error_log_path=str(log_path))
|
||||
|
||||
processors = configure_mock.call_args.kwargs["processors"]
|
||||
assert any(isinstance(processor, _ErrorFileSink) for processor in processors)
|
||||
assert log_path.exists()
|
||||
|
||||
|
||||
def test_error_file_sink_writes_only_configured_levels(tmp_path):
|
||||
log_path = tmp_path / "errors.log"
|
||||
sink = _ErrorFileSink(str(log_path), logging.WARNING)
|
||||
|
||||
sink(None, "info", {"event": "skip", "level": "info"})
|
||||
sink(None, "warning", {"event": "warn", "level": "warning"})
|
||||
sink(None, "error", {"event": "boom", "level": "error"})
|
||||
|
||||
lines = log_path.read_text(encoding="utf-8").splitlines()
|
||||
payloads = [json.loads(line) for line in lines]
|
||||
|
||||
assert [payload["event"] for payload in payloads] == ["warn", "boom"]
|
||||
assert payloads[0]["level"] == "warning"
|
||||
|
||||
|
||||
def test_error_file_sink_writes_traceback(tmp_path):
|
||||
log_path = tmp_path / "errors.log"
|
||||
sink = _ErrorFileSink(str(log_path), logging.WARNING)
|
||||
|
||||
try:
|
||||
raise RuntimeError("test failure")
|
||||
except RuntimeError:
|
||||
sink(None, "error", {"event": "fail", "level": "error", "exc_info": True})
|
||||
|
||||
payload = json.loads(log_path.read_text(encoding="utf-8").splitlines()[0])
|
||||
assert "RuntimeError: test failure" in payload["exception"]
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Тесты _run_with_shutdown
|
||||
# =========================================================================
|
||||
@@ -258,3 +307,23 @@ def test_run_exits_on_fatal_error(mocker):
|
||||
run()
|
||||
|
||||
assert exc_info.value.code == 1
|
||||
|
||||
|
||||
def test_error_file_sink_rotates(tmp_path):
|
||||
log_path = tmp_path / "errors.log"
|
||||
sink = _ErrorFileSink(
|
||||
str(log_path),
|
||||
logging.WARNING,
|
||||
max_bytes=200,
|
||||
backup_count=1,
|
||||
)
|
||||
|
||||
for _ in range(20):
|
||||
sink(
|
||||
None,
|
||||
"error",
|
||||
{"event": "e" * 50, "level": "error", "timestamp": "2026-01-01T00:00:00Z"},
|
||||
)
|
||||
|
||||
assert log_path.exists()
|
||||
assert (tmp_path / "errors.log.1").exists()
|
||||
Reference in new issue
Block a user