DEV Community

Sam
Sam

Posted on

SNS Email notifications for errors trigged by AWS Lambda functions using CloudWatch Alarms and CDK

The following is a CDK stack, setup for monitoring errors logged from Lambda functions, to supplement the lack of good examples for achieving this.

It is setup with the following goals but can be customised:

  • Measure at 1 minute intervals.
  • Trigger alerts if any errors are logged.
  • Send to an email address.
import * as cdk from "@aws-cdk/core";
import {Duration} from "@aws-cdk/core";
import * as sns from "@aws-cdk/aws-sns";
import * as subs from "@aws-cdk/aws-sns-subscriptions";
import * as cw from "@aws-cdk/aws-cloudwatch";
import {ComparisonOperator} from "@aws-cdk/aws-cloudwatch";
import * as actions from "@aws-cdk/aws-cloudwatch-actions";

export class CloudwatchAlarmsStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const topic = this.createTopic('foo@example.com');
    this.alertOnLambdaProducesAnyError(topic, 'lambda-a');
    this.alertOnLambdaProducesAnyError(topic, 'lambda-b');
  }

  createTopic(notifyEmail: string) {
    const topic = new sns.Topic(this, 'oly-monitoring', {
      displayName: 'OlyServiceMonitoring',
    });
    topic.addSubscription(
        new subs.EmailSubscription(notifyEmail),
    );
    return topic;
  }

  alertOnLambdaProducesAnyError(topic: sns.Topic, lambdaName: string) {
    const alarm = new cw.Alarm(this, `any-errors-${lambdaName}`, {
      alarmName: `any-errors-${lambdaName}`,
      actionsEnabled: true,
      alarmDescription: `Notify for any errors logged for the lambda function ${lambdaName}`,
      threshold: 1,
      evaluationPeriods: 1,
      comparisonOperator: ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,

      metric: new cw.Metric({
        namespace: 'AWS/Lambda',
        metricName: 'Errors',
        dimensionsMap: {
          'FunctionName': lambdaName,
        },
        statistic: 'min',
        period: Duration.minutes(1),
      }),
    });

    alarm.addAlarmAction(new actions.SnsAction(topic));
  }

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)