fix:增加接口调试信息

This commit is contained in:
ZhangYonghao
2026-03-21 21:39:25 +08:00
parent 3b660203dd
commit 7e563fae30
5 changed files with 51 additions and 1 deletions

View File

@@ -1,7 +1,9 @@
import logging
from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from app.config import settings
from app.database import Base, SessionLocal, engine, ensure_database_schema
@@ -39,6 +41,46 @@ app.add_middleware(
app.include_router(html.router, prefix=settings.api_prefix)
def _truncate_for_log(value: str) -> str:
limit = settings.request_log_max_chars
if len(value) <= limit:
return value
return f"{value[:limit]}... [truncated {len(value) - limit} chars]"
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(
request: Request,
exc: RequestValidationError,
) -> JSONResponse:
if settings.enable_request_debug_log:
try:
raw_body = (await request.body()).decode("utf-8", errors="replace")
except Exception as body_error:
raw_body = f"<failed to read body: {body_error}>"
interesting_headers = {
key: value
for key, value in request.headers.items()
if key.lower() in {"content-type", "content-length", "x-api-key", "user-agent"}
}
logger.error(
"422 validation error: method=%s path=%s query=%s headers=%s errors=%s body=%s",
request.method,
request.url.path,
dict(request.query_params),
interesting_headers,
exc.errors(),
_truncate_for_log(raw_body),
)
return JSONResponse(
status_code=422,
content={"detail": exc.errors()},
)
@app.on_event("startup")
def cleanup_on_startup() -> None:
db = SessionLocal()