有没有办法把API Gateway请求日志中的查询字符串参数记录到CloudWatch?
我目前正在使用Serverless框架来搭建我们的微服务。已经开启对API Gateway请求的日志记录,并设置了如下日志格式:
provider:
logs:
restApi:
format: '{ "requestId":"$context.requestId", "ip": "$context.identity.sourceIp", "requestTime":"$context.requestTime", "httpMethod":"$context.httpMethod", "routeKey":"$context.routeKey", "status":"$context.status", "protocol":"$context.protocol", "responseLength":"$context.responseLength", "queryStringParameters": "$util.escapeJavaScript($context.queryStringParameters)", "resourcePath": "$context.resourcePath", "path": "$context.path", "params": "$util.escapeJavaScript($input.params().querystring)" }'
然而,当我发送一个看起来像这样的请求时:
example.com/content/node?pathAlias=business-support&status=1&loadRef=1
接着,在查看日志时,发现查询字符串参数被省略了:
{
"requestId": "bc987f8f-cd83-4b1c-ac50-6e3c461e00f9",
"ip": "143.58.138.188",
"requestTime": "01/Jul/2026:06:47:02 +0000",
"httpMethod": "GET",
"routeKey": "-",
"status": "200",
"protocol": "HTTP/1.1",
"responseLength": "11728",
"queryStringParameters": "-(-)",
"resourcePath": "/node",
"path": "/content/node",
"params": "-(-().querystring)"
}
有没有办法将查询字符串参数记录到API Gateway的 CloudWatch日志中?
解决方案
根本原因是你把两种不同的API Gateway功能混用:访问日志格式和VTL映射模板。
provider.logs.restApi.format 配置了访问日志格式。它并不是被当作Velocity模板来求值,因此诸如 $input.params() 和 $util.escapeJavaScript() 之类的表达式永远不会执行。
这就是为什么:
"params": "$util.escapeJavaScript($input.params().querystring)"
会被字面输出,而不是产生实际的查询字符串。
API Gateway的访问日志只支持文档中列出的 $context 变量。没有任何通用变量可以展开整个查询字符串。
如果你的目标是记录查询参数,推荐的做法是在你的集成端记录它们(例如使用Lambda代理集成):
(代码块)
对于该请求:
/content/node?pathAlias=business-support&status=1&loadRef=1
Lambda收到:
(JSON块)
因此简短的回答是 不可以:访问日志不能评估 $input.* 或 $util.*。请改为从后端记录查询字符串。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。