Initial commit: 智能项目定价模型
This commit is contained in:
50
后端服务/app/middleware/performance.py
Normal file
50
后端服务/app/middleware/performance.py
Normal file
@@ -0,0 +1,50 @@
|
||||
"""性能监控中间件
|
||||
|
||||
记录请求响应时间,用于性能分析和优化
|
||||
"""
|
||||
|
||||
import time
|
||||
import logging
|
||||
from typing import Callable
|
||||
|
||||
from fastapi import Request, Response
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PerformanceMiddleware(BaseHTTPMiddleware):
|
||||
"""性能监控中间件
|
||||
|
||||
记录每个请求的响应时间,并在响应头中添加 X-Response-Time
|
||||
"""
|
||||
|
||||
# 慢请求阈值(毫秒)
|
||||
SLOW_REQUEST_THRESHOLD = 1000
|
||||
|
||||
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
||||
start_time = time.time()
|
||||
|
||||
# 执行请求
|
||||
response = await call_next(request)
|
||||
|
||||
# 计算响应时间
|
||||
process_time = (time.time() - start_time) * 1000
|
||||
|
||||
# 添加响应头
|
||||
response.headers["X-Response-Time"] = f"{process_time:.2f}ms"
|
||||
|
||||
# 记录慢请求
|
||||
if process_time > self.SLOW_REQUEST_THRESHOLD:
|
||||
logger.warning(
|
||||
f"Slow request: {request.method} {request.url.path} "
|
||||
f"took {process_time:.2f}ms"
|
||||
)
|
||||
|
||||
# 记录请求日志(开发环境)
|
||||
logger.debug(
|
||||
f"{request.method} {request.url.path} - "
|
||||
f"{response.status_code} - {process_time:.2f}ms"
|
||||
)
|
||||
|
||||
return response
|
||||
Reference in New Issue
Block a user