I have errors in my AWS Lambda code as shown in the monitoring tab on my Lambda configuration however I can't see the error in CloudWatch logs.
How can I configure AWS in such a way that when my lambda function fails, I get an email stating which lambda failed, why(timeout or application error).
I set up a CloudWatch alarm but I just get an alarm notification not telling me why it failed(or I don't know where to look)
The first approach I think of is better trapping in your Lambda function of exceptions so that you can take that exception and send a notification to an SNS queue which your email address is subscribed to.
Alternatively, you could write a Lambda function that is activated by the cloud watch alarm and sends through the last 'N' number of lines of your CloudWatch Logs (or you could write something more intelligent) to an SNS queue again which you are a subscriber of.
The second approach is probably nicer as you could make it reusable for many Lambda queries, however I think that the first option is the simplest and easiest option to get you to where you want to be.
For both of the above you could also use SES however I think that is overkill and SNS is more appropriate to the use case.
Finally check out the "MessageStructure" parameter for publishing to SNS. If you want to kick off some form of automation at the recipient end you could send some pretty amazing JSON through to accomplish this.
Posting to an SNS Queue from Lambda is very simple, I'll link you to the JavaScript SDK reference below:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#publish-property
Example Code:
var AWS = require('aws-sdk');
var sns = new AWS.SNS();
var exceptionMessage = "This is exception data / information";
var topicArn = "arn:aws:sns:ap-southeast-2:012345678912:My-SNS-Topic";
var subject = "Lambda exception alert";
var params = {
Message: exceptionMessage,
MessageAttributes: {
someKey: {
DataType: 'String',
StringValue: exceptionMessage
}
},
Subject: subject,
TopicArn: topicArn
};
sns.publish(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
IAM Policy Document for your Lambda Function:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1477112217000",
"Effect": "Allow",
"Action": [
"sns:Publish"
],
"Resource": [
"arn:aws:sns:ap-southeast-2:012345678912:My-SNS-Topic"
]
}
]
}