如何使用 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 日志缺失问题?

为 API Gateway 中的 REST API 设置 CloudWatch 日志记录

使用 Amazon CloudWatch 指标监控 REST API 的执行

使用 CloudWatch 指标监控 WebSocket API 的执行

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