由CloudWatch日志事件触发的AWS Lambda无法正确接收事件对象
问题分析
你的核心问题是事件类型不匹配,或者JSON序列化时属性映射错误:
- 如果你是直接把Lambda订阅到SNS主题(用来接收投递失败通知),却错误用了
CloudWatchEvent类型接收事件,SNS的事件格式和CloudWatch Event完全不同,导致序列化后字段全为null。 - 即便确实是CloudWatch Events触发,自定义的
EventConfig类可能没正确映射JSON字段(比如JSON里的topicArn和C#的TopicArn命名差异)。
解决方案
场景1:Lambda直接被SNS主题触发
这是监控SNS投递失败最常见的场景,修改代码如下:
先确保安装Amazon.Lambda.SNSEvents NuGet包,然后调整函数签名和处理逻辑:
using Amazon.Lambda.Core; using Amazon.Lambda.SNSEvents; namespace SnsLogProcessor { public void FunctionHandler(SNSEvent evnt, ILambdaContext context) { context.Logger.LogInformation($"Lambda triggered!"); foreach (var record in evnt.Records) { context.Logger.LogInformation($"SNS消息ID: {record.Sns.MessageId}"); context.Logger.LogInformation($"SNS主题ARN: {record.Sns.TopicArn}"); context.Logger.LogInformation($"消息内容: {record.Sns.Message}"); // 解析投递失败通知的详情(SNS投递失败的消息通常是JSON格式) var failureDetail = System.Text.Json.JsonSerializer.Deserialize<EventConfig>(record.Sns.Message); if (failureDetail != null) { context.Logger.LogInformation($"投递状态: {failureDetail.status}"); context.Logger.LogInformation($"目标主题ARN: {failureDetail.TopicArn}"); } } } public class EventConfig { public string TopicArn { get; set; } public string status { get; set; } } }
场景2:Lambda被CloudWatch Events触发
如果是通过CloudWatch告警或规则触发Lambda,需要修正属性映射:
给EventConfig的属性添加JsonPropertyName特性,匹配JSON字段的命名:
using Amazon.Lambda.CloudWatchEvents; using Amazon.Lambda.Core; using System.Text.Json.Serialization; namespace SnsLogProcessor { public class EventConfig { [JsonPropertyName("topicArn")] public string TopicArn { get; set; } [JsonPropertyName("status")] public string Status { get; set; } } public void FunctionHandler(CloudWatchEvent<EventConfig> evnt, ILambdaContext context) { context.Logger.LogInformation($"Lambda triggered!"); context.Logger.LogInformation($"DetailType: {evnt.DetailType}"); context.Logger.LogInformation($"Region: {evnt.Region}"); context.Logger.LogInformation($"Source: {evnt.Source}"); context.Logger.LogInformation($"Account: {evnt.Account}"); if (evnt.Detail != null) { context.Logger.LogInformation($"投递状态: {evnt.Detail.Status}"); context.Logger.LogInformation($"主题ARN: {evnt.Detail.TopicArn}"); } } }
必做排查
- 查看Lambda日志里的原始事件JSON:在CloudWatch日志中找到触发Lambda的完整事件内容,确认是SNS Event还是CloudWatch Event格式,这是定位问题的关键。
- 检查NuGet包版本:确保
Amazon.Lambda.CloudWatchEvents和Amazon.Lambda.SNSEvents是最新稳定版,避免序列化兼容问题。
内容的提问来源于stack exchange,提问作者Haiyu Hou
相关产品推荐
相关产品推荐

