| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157 |
- """
- API日志中间件 - 管理端专用
- """
- import time
- from app.database import SessionLocal
- from app.models.api_log import APILog
- from app.core.logger import logger, get_logger_by_path
- from app.utils.timezone import beijing_now
- class APILoggingASGIMiddleware:
- """更可靠的 ASGI 层日志中间件,捕获请求/响应流(用于记录完整返回报文)"""
- def __init__(self, app):
- self.app = app
- async def __call__(self, scope, receive, send):
- if scope.get("type") != "http":
- await self.app(scope, receive, send)
- return
- start_time = time.time()
- method = scope.get("method")
- server = scope.get("server") or ("localhost", 80)
- path = scope.get("raw_path", b"").decode("utf-8", errors="ignore")
- query_string = scope.get("query_string", b"").decode("utf-8", errors="ignore")
- scheme = scope.get("scheme", "http")
- url = f"{scheme}://{server[0]}:{server[1]}{path}" + (f"?{query_string}" if query_string else "")
- client = scope.get("client")
- client_ip = client[0] if client else None
- headers = {k.decode("utf-8"): v.decode("utf-8") for k, v in scope.get("headers", [])}
- user_agent = headers.get("user-agent", "")
- # 直接从请求头获取user_id和user_name,进行组合校验
- user_id = None
- admin_id = None
- try:
- # 从header获取user_id和user_name
- header_user_id = headers.get("x-user-id") or headers.get("X-User-Id")
- header_user_name = headers.get("x-user-name") or headers.get("X-User-Name")
- if header_user_id and header_user_name:
- # 管理端:从Admin表查询
- db_temp = SessionLocal()
- try:
- from app.models.admin import Admin
- admin = db_temp.query(Admin).filter(
- Admin.id == int(header_user_id),
- Admin.username == header_user_name
- ).first()
- if admin:
- admin_id = admin.id
- finally:
- db_temp.close()
- except Exception:
- # 如果header验证失败,记录为None
- user_id = None
- admin_id = None
- # 包装 receive,收集请求体(仅在有 body 时)
- body_bytes = b""
- async def receive_wrapper():
- nonlocal body_bytes
- message = await receive()
- if message.get("type") == "http.request":
- body_bytes += message.get("body", b"")
- return message
- # 包装 send,收集响应状态与 body 分片
- status_code = 500
- resp_chunks = []
- async def send_wrapper(message):
- nonlocal status_code, resp_chunks
- if message.get("type") == "http.response.start":
- status_code = message.get("status", 0)
- if message.get("type") == "http.response.body":
- chunk = message.get("body", b"")
- if chunk:
- resp_chunks.append(chunk)
- await send(message)
- # 调用下游应用并在返回后记录日志
- try:
- await self.app(scope, receive_wrapper, send_wrapper)
- finally:
- try:
- response_body_bytes = b"".join(resp_chunks) if resp_chunks else b""
- try:
- response_text = response_body_bytes.decode("utf-8", errors="ignore") if response_body_bytes else None
- except Exception:
- response_text = str(response_body_bytes)
- if not response_text:
- response_text = f"Status: {status_code}"
- if len(response_text) > 2000:
- response_text = response_text[:2000] + "..."
- request_text = None
- if body_bytes:
- try:
- request_text = body_bytes.decode("utf-8", errors="ignore")
- if len(request_text) > 2000:
- request_text = request_text[:2000] + "..."
- except Exception:
- request_text = str(body_bytes)
- # 计算执行时间
- execution_time = int((time.time() - start_time) * 1000)
- # 根据路径选择对应的logger
- api_logger = get_logger_by_path(path)
- # 在控制台打印API入参出参
- try:
- request_display = request_text[:1000] + ('...' if request_text and len(request_text) > 1000 else '') if request_text else 'None'
- response_display = response_text[:1000] + ('...' if response_text and len(response_text) > 1000 else '') if response_text else 'None'
- api_logger.info(f"[API请求] {method} {url} - 请求数据: {request_display}")
- api_logger.info(f"[API响应] {method} {url} - 响应数据: {response_display} - 执行时间: {execution_time}ms")
- except Exception as e:
- api_logger.warning(f"[API日志] 控制台日志输出失败: {e}")
- # 写入数据库(异步性与错误容忍)
- try:
- db = SessionLocal()
- try:
- # 临时调试日志:打印请求头中的 X-User-Id/X-User-Name 与 scope 注入的 verified ids
- try:
- headers_lower = {k.lower(): v for k, v in headers.items()} if 'headers' in locals() else {}
- xu = headers_lower.get('x-user-id') or headers_lower.get('x-user-name') or None
- except Exception:
- xu = None
- api_logger.debug(f"[APILoggingASGI][DEBUG] endpoint={url} verified_user_id={scope.get('verified_user_id')} verified_admin_id={scope.get('verified_admin_id')} header_X_User_Id={xu}")
- api_log = APILog(
- user_id=user_id,
- admin_id=scope.get("verified_admin_id") if scope.get("verified_admin_id") else None,
- endpoint=url,
- method=method,
- request_data=request_text if request_text else None,
- response_data=response_text if response_text else None,
- ip_address=client_ip,
- user_agent=user_agent,
- response_code=status_code,
- execution_time=execution_time,
- created_at=beijing_now()
- )
- db.add(api_log)
- db.commit()
- api_logger.debug(f"[APILoggingASGI] 成功记录API日志: {url} {method} {status_code} {execution_time}ms")
- except Exception as e:
- db.rollback()
- api_logger.error(f"[APILoggingASGI] 记录API日志失败: {url} {method} {status_code}", exc_info=True)
- finally:
- db.close()
- except Exception as e:
- api_logger.error(f"[APILoggingASGI] 创建数据库连接失败: {e}")
- except Exception:
- pass
|