Files
gemini-balance/app/middleware/request_logging_middleware.py
snaily b14bb93d8f refactor: 项目结构优化与FastAPI生命周期更新
重构项目目录结构,提高代码组织性和可维护性

将schemas目录重命名为domain,更好地表达领域模型概念
将services目录细分为service/chat、service/image等子目录
将api目录重命名为router,更符合FastAPI惯例
创建utils目录存放通用工具函数
更新FastAPI应用程序生命周期管理

替换已弃用的on_event方法为推荐的lifespan事件处理器
添加应用程序关闭时的日志记录
代码质量改进

抽取常量到constants.py,减少硬编码值
添加helpers.py提供通用工具函数
优化配置管理,使用环境变量和默认值
完善文档字符串,提高代码可读性
2025-03-20 17:13:03 +08:00

37 lines
1.3 KiB
Python

from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
import json
from app.logger.logger import get_request_logger
logger = get_request_logger()
# 添加中间件类
class RequestLoggingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
# 记录请求路径
logger.info(f"Request path: {request.url.path}")
# 获取并记录请求体
try:
body = await request.body()
if body:
body_str = body.decode()
# 尝试格式化JSON
try:
formatted_body = json.loads(body_str)
logger.info(f"Formatted request body:\n{json.dumps(formatted_body, indent=2, ensure_ascii=False)}")
except json.JSONDecodeError:
logger.info("Request body is not valid JSON.")
except Exception as e:
logger.error(f"Error reading request body: {str(e)}")
# 重置请求的接收器,以便后续处理器可以继续读取请求体
async def receive():
return {"type": "http.request", "body": body, "more_body": False}
request._receive = receive
response = await call_next(request)
return response