Add a metric to the metrics buffer.
By default, metrics are buffered and flushed at the end of the Lambda invocation or when calling Metrics.publishStoredMetrics.
You can add a metric by specifying the metric name, unit, and value. For convenience, we provide a set of constants for the most common units in MetricUnit.
The metric name
The metric unit
The metric value
The metric resolution
import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
Optionally, you can specify the metric resolution, which can be either High
or Standard
.
By default, metrics are published with a resolution of Standard
, click here
to learn more about metric resolutions.
import { Metrics, MetricUnit, MetricResolution } from '@aws-lambda-powertools/metrics';
const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
metrics.addMetric('successfulBooking', MetricUnit.Count, 1, MetricResolution.High);
Create a singleMetric to capture cold start.
If it's a cold start invocation, this feature will:
This has the advantage of keeping cold start metric separate from your application metrics, where you might have unrelated dimensions, as well as avoiding potential data loss from metrics not being published for other reasons.
import { Metrics } from '@aws-lambda-powertools/metrics';
const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
metrics.captureColdStartMetric();
};
Get the cold start status of the current execution environment.
import { Utility } from '@aws-lambda-powertools/commons';
const utility = new Utility();
utility.isColdStart(); // true
utility.isColdStart(); // false
The method also flips the cold start status to false
after the first invocation.
Protected
getProtected
isA decorator automating coldstart capture, throw on empty metrics and publishing metrics on handler exit.
import { Metrics } from '@aws-lambda-powertools/metrics';
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
class Lambda implements LambdaInterface {
@metrics.logMetrics({ captureColdStartMetric: true })
public handler(_event: unknown, __context: unknown): Promise<void> {
// ...
}
}
const handlerClass = new Lambda();
export const handler = handlerClass.handler.bind(handlerClass);
Class
Synchronous function to actually publish your metrics. (Not needed if using logMetrics decorator). It will create a new EMF blob and log it to standard output to be then ingested by Cloudwatch logs and processed automatically for metrics creation.
import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); // Sets metric namespace, and service as a metric dimension
export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
metrics.addMetric('test-metric', MetricUnit.Count, 10);
metrics.publishStoredMetrics();
};
Function to create a new metric object compliant with the EMF (Embedded Metric Format) schema which includes the metric name, unit, and optionally storage resolution.
The function will create a new EMF blob and log it to standard output to be then ingested by Cloudwatch logs and processed automatically for metrics creation.
metrics as JSON object compliant EMF Schema Specification
Sets default dimensions that will be added to all metrics.
The default dimensions to be added to all metrics.
CloudWatch EMF uses the same dimensions across all your metrics. Use singleMetric if you have a metric that should have different dimensions.
You don't need to call publishStoredMetrics() after calling addMetric for a singleMetrics, they will be flushed directly.
the Metrics
const singleMetric = metrics.singleMetric();
singleMetric.addDimension('InnerDimension', 'true');
singleMetric.addMetric('single-metric', MetricUnit.Percent, 50);
Throw an Error if the metrics buffer is empty.
import { Metrics } from '@aws-lambda-powertools/metrics';
const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName:'orders' });
export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
metrics.throwOnEmptyMetrics();
metrics.publishStoredMetrics(); // will throw since no metrics added.
};
Intro
Metrics creates custom metrics asynchronously by logging metrics to standard output following Amazon CloudWatch Embedded Metric Format (EMF).
These metrics can be visualized through Amazon CloudWatch Console.
Key features
Usage
Functions usage with middleware
Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error. Additionally, you can configure the middleware to easily:
ColdStart
a metricExample
Object oriented way with decorator
If you are used to TypeScript Class usage to encapsulate your Lambda handler you can leverage the @metrics.logMetrics() decorator to automatically:
ColdStart
metricExample
Standard function
If you are used to classic JavaScript functions, you can leverage the different methods provided to create and publish metrics.
Example