Creating Custom CloudWatch Alarms for AWS Lambdas

AWS allows you to setup CloudWatch alarms on many performance-related metrics. Doing this for metrics like CPU load or storage use is trivial. However, setting up custom alarms based on events or errors in a log isn’t as straightforward. By the end of this post, you should know how to set up alarms based on errors and events within a Lambda on AWS.

1. Create a Lambda

First, you’ll need a Lambda. If you have an existing Lambda or you are creating a new Lambda, make sure it has permissions to log to CloudWatch. For the examples in this post, we are going to be using the following Node.js code:

exports.handler = async (event) => {
    event: 'test',
    more: 'stuff'
    event: "don't catch",
    more: 'stuff'

Note: If this Lambda has not logged anything yet, trigger an event that will cause it to do so. The log group for Lambdas isn’t created until something is logged, and we’ll need that later on.

2. Create Metric Filter

After you have a Lambda with a log group, open the CloudWatch console and click “Logs” in the sidebar. Next, select the log group that relates to your Lambda and click “Create Metric Filter.” You should see a screen asking you to specify a filter pattern. For the example mentioned earlier, we will use the following filter:

{ $.event = test }

This filter will find and count any logged JSON that has event as a key, and test as a value on that key. If you need a more personalized filter, checkout Amazon’s official documentation on CloudWatch’s filter and pattern syntax.

After you have set your filter pattern, you can test it on one of your existing logs or confirm your filter by pressing “Assign Metric.” Then you can input a name for you filter, along with a name and namespace for the given metric.

3.Create Alarm

After creating a metric filter, you will be taken to a screen showing all metric filters for your chosen log. Find the metric filter you just created, and click “Create Alarm.” A modal will pop up prompting you to create an alarm. Fill in the form with your desired details, click “Create Alarm,” and you will have a custom alarm based on Lambda logs!

You should now be receiving notifications whenever your specified event gets triggered.