Analyze Helper Functions

To ease some of the complexity of structuring the code to push metrics to CloudWatch, you’ll find a lib folder under /serverless-observability-workshop/code/sample-app/src/lib containing some helper functions. Let’s spend some time understanding two different ways we can publish metrics to CloudWatch.

Spare a couple of minutes to understand the methods and enums created the /serverless-observability-workshop/code/sample-app/src/lib/logging/logger.js and /serverless-observability-workshop/code/sample-app/src/lib/helper/models.js files.

Metric Units

When you are pushing metrics to CloudWatch Metrics, you have to define the unit of your metric in order for CloudWatch to properly aggregate your data. The Enum present on /serverless-observability-workshop/code/sample-app/src/lib/helper/models.js gives you a full list of the possible unit options allowed by CloudWatch Metrics.

You can visualize the entire unit list expanding the section below

Full Enum object (expand for code)

Pushing Metrics To CloudWatch Metrics

Let us now navigate through the /serverless-observability-workshop/code/sample-app/src/lib/logging/logger.js file containing methods to help you pushing your custom metrics to CloudWatch Metrics.

Pushing Metric Synchronously

The simplest way to push your metrics is by synchronously invoking the putMetricData() method present in the AWS SDK and passing your metric object as a payload. The options parameter below receives an JSON object containing metric attributes and dimensions and parses it in a way that satisfies the putMetricData() method needs by calling the buildMetricData() helper function.

You can visualize the full helper functions expanding the section below

Full helper functions (expand for code)

Pushing Metric Asynchronously

However, it is important to take in consideration that creating Custom Metrics synchronously may impact on performance/execution time. For this reason, it is advisable to push your metrics asynchronously, which is accomplished by logging your metrics to CloudWatch Logs and then creating subscription filters that process these specific log entries and push them to CloudWatch Metrics in background.

In order to log our metrics in a unique format that won’t mess with the rest of our function logs, we are parsing our JSON object in the StatsD format. Once our payload is formed, we use the logMetric() method to log them to CloudWatch Logs.

You can visualize the full helper functions expanding the section below

Full helper functions (expand for code)

Pushing Metrics using Embedded Metric Format (EMF)

In order to leverage EMF to push metrics to CloudWatch through structured log, we can follow several implementation approaches as described in the AWS Embedded Metric Format GitHub Repository.

You can visualize the full helper functions expanding the section below

Full helper functions (expand for code)