如何在AWS API Gateway日志中获取查询参数信息
在AWS API Gateway日志中记录查询参数的方法
有两种常用方式实现这个需求,按需选择即可:
1. 记录带查询参数的完整请求路径
直接使用$context.requestString变量,它会返回包含查询参数的完整路径(比如/api/v1/pets?name="name1")。你可以替换原有的path字段,或者新增字段存储完整路径:
修改后的日志格式示例:
{ "requestTime": "$context.requestTime", "requestId": "$context.requestId", "httpMethod": "$context.httpMethod", "resourcePath": "$context.resourcePath", "status": $context.status, "path": "$context.path", "fullRequestPath": "$context.requestString" }
2. 单独记录查询参数(全部或指定参数)
如果需要单独提取查询参数,用$context.queryStringParameters变量,它会返回所有查询参数组成的JSON对象;如果只需要某个特定参数,比如name,直接用$context.queryStringParameters.name即可。
记录所有查询参数
{ "requestTime": "$context.requestTime", "requestId": "$context.requestId", "httpMethod": "$context.httpMethod", "resourcePath": "$context.resourcePath", "status": $context.status, "path": "$context.path", "queryParams": $context.queryStringParameters }
注意:queryParams字段不需要加引号,因为$context.queryStringParameters本身就是合法的JSON格式。
记录单个指定参数
比如只记录name参数:
{ "requestTime": "$context.requestTime", "requestId": "$context.requestId", "httpMethod": "$context.httpMethod", "resourcePath": "$context.resourcePath", "status": $context.status, "path": "$context.path", "petName": "$context.queryStringParameters.name" }
修改日志格式的操作步骤
- 打开AWS API Gateway控制台,找到目标API
- 进入对应的**阶段(Stage)**设置页面
- 找到「日志记录和跟踪」模块,编辑「日志格式」,替换为上述内容即可
内容的提问来源于stack exchange,提问作者Tanu
相关产品推荐
相关产品推荐

