Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(logging): silence routine 200 access-log spam on all launch paths

Bingxi Zhao (Frank)1d9a4a904db3
diff --git a/Dockerfile b/Dockerfile
index bd6623cbd..46c2a1e83 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -246,7 +246,7 @@ echo "[Backend] πŸš€ Starting FastAPI backend on port ${BACKEND_PORT}..."
# Run uvicorn directly - the application's logging system already handles:
# 1. Console output (visible in docker logs)
# 2. File logging to data/user/logs/ai_tutor_*.log
-exec python -m uvicorn deeptutor.api.main:app --host 0.0.0.0 --port ${BACKEND_PORT}
+exec python -m uvicorn deeptutor.api.main:app --host 0.0.0.0 --port ${BACKEND_PORT} --no-access-log
EOF
RUN sed -i 's/\r$//' /app/start-backend.sh && chmod +x /app/start-backend.sh
@@ -425,7 +425,7 @@ logfile_maxbytes=0
pidfile=/var/run/supervisord.pid
[program:backend]
-command=python -m uvicorn deeptutor.api.main:app --host 0.0.0.0 --port %(ENV_BACKEND_PORT)s --reload
+command=python -m uvicorn deeptutor.api.main:app --host 0.0.0.0 --port %(ENV_BACKEND_PORT)s --reload --no-access-log
directory=/app
autostart=true
autorestart=true
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py
index 2249b9add..e90f9ab87 100644
--- a/deeptutor/api/main.py
+++ b/deeptutor/api/main.py
@@ -1,5 +1,6 @@
from contextlib import asynccontextmanager
import logging
+import sys
from fastapi import Depends, FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
@@ -226,8 +227,29 @@ app = FastAPI(
redirect_slashes=False,
)
-# Log only non-200 requests (uvicorn access_log is disabled in run_server.py)
-_access_logger = logging.getLogger("uvicorn.access")
+# Access logging is funneled through this one middleware. uvicorn's own
+# per-request access log is disabled on every launch path (run_server.py via
+# access_log=False; the launcher and Docker via `--no-access-log`), so routine
+# 200s β€” the chatty frontend polling of /settings, /tools, /knowledge/list,
+# etc. β€” never reach the logs. Only non-200s are surfaced, since those are the
+# ones worth seeing.
+#
+# The `deeptutor.access` logger gets its own INFO stdout handler rather than
+# leaning on the root handlers: the root console handler runs at the global log
+# level (WARNING by default), which would swallow these INFO access lines.
+# propagate=False keeps them from also printing through root if the global
+# level is ever lowered to INFO/DEBUG.
+_access_logger = logging.getLogger("deeptutor.access")
+if not any(
+ getattr(h, "_deeptutor_access_handler", False) for h in _access_logger.handlers
+):
+ _access_handler = logging.StreamHandler(sys.stdout)
+ _access_handler.setLevel(logging.INFO)
+ _access_handler.setFormatter(logging.Formatter("%(message)s"))
+ _access_handler._deeptutor_access_handler = True # type: ignore[attr-defined]
+ _access_logger.addHandler(_access_handler)
+ _access_logger.setLevel(logging.INFO)
+ _access_logger.propagate = False
@app.middleware("http")
diff --git a/deeptutor/runtime/launcher.py b/deeptutor/runtime/launcher.py
index c0bd6e4a2..6857f5ec1 100644
--- a/deeptutor/runtime/launcher.py
+++ b/deeptutor/runtime/launcher.py
@@ -838,6 +838,11 @@ def start(home: str | Path | None = None) -> None:
str(backend_port),
"--log-level",
"info",
+ # Disable uvicorn's per-request access log. The selective_access_log
+ # middleware (deeptutor/api/main.py) surfaces only non-200s, so routine
+ # 200 polling (/settings, /tools, /knowledge/list, ...) stays out of the
+ # logs β€” matching run_server.py's access_log=False.
+ "--no-access-log",
]
processes: list[ManagedProcess] = []
diff --git a/tests/api/test_selective_access_log.py b/tests/api/test_selective_access_log.py
index 8b68ffa7f..6eab0dea4 100644
--- a/tests/api/test_selective_access_log.py
+++ b/tests/api/test_selective_access_log.py
@@ -1,14 +1,18 @@
"""Tests for the selective_access_log middleware in main.py.
Verifies that non-200 responses are logged with the 5-element args tuple
-expected by uvicorn's AccessFormatter (client_addr, method, full_path,
-http_version, status_code), preventing the ValueError documented in #334.
+(client_addr, method, full_path, http_version, status_code) β€” the shape that
+was needed for uvicorn's AccessFormatter in #334 β€” while 200s stay silent.
+
+The real middleware logs through the ``deeptutor.access`` logger, which carries
+its own stdout handler with ``propagate=False`` (uvicorn's own access log is
+disabled on every launch path). Because it does not propagate to root, we
+capture by attaching a handler directly to that logger rather than via caplog.
"""
from __future__ import annotations
import logging
-from unittest.mock import patch
import pytest
@@ -19,11 +23,13 @@ from fastapi.testclient import TestClient
from starlette.requests import Request
from starlette.responses import JSONResponse
+ACCESS_LOGGER = "deeptutor.access"
+
def _build_app_with_middleware():
"""Build a minimal app that replicates the selective_access_log middleware."""
test_app = FastAPI()
- _access_logger = logging.getLogger("uvicorn.access")
+ _access_logger = logging.getLogger(ACCESS_LOGGER)
@test_app.middleware("http")
async def selective_access_log(request: Request, call_next):
@@ -50,19 +56,43 @@ def _build_app_with_middleware():
return test_app
+class _RecordCollector(logging.Handler):
+ """Capture emitted records directly on the access logger (no propagation)."""
+
+ def __init__(self) -> None:
+ super().__init__(level=logging.INFO)
+ self.records: list[logging.LogRecord] = []
+
+ def emit(self, record: logging.LogRecord) -> None:
+ self.records.append(record)
+
+
+class _CaptureAccess:
+ def __enter__(self) -> _RecordCollector:
+ self._logger = logging.getLogger(ACCESS_LOGGER)
+ self._handler = _RecordCollector()
+ self._prev_level = self._logger.level
+ self._logger.setLevel(logging.INFO)
+ self._logger.addHandler(self._handler)
+ return self._handler
+
+ def __exit__(self, *exc) -> None:
+ self._logger.removeHandler(self._handler)
+ self._logger.setLevel(self._prev_level)
+
+
class TestSelectiveAccessLog:
- """selective_access_log middleware must emit 5-arg tuples for uvicorn."""
+ """selective_access_log middleware must emit 5-arg tuples for the formatter."""
- def test_non_200_log_has_five_args(self, caplog):
+ def test_non_200_log_has_five_args(self):
"""Non-200 response log record args must have 5 elements (#334)."""
app = _build_app_with_middleware()
- with caplog.at_level(logging.INFO, logger="uvicorn.access"):
+ with _CaptureAccess() as cap:
with TestClient(app) as client:
client.get("/not-found")
- access_records = [r for r in caplog.records if r.name == "uvicorn.access"]
- assert len(access_records) >= 1
- record = access_records[0]
+ assert len(cap.records) >= 1
+ record = cap.records[0]
assert len(record.args) == 5, (
f"Expected 5-element args for AccessFormatter, got {len(record.args)}"
)
@@ -72,17 +102,16 @@ class TestSelectiveAccessLog:
assert http_version in ("1.0", "1.1", "2")
assert status_code == 404
- def test_200_not_logged(self, caplog):
- """200 responses should not produce uvicorn.access log records."""
+ def test_200_not_logged(self):
+ """200 responses should not produce deeptutor.access log records."""
app = _build_app_with_middleware()
- with caplog.at_level(logging.INFO, logger="uvicorn.access"):
+ with _CaptureAccess() as cap:
with TestClient(app) as client:
client.get("/ok")
- access_records = [
+ ok_records = [
r
- for r in caplog.records
- if r.name == "uvicorn.access" and hasattr(r, "args") and r.args
+ for r in cap.records
+ if r.args and len(r.args) >= 3 and "/ok" in str(r.args[2])
]
- ok_records = [r for r in access_records if len(r.args) >= 3 and "/ok" in str(r.args[2])]
assert len(ok_records) == 0