mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-07 02:48:05 +08:00
fix(logging): silence routine 200 access-log spam on all launch paths
The backend was logging every request (the chatty frontend polling of /settings, /tools, /knowledge/list, /settings/llm-options, ...) as `::1:0 - "GET ... 200 OK"`. uvicorn's per-request access log was only disabled in run_server.py (access_log=False); the `deeptutor start` launcher and the Docker entrypoints invoked uvicorn directly with it still on, so the 200s leaked. - launcher.py + Dockerfile (production start-backend.sh and the dev supervisord program): add `--no-access-log` so all launch paths match run_server.py. - Funnel access logging through the existing selective_access_log middleware (non-200 only), but log via a `deeptutor.access` logger with its own INFO stdout handler (propagate=False). Previously it used `uvicorn.access`, which has no handler once uvicorn's access log is off, and the root console handler runs at WARNING — so non-200s were being silently dropped. Now 200s are quiet and 4xx/5xx still surface. - Rewrite the middleware test to capture on the deeptutor.access logger directly (it no longer propagates to root). Verified: live server with --no-access-log logs nothing for 200s and prints `127.0.0.1 - "GET /api/v1/... HTTP/1.1" 404` for a 404. ruff + pytest (2447) green. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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] = []
|
||||
|
||||
@@ -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 TestSelectiveAccessLog:
|
||||
"""selective_access_log middleware must emit 5-arg tuples for uvicorn."""
|
||||
class _RecordCollector(logging.Handler):
|
||||
"""Capture emitted records directly on the access logger (no propagation)."""
|
||||
|
||||
def test_non_200_log_has_five_args(self, caplog):
|
||||
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 the formatter."""
|
||||
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user