如何使用 Amazon API Gateway 日誌進行疑難排解?

2 分的閱讀內容
0

我想要使用 Amazon API Gateway 日誌來疑難排解 API 問題。

簡短描述

若要對 API Gateway REST API 或 WebSocket API 進行疑難排解,請使用 Amazon CloudWatch Logs 開啟執行日誌記錄和存取日誌記錄功能。確保您已將所有必要的許可連接至 API Gateway AWS Identity and Access Management (IAM) 角色。如需指示,請參閱如何開啟 CloudWatch Logs 以對 API Gateway REST API 或 WebSocket API 進行疑難排解?

**備註:**HTTP API 目前僅支援存取日誌記錄,而且這些 API 的日誌記錄設定有所不同。如需詳細資訊,請參閱設定 HTTP API 的日誌記錄

解決方案

開啟日誌記錄功能之後,API Gateway 會自動建立名為 API-Gateway-Execution-Logs/{rest-api-id}/{stage-name} 的 CloudWatch 日誌群組。如需詳細資訊,請參閱 API Gateway 的 CloudWatch 日誌格式

AWS Lambda 授權方

如果您為 API 開啟了 Lambda 授權方,則日誌會指出請求是否獲得授權,並包含授權方和請求 ID。

授權日誌範例:

Starting authorizer: 62mgrc for request: 3323ffe5-6ddf-45c8-896a-b45ec2284cc0
Successfully completed authorizer execution

未授權日誌範例:

Starting authorizer: 62mgrc for request: fd443056-60d0-425f-874e-e93e5d61351e
Unauthorized request: fd443056-60d0-425f-874e-e93e5d61351e

使用計劃

在記錄 Lambda 授權方日誌之後,API Gateway 會驗證 API 請求的使用計劃。如果您尚未設定使用計劃,則 API 要求不會計入限流限制。

使用計劃日誌範例:

Verifying Usage Plan for request: 3323ffe5-6ddf-45c8-896a-b45ec2284cc0. API Key: API Stage: <api_id>/<stage>
API Key authorized because method 'GET /' does not require API Key. Request will not contribute to throttle or quota limits
Usage Plan check succeeded for API Key and API Stage <api_id>/<stage>

如果您已使用 API 金鑰設定 API,但缺少 X-API-Key 標頭,則日誌會傳回類似下列內容的錯誤:

API Key not authorized because method 'GET /' requires API Key and API 
Key is not associated with a Usage Plan for API Stage 
<api_id>/<stage>: API Key was required but not present

如果您在標頭中新增了正確的 API 金鑰,但請求已限流,則日誌會傳回類似下列內容的錯誤:

API Key **********************************FGQes7 exceeded throttle limit for API Stage <api_id>/<stage>: Key throttle limit exceeded for Usage Plan ID iwuzkt. Limit: 5.00 Burst: 0
Method completed with status: 429

請求日誌類型

備註:所有請求日誌類型都需要在執行日誌中開啟日誌完整請求/回應資料

方法請求日誌

方法請求日誌包括 API 請求接收的詳細資訊,包括請求路徑、查詢參數、請求標頭和請求主體。

端點請求日誌

端點請求日誌包括 API 請求接收的詳細資訊,包括 URI,請求標頭和請求主體。

端點請求中包含的資料將傳送到您的後端整合以進行進一步處理。

端點回應日誌

端點回應日誌包含後端整合傳回的資料,涵蓋狀態碼、標頭主體和整合延遲。

方法回應日誌

方法回應日誌包括轉換後傳送至用戶端的標頭和主體。

**重要事項:**API Gateway 將日誌事件限制為 1024 位元組。大於 1024 位元組的日誌事件 (例如請求和回應主體) 會在提交至 CloudWatch 日誌之前被 API Gateway 截斷。


相關資訊

該如何針對 API Gateway REST API 遺失 CloudWatch Logs 進行疑難排解?

在 API Gateway 中設定 REST API 的 CloudWatch 日誌記錄

使用 Amazon CloudWatch 指標監控 REST API 執行

使用 CloudWatch 指標監控 WebSocket API 執行

AWS 官方
AWS 官方已更新 1 年前