|
|
@@ -178,6 +178,7 @@ class APILoggingASGIMiddleware:
|
|
|
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")
|
|
|
@@ -282,6 +283,8 @@ class APILoggingASGIMiddleware:
|
|
|
except Exception:
|
|
|
xu = None
|
|
|
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}")
|
|
|
+ # 计算执行时间
|
|
|
+ execution_time = int((time.time() - start_time) * 1000)
|
|
|
api_log = APILog(
|
|
|
user_id=user_id,
|
|
|
admin_id=scope.get("verified_admin_id") if scope.get("verified_admin_id") else None,
|
|
|
@@ -292,17 +295,19 @@ class APILoggingASGIMiddleware:
|
|
|
ip_address=client_ip,
|
|
|
user_agent=user_agent,
|
|
|
response_code=status_code,
|
|
|
- execution_time=None,
|
|
|
+ execution_time=execution_time,
|
|
|
created_at=beijing_now()
|
|
|
)
|
|
|
db.add(api_log)
|
|
|
db.commit()
|
|
|
- except Exception:
|
|
|
+ logger.debug(f"[APILoggingASGI] 成功记录API日志: {url} {method} {status_code} {execution_time}ms")
|
|
|
+ except Exception as e:
|
|
|
db.rollback()
|
|
|
+ logger.error(f"[APILoggingASGI] 记录API日志失败: {url} {method} {status_code}, 错误: {e}")
|
|
|
finally:
|
|
|
db.close()
|
|
|
- except Exception:
|
|
|
- pass
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"[APILoggingASGI] 创建数据库连接失败: {e}")
|
|
|
except Exception:
|
|
|
pass
|
|
|
|