API Gateway调用Lambda时print输出丢失问题咨询
问题
我正在学习API Gateway,将Lambda函数配置为某路由的实现。我在Lambda函数中添加了print语句,用于查看传入的event对象具体结构。在Lambda控制台点击Test按钮时,日志能正常显示print输出;但在API Gateway控制台配置好测试参数后点击Test,生成的详细日志中没有print输出,且对应的CloudWatch日志组中也找不到这些输出。请问如何获取这些输出?是否需要改用logger接口?我能确认调用的是同一函数,因为之前语法错误时两者报错一致。
我的测试代码如下:
def lambda_handler(event, context): print("hello") print("hello") print(event) print("hello") print("hello") return event
Lambda测试日志:
**Function Logs** START RequestId: 5a981182-0c07-47ab-9870-a126077a47fb Version: $LATEST hello hello {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} hello hello END RequestId: 5a981182-0c07-47ab-9870-a126077a47fb REPORT RequestId: 5a981182-0c07-47ab-9870-a126077a47fb Duration: 1.59 ms Billed Duration: 2 ms Memory Size: 128 MB Max Memory Used: 72 MB Init Duration: 359.06 ms
API Gateway测试日志:
Execution log for request 9e9fc8df-5865-4511-b98c-170dc200cdbf Tue Oct 17 21:24:07 UTC 2023 : Starting execution for request: 9e9fc8df-5865-4511-b98c-170dc200cdbf Tue Oct 17 21:24:07 UTC 2023 : HTTP Method: POST, Resource Path: /blast-jobs Tue Oct 17 21:24:07 UTC 2023 : Method request path: {} Tue Oct 17 21:24:07 UTC 2023 : Method request query string: {id=12543} Tue Oct 17 21:24:07 UTC 2023 : Method request headers: {} Tue Oct 17 21:24:07 UTC 2023 : Method request body before transformations: Tue Oct 17 21:24:07 UTC 2023 : Endpoint request URI: https://lambda.us-west-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-west-2:680678151940:function:blast-job-create/invocations Tue Oct 17 21:24:07 UTC 2023 : Endpoint request headers: {x-amzn-lambda-integration-tag=9e9fc8df-5865-4511-b98c-170dc200cdbf, Authorization=***********************************************************************************************************************************************************************************************************************************************************************************************************5b1b40, X-Amz-Date=20231017T212407Z, x-amzn-apigateway-api-id=z7p03y8fsl, X-Amz-Source-Arn=arn:aws:execute-api:us-west-2:680678151940:z7p03y8fsl/test-invoke-stage/POST/blast-jobs, Accept=application/json, User-Agent=AmazonAPIGateway_z7p03y8fsl, X-Amz-Security-Token=IQoJb3JpZ2luX2VjEHwaCXVzLXdlc3QtMiJGMEQCIFAlRNi2qWdb/t4Ns7aPhBEL4xS8S+RNosv3YDwwPZ62AiBtBEDMynu2sHifcWuRMp1ENJkn0Lw6A4NpHc+kiCPjiCq5BQiV//////////8BEAUaDDEwOTM1MTMwOTQwNyIM0aToxb8NiSJg8PjnKo0FV/S77p/giiwY1oGpDmFGbblLZN1SiE5M4XQr7DmilAwgielGxojWaFxi84R7A3W+0wcuB4kDcLomVgp2I+K4T3BdTqytzi+fr41UvYkVdfrzEjymAWrR+JtzgFjSaD+3W7cX3Mfl+0W/uj0YVQ9P+TUTOsu5Wk [TRUNCATED] Tue Oct 17 21:24:07 UTC 2023 : Endpoint request body after transformations: Tue Oct 17 21:24:07 UTC 2023 : Sending request to https://lambda.us-west-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-west-2:680678151940:function:blast-job-create/invocations Tue Oct 17 21:24:08 UTC 2023 : Received response. Status: 200, Integration latency: 513 ms Tue Oct 17 21:24:08 UTC 2023 : Endpoint response headers: {Date=Tue, 17 Oct 2023 21:24:08 GMT, Content-Type=application/json, Content-Length=2, Connection=keep-alive, x-amzn-RequestId=f7561b7d-f61e-4b8d-b55b-9cf1b77f819a, x-amzn-Remapped-Content-Length=0, X-Amz-Executed-Version=$LATEST, X-Amzn-Trace-Id=root=1-652efb77-e9cf5f6c51fdabede9c58813;sampled=0;lineage=1dc83a0a:0} Tue Oct 17 21:24:08 UTC 2023 : Endpoint response body before transformations: {} Tue Oct 17 21:24:08 UTC 2023 : Method response body after transformations: {} Tue Oct 17 21:24:08 UTC 2023 : Method response headers: {X-Amzn-Trace-Id=Root=1-652efb77-e9cf5f6c51fdabede9c58813;Sampled=0;lineage=1dc83a0a:0, Content-Type=application/json} Tue Oct 17 21:24:08 UTC 2023 : Successfully completed execution Tue Oct 17 21:24:08 UTC 2023 : Method completed with status: 200
解决方案
- 检查Lambda执行角色权限:确保Lambda的执行角色拥有
logs:CreateLogGroup、logs:CreateLogStream、logs:PutLogEvents这三个CloudWatch日志权限。如果权限不足,API Gateway触发Lambda时,日志无法写入CloudWatch,自然看不到print输出。 - 确认CloudWatch日志组路径:Lambda对应的日志组固定为
/aws/lambda/[你的函数名],检查是否查看了正确的日志组,同时确认日志的时间范围与API Gateway测试时间匹配,避免因时间筛选错误遗漏日志。 - API Gateway集成日志设置:在API Gateway的集成请求配置中,开启"Enable Detailed CloudWatch Metrics"并勾选"Log full requests/responses data",不过这仅用于查看API网关自身的请求日志,Lambda的日志仍需到对应CloudWatch日志组查看。
- 无需强制替换print为logger,但推荐使用:Python Lambda中
print语句默认会输出到CloudWatch,只要配置正确就能显示。不过官方更推荐使用logging模块,它支持日志级别划分,格式更规范,便于后续排查问题。示例代码:
import logging logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event, context): logger.info("hello") logger.info(event) return event
- 排查调用类型延迟:如果API Gateway配置的是异步调用Lambda,日志可能会有几分钟的延迟,需要等待后再查看CloudWatch。从你的测试日志来看是同步调用(返回200状态),此情况概率较低,但可以留意。
内容的提问来源于stack exchange,提问作者Joymaker
相关产品推荐
相关产品推荐

