使用映射模板覆盖 API 的请求和响应参数以及状态代码
映射模板覆盖不能与缺少数据映射的代理集成端点一起使用
- 模型仅用于表示输入和输出格式
- 用于转换数据的映射模板
您可以按照以下步骤在 API 网关中启用日志记录:
- 创建
arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs
附加权限并遵循信任策略的 IAM
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
- 在
- In the API Gateway console, on the APIs pane, choose the name of an API that you created.
- In the left navigation pane, at the bottom, choose Settings.
- Under Settings, for CloudWatch log role ARN, paste the IAM role ARN that you copied.
- Choose Save.
现在有两种记录 IP 地址的方法
- 在 AWS 控制台中转到您的 AWS API Gateway 实例。在左侧菜单中选择 Stages,然后选择 Logs/Tracing 选项卡 Toggle on
Enable CloudWatch Logs
并选择Log Level
asINFO
接着
您可以通过以下方式启用映射模板
这导致访问日志如下:

最重要的是,您还可以Method request headers
在
(b1fe0021-8064-4be8-a548-203c6fd795a6) Method request headers:
{accept-language=en-us, User-Agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15,
X-Forwarded-Proto=https,
X-Forwarded-For=8.xx.xx.xx,
Host=xxxxx.execute-api.eu-central-1.amazonaws.com,
X-Forwarded-Port=443, accept-encoding=gzip, deflate, br,
X-Amzn-Trace-Id=Root=1-602e74b0-439e58b379ac537c27664a34, accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8}
如果您不启用CloudWatch
登录,则通过映射模板的地址信息IP
也将被传递到端点。就像这个答案中描述的那样,例如 lambda。
'use strict';
console.log('Loading function');
exports.handler = (event, context, callback) => {
console.log('SourceIP =', event.identity.sourceIP);
callback(null, event.identity.sourceIP);
};
或者
{
"ip": "$context.identity.sourceIp",
"apiId": "$context.apiId",
"requestId": "$context.requestId",
"requestTime": "$context.requestTime",
"protocol": "$context.protocol",
...
...
}
- 单击保存更改,就是这样!API 日志应在几分钟后开始显示。

如何启用 CloudWatch Logs 以对我的 API Gateway REST API 或 WebSocket API 进行故障排除?