How to Set AWS Cloud Watch Alarm for a Specific Text on AWS Cloud Logs

First, let's create a lambda function that log specific text randomly

Go to lambda Functions hit Create lambda

Let's take the function name randomText as an example

Hit Create function keeping the default values for other fields

Now we have a lambda function as shown bellow

Next, we can edit the index.mjs file to add the actual implementation. I'm adding very simple implementation.

export const handler = async (event) => {
  if (Math.random() < 0.5) console.log('Lower value');
  else console.log('Upper value');

  const response = {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda!'),
  };
  return response;
};

Next, let's test our lambda function. Switch to the Test tab and fill the values as shown bellow

Then, hit Save and Test

We should get a similar result as shown bellow

Next, go to CloudWatch -> Log groups

Then, click on the log group

Switch to Metric filters tab

Hit Create metric filter button

We can add a filter pattern. Embedding filtering text between two % marks we can create a filter pattern easily. Then, we can test whether our filter is working fine with existing logs or with custom log data.

Then, hit Next button. Fill the data related to our metric filter.

Then, hit Next button.

After hitting Create metric filter button we’ll get the filter

Then, check the checkbox on the filter and create alarm button. Then, we should load similar page in a new browser tab shown bellow.

We have to add threshold value. I’m adding zero here and keep the rest of the values on their defaults. Then, hit Next button.

Here, we have to select a SNS topic or create new. I’m selecting Create new topic.

Then we have to add unique name for the SNS topic and an email address to receive notifications. After adding values there, hit Create topic button.

Then, we should receive an email for confirming the subscription. By clicking the link given on the email, we have to confirm the subscription.

Next, we can hit Next button.

Then, add a suitable name for the alarm and hit Next button.

Finally, hitting Create alarm we’ll get the alarm. Then we can test this going back to the lambda. Run the test as we did earlier, util we get an Upper value on logs.

Within, few minutes email notification should be received to the given email.