The Metrics utility 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

  • Aggregating up to 100 metrics using a single CloudWatch EMF object (large JSON blob).
  • Validating your metrics against common metric definitions mistakes (for example, metric unit, values, max dimensions, max metrics).
  • Metrics are created asynchronously by the CloudWatch service. You do not need any custom stacks, and there is no impact to Lambda function latency.
  • Creating a one-off metric with different dimensions.

After initializing the Metrics class, you can add metrics using the addMetric() method. The metrics are stored in a buffer and are flushed when calling publishStoredMetrics(). Each metric can have dimensions and metadata added to it.

import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';

const metrics = new Metrics({
namespace: 'serverlessAirline',
serviceName: 'orders',
defaultDimensions: { environment: 'dev' },
});

export const handler = async (event: { requestId: string }) => {
metrics.addMetadata('request_id', event.requestId);
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
metrics.publishStoredMetrics();
};

If you don't want to manually flush the metrics, you can use the logMetrics() decorator or the Middy.js middleware to automatically flush the metrics after the handler function returns or throws an error.

In addition to this, the decorator and middleware can also be configured to capture a ColdStart metric and set default dimensions for all metrics.

Class method decorator

import type { Context } from 'aws-lambda';
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';

const metrics = new Metrics({
namespace: 'serverlessAirline',
serviceName: 'orders'
});

class Lambda implements LambdaInterface {
⁣@metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true })
public async handler(_event: { requestId: string }, _: Context) {
metrics.addMetadata('request_id', event.requestId);
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
}
}

const handlerClass = new Lambda();
export const handler = handlerClass.handler.bind(handlerClass);

Note that decorators are a Stage 3 proposal for JavaScript and are not yet part of the ECMAScript standard. The current implmementation in this library is based on the legacy TypeScript decorator syntax enabled by the experimentalDecorators flag set to true in the tsconfig.json file.

Middy.js middleware

import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
import middy from '@middy/core';

const metrics = new Metrics({
namespace: 'serverlessAirline',
serviceName: 'orders'
});

export const handler = middy(async () => {
metrics.addMetadata('request_id', event.requestId);
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
}).use(logMetrics(metrics, {
captureColdStartMetric: true,
throwOnEmptyMetrics: true,
}));

The logMetrics() middleware is compatible with @middy/core@3.x and above.

Hierarchy (View Summary)

Implements

Constructors

Methods

  • Add a dimension to metrics.

    A dimension is a key-value pair that is used to group metrics, and it is included in all metrics emitted after it is added. Invalid dimension values are skipped and a warning is logged.

    When calling the publishStoredMetrics() method, the dimensions are cleared. This type of dimension is useful when you want to add request-specific dimensions to your metrics. If you want to add dimensions that are included in all metrics, use the setDefaultDimensions() method.

    Parameters

    • name: string

      The name of the dimension

    • value: string

      The value of the dimension

    Returns void

  • Add multiple dimensions to the metrics.

    This method is useful when you want to add multiple dimensions to the metrics at once. Invalid dimension values are skipped and a warning is logged.

    When calling the publishStoredMetrics() method, the dimensions are cleared. This type of dimension is useful when you want to add request-specific dimensions to your metrics. If you want to add dimensions that are included in all metrics, use the setDefaultDimensions() method.

    Parameters

    • dimensions: Dimensions

      An object with key-value pairs of dimensions

    Returns void

  • A metadata key-value pair to be included with metrics.

    You can use this method to add high-cardinality data as part of your metrics. This is useful when you want to search highly contextual information along with your metrics in your logs.

    Note that the metadata is not included in the Amazon CloudWatch UI, but it can be used to search and filter logs.

    Parameters

    • key: string

      The key of the metadata

    • value: string

      The value of the metadata

    Returns void

    import { Metrics } from '@aws-lambda-powertools/metrics';

    const metrics = new Metrics({
    namespace: 'serverlessAirline',
    serviceName: 'orders'
    });

    export const handler = async (event) => {
    metrics.addMetadata('request_id', event.requestId);
    metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
    metrics.publishStoredMetrics();
    };
  • Add a metric to the metrics buffer.

    By default, metrics are buffered and flushed when calling publishStoredMetrics() method, or at the end of the handler function when using the logMetrics() decorator or the Middy.js middleware.

    Metrics are emitted to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.

    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 the MetricUnit dictionary object.

    Optionally, you can specify a resolution, which can be either High or Standard, using the MetricResolution dictionary object. By default, metrics are published with a resolution of Standard.

    Parameters

    Returns void

    import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';

    const metrics = new Metrics({
    namespace: 'serverlessAirline',
    serviceName: 'orders'
    });

    export const handler = async () => {
    metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
    metrics.publishStoredMetrics();
    };
  • Immediately emit a ColdStart metric if this is a cold start invocation.

    A cold start is when AWS Lambda initializes a new instance of your function. To take advantage of this feature, you must instantiate the Metrics class outside of the handler function.

    By using this method, the metric will be emitted immediately without you having to call publishStoredMetrics().

    If you are using the logMetrics() decorator, or the Middy.js middleware, you can enable this feature by setting the captureColdStartMetric option to true.

    Returns void

    import { Metrics } from '@aws-lambda-powertools/metrics';

    const metrics = new Metrics({
    namespace: 'serverlessAirline',
    serviceName: 'orders'
    });

    export const handler = async () => {
    metrics.captureColdStartMetric();
    };
  • Clear all previously set default dimensions.

    This will remove all default dimensions set by the setDefaultDimensions() method or via the defaultDimensions parameter in the constructor.

    Returns void

    import { Metrics } from '@aws-lambda-powertools/metrics';

    const metrics = new Metrics({
    namespace: 'serverlessAirline',
    serviceName: 'orders',
    defaultDimensions: { environment: 'dev' },
    });

    metrics.setDefaultDimensions({ region: 'us-west-2' });

    // both environment and region dimensions are removed
    metrics.clearDefaultDimensions();
  • Clear all the dimensions added to the Metrics instance via addDimension() or addDimensions().

    These dimensions are normally cleared when calling publishStoredMetrics(), but you can use this method to clear specific dimensions that you no longer need at runtime.

    This method does not clear the default dimensions set via setDefaultDimensions() or via the defaultDimensions parameter in the constructor.

    Returns void

    import { Metrics } from '@aws-lambda-powertools/metrics';

    const metrics = new Metrics({
    namespace: 'serverlessAirline',
    serviceName: 'orders'
    });

    export const handler = async () => {
    metrics.addDimension('region', 'us-west-2');

    // ...

    metrics.clearDimensions(); // olnly the region dimension is removed
    };

    The method is primarily intended for internal use, but it is exposed for advanced use cases.

  • Clear all the metadata added to the Metrics instance.

    Metadata is normally cleared when calling publishStoredMetrics(), but you can use this method to clear specific metadata that you no longer need at runtime.

    The method is primarily intended for internal use, but it is exposed for advanced use cases.

    Returns void

  • Clear all the metrics stored in the buffer.

    This is useful when you want to clear the metrics stored in the buffer without publishing them.

    The method is primarily intended for internal use, but it is exposed for advanced use cases.

    Returns void

  • Get the cold start status of the current execution environment.

    Returns boolean

    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.

  • Get the default service name.

    Returns string

  • Get the cold start status of the current execution environment.

    Returns boolean

    import { Utility } from '@aws-lambda-powertools/commons';

    const utility = new Utility();
    utility.isColdStart(); // true
    utility.isColdStart(); // false
  • Validate that the service name provided is valid. Used internally during initialization.

    Parameters

    • OptionalserviceName: string

      Service name to validate

    Returns boolean

  • A class method decorator to automatically log metrics after the method returns or throws an error.

    The decorator can be used with TypeScript classes and can be configured to optionally capture a ColdStart metric (see captureColdStartMetric()), throw an error if no metrics are emitted (see setThrowOnEmptyMetrics()), and set default dimensions for all metrics (see setDefaultDimensions()).

    Parameters

    Returns HandlerMethodDecorator

    import type { Context } from 'aws-lambda';
    import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
    import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';

    const metrics = new Metrics({
    namespace: 'serverlessAirline',
    serviceName: 'orders'
    });

    class Lambda implements LambdaInterface {
    ⁣@metrics.logMetrics({ captureColdStartMetric: true })
    public async handler(_event: { requestId: string }, _: Context) {
    metrics.addMetadata('request_id', event.requestId);
    metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
    }
    }

    const handlerClass = new Lambda();
    export const handler = handlerClass.handler.bind(handlerClass);

    You can configure the decorator with the following options:

    • captureColdStartMetric - Whether to capture a ColdStart metric
    • defaultDimensions - Default dimensions to add to all metrics
    • throwOnEmptyMetrics - Whether to throw an error if no metrics are emitted
  • Flush the stored metrics to standard output.

    The method empties the metrics buffer and emits the metrics to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.

    When using the logMetrics() decorator, or the Middy.js middleware, the metrics are automatically flushed after the handler function returns or throws an error.

    Returns void

    import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';

    const metrics = new Metrics({
    namespace: 'serverlessAirline',
    serviceName: 'orders'
    });

    export const handler = async () => {
    metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
    metrics.publishStoredMetrics();
    };
  • Serialize the stored metrics into a JSON object compliant with the Amazon CloudWatch EMF (Embedded Metric Format) schema.

    The EMF schema is a JSON object that contains the following properties:

    • _aws: An object containing the timestamp and the CloudWatch metrics.
    • CloudWatchMetrics: An array of CloudWatch metrics objects.
    • Namespace: The namespace of the metrics.
    • Dimensions: An array of dimensions for the metrics.
    • Metrics: An array of metric definitions.

    The object is then emitted to standard output, which in AWS Lambda is picked up by CloudWatch logs and processed asynchronously.

    Returns Readonly<
        {
            _aws: {
                CloudWatchMetrics: {
                    Dimensions: [string[]];
                    Metrics: MetricDefinition[];
                    Namespace: string;
                }[];
                Timestamp: number;
            };
            [key: string]: string
            | number
            | object;
        },
    >

  • Set default dimensions that will be added to all metrics.

    This method will merge the provided dimensions with the existing default dimensions.

    Parameters

    • dimensions: undefined | Dimensions

      The dimensions to be added to the default dimensions object

    Returns void

    import { Metrics } from '@aws-lambda-powertools/metrics';

    const metrics = new Metrics({
    namespace: 'serverlessAirline',
    serviceName: 'orders',
    defaultDimensions: { environment: 'dev' },
    });

    // Default dimensions will contain both region and environment
    metrics.setDefaultDimensions({
    region: 'us-west-2',
    environment: 'prod',
    });
  • Set the function name to be added to each metric as a dimension.

    When using the logMetrics() decorator, or the Middy.js middleware, the function name is automatically inferred from the Lambda context.

    Parameters

    • name: string

      The function name

    Returns void

    import { Metrics } from '@aws-lambda-powertools/metrics';

    const metrics = new Metrics({
    namespace: 'serverlessAirline',
    serviceName: 'orders'
    });

    metrics.setFunctionName('my-function-name');
  • Set the flag to throw an error if no metrics are emitted.

    You can use this method to enable or disable this opt-in feature. This is useful if you want to ensure that at least one metric is emitted when flushing the metrics. This can be useful to catch bugs where metrics are not being emitted as expected.

    Parameters

    • enabled: boolean

      Whether to throw an error if no metrics are emitted

    Returns void

  • Create a new Metrics instance configured to immediately flush a single metric.

    CloudWatch EMF uses the same dimensions and timestamp across all your metrics, this is useful when you have a metric that should have different dimensions or when you want to emit a single metric without buffering it.

    This method is used internally by the captureColdStartMetric() method to emit the ColdStart metric immediately after the handler function is called.

    Returns Metrics

    import { Metrics } from '@aws-lambda-powertools/metrics';

    const metrics = new Metrics({
    namespace: 'serverlessAirline',
    serviceName: 'orders'
    });

    export const handler = async () => {
    const singleMetric = metrics.singleMetric();
    // The single metric will be emitted immediately
    singleMetric.addMetric('ColdStart', MetricUnit.Count, 1);

    // These other metrics will be buffered and emitted when calling `publishStoredMetrics()`
    metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
    metrics.publishStoredMetrics();