wangdongxu

jira:NYJ-1460 desc:init

1 import json 1 import json
2 import time 2 import time
3 import logging 3 import logging
  4 +
4 logger = logging.getLogger(__name__) 5 logger = logging.getLogger(__name__)
5 -from fastapi import FastAPI, Request 6 +from fastapi import Request
6 from starlette.middleware.base import BaseHTTPMiddleware 7 from starlette.middleware.base import BaseHTTPMiddleware
7 from starlette.responses import StreamingResponse 8 from starlette.responses import StreamingResponse
  9 +from config import settings
  10 +
8 11
9 class LoggingMiddleware(BaseHTTPMiddleware): 12 class LoggingMiddleware(BaseHTTPMiddleware):
10 - """HTTP请求/响应日志中间件."""  
11 13
  14 + # 日志记录路径前缀
12 async def dispatch(self, request: Request, call_next): 15 async def dispatch(self, request: Request, call_next):
13 - # 记录请求开始时间  
14 - start_time = time.time()  
15 -  
16 # 获取请求信息 16 # 获取请求信息
17 method = request.method 17 method = request.method
18 url = str(request.url) 18 url = str(request.url)
19 client_host = request.client.host if request.client else "unknown" 19 client_host = request.client.host if request.client else "unknown"
20 20
21 - # 读取请求体  
22 - request_body = None  
23 - if method in ("POST", "PUT", "PATCH"):  
24 - try:  
25 - body = await request.body()  
26 - if body:  
27 - request_body = body.decode("utf-8", errors="replace")  
28 - # 尝试格式化为JSON  
29 - try:  
30 - request_body = json.loads(request_body)  
31 - except json.JSONDecodeError:  
32 - pass # 保持原始字符串  
33 - except Exception:  
34 - pass 21 + # 判断是否需要记录日志
  22 + should_log = request.url.path.startswith(settings.url_prefix)
35 23
36 - # 记录请求日志  
37 - logger.info(f"→ HTTP Request | {method} {url} | Client: {client_host}")  
38 - if request_body:  
39 - logger.info(f" Request Body: {request_body}") 24 + if should_log:
  25 + # 记录请求开始时间
  26 + start_time = time.time()
40 27
41 - # 处理请求  
42 - response = await call_next(request) 28 + # 读取请求体
  29 + request_body = None
  30 + if method in ("POST", "PUT", "PATCH"):
  31 + try:
  32 + body = await request.body()
  33 + if body:
  34 + request_body = body.decode("utf-8", errors="replace")
  35 + # 尝试格式化为JSON
  36 + try:
  37 + request_body = json.loads(request_body)
  38 + except json.JSONDecodeError:
  39 + pass # 保持原始字符串
  40 + except Exception:
  41 + pass
  42 +
  43 + # 记录请求日志
  44 + logger.info(f"→ HTTP Request | {method} {url} | Client: {client_host}")
  45 + if request_body:
  46 + logger.info(f" Request Body: {request_body}")
43 47
44 - # 计算处理时间  
45 - process_time = time.time() - start_time 48 + # 处理请求
  49 + response = await call_next(request)
46 50
47 - # 读取响应体(仅处理非流式响应)  
48 - response_body = None  
49 - if not isinstance(response, StreamingResponse):  
50 - try:  
51 - response_body_bytes = b""  
52 - async for chunk in response.body_iterator:  
53 - response_body_bytes += chunk 51 + # 计算处理时间
  52 + process_time = time.time() - start_time
54 53
55 - # 重新构建响应  
56 - response_body = response_body_bytes.decode("utf-8", errors="replace")  
57 - # 尝试格式化为JSON 54 + # 读取响应体(仅处理非流式响应)
  55 + response_body = None
  56 + if not isinstance(response, StreamingResponse):
58 try: 57 try:
59 - response_body = json.loads(response_body)  
60 - except json.JSONDecodeError:  
61 - pass # 保持原始字符串 58 + response_body_bytes = b""
  59 + async for chunk in response.body_iterator:
  60 + response_body_bytes += chunk
  61 +
  62 + # 重新构建响应
  63 + response_body = response_body_bytes.decode("utf-8", errors="replace")
  64 + # 尝试格式化为JSON
  65 + try:
  66 + response_body = json.loads(response_body)
  67 + except json.JSONDecodeError:
  68 + pass # 保持原始字符串
62 69
63 - # 重建响应对象  
64 - response = StreamingResponse(  
65 - iter([response_body_bytes]),  
66 - status_code=response.status_code,  
67 - headers=dict(response.headers),  
68 - media_type=response.media_type,  
69 - )  
70 - except Exception:  
71 - pass 70 + # 重建响应对象
  71 + response = StreamingResponse(
  72 + iter([response_body_bytes]),
  73 + status_code=response.status_code,
  74 + headers=dict(response.headers),
  75 + media_type=response.media_type,
  76 + )
  77 + except Exception:
  78 + pass
72 79
73 - # 记录响应日志  
74 - status_code = response.status_code  
75 - logger.info(f"← HTTP Response | {method} {url} | Status: {status_code} | Time: {process_time:.3f}s")  
76 - if response_body:  
77 - logger.info(f" Response Body: {response_body}") 80 + # 记录响应日志
  81 + status_code = response.status_code
  82 + logger.info(f"← HTTP Response | {method} {url} | Status: {status_code} | Time: {process_time:.3f}s")
  83 + if response_body:
  84 + logger.info(f" Response Body: {response_body}")
78 85
79 - return response  
  86 + return response
  87 + else:
  88 + # 不需要记录日志的请求,直接处理
  89 + return await call_next(request)
1 -"""API路由聚合模块."""  
2 -  
3 from fastapi import APIRouter 1 from fastapi import APIRouter
  2 +from config import settings
  3 +
  4 +api_router = APIRouter(prefix=settings.url_prefix)
4 5
5 -# 创建主路由  
6 -api_router = APIRouter(prefix="/aigc-embedding/api")  
7 6
8 def register_router(router: APIRouter, prefix: str): 7 def register_router(router: APIRouter, prefix: str):
9 api_router.include_router(router, prefix=prefix) 8 api_router.include_router(router, prefix=prefix)
10 -  
@@ -2,12 +2,10 @@ app_name: "Embedding Service" @@ -2,12 +2,10 @@ app_name: "Embedding Service"
2 app_version: "1.0.0" 2 app_version: "1.0.0"
3 port: 8000 3 port: 8000
4 debug: false 4 debug: false
  5 +url_prefix: "/aigc-embedding/api"
5 6
6 db_es_enable: true 7 db_es_enable: true
7 db_es_url: "http://localhost:9200" 8 db_es_url: "http://localhost:9200"
8 -db_postgres_enable: false  
9 -db_postgres_url: "postgresql://postgres:postgres@localhost:5432/postgres"  
10 9
11 -service:  
12 - face:  
13 - db_client: "es" 10 +#db_postgres_enable: false
  11 +#db_postgres_url: "postgresql://postgres:postgres@localhost:5432/postgres"