DEV Community

Sam
Sam

Posted on

1

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

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please consider showing your support with a ❤️ or a kind comment if you enjoyed this post!

Sure thing