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

  • Aggregate up to 100 metrics using a single CloudWatch EMF object (large JSON blob)
  • Validate against common metric definitions mistakes (metric unit, values, max dimensions, max metrics, etc)
  • Metrics are created asynchronously by CloudWatch service, no custom stacks needed
  • Context manager to create a one off metric with a different dimension

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:

  • ensure that at least one metric is emitted before you flush them
  • capture a ColdStart a metric
  • set default dimensions for all your metrics

Example

import { Metrics } 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' });

const lambdaHandler = async (_event: unknown, _context: unknown) => {
...
};

export const handler = middy(lambdaHandler).use(logMetrics(metrics));

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:

  • capture a ColdStart metric
  • flush buffered metrics
  • throw on empty metrics

Example

import { Metrics, MetricUnit } 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 {
// Decorate your handler with the logMetrics decorator
⁣@metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true })
public handler(_event: unknown, _context: unknown): Promise<void> {
// ...
metrics.addMetric('test-metric', MetricUnit.Count, 10);
// ...
}
}

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

Standard function

If you are used to classic JavaScript functions, you can leverage the different methods provided to create and publish metrics.

Example

import { Metrics, MetricUnit } 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();
metrics.addMetric('test-metric', MetricUnit.Count, 10);
metrics.publishStoredMetrics();
};

Hierarchy (view full)

Implements

Constructors

Methods

  • Add multiple dimensions to the metrics.

    A dimension is a key-value pair that is used to group metrics.

    Parameters

    • dimensions: {
          [key: string]: string;
      }

      A key-value pair of dimensions

      • [key: string]: string

    Returns void

  • A high-cardinality data part of your Metrics log.

    This is useful when you want to search highly contextual information along with your metrics in your logs.

    Parameters

    • key: string

      The key of the metadata

    • value: string

      The value of the metadata

    Returns void

  • 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.

    Parameters

    • name: string

      The metric name

    • unit: MetricUnit

      The metric unit

    • value: number

      The metric value

    • resolution: MetricResolution = MetricResolutions.Standard

      The metric resolution

    Returns void

    Example

    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.

    Example

    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:

    • Create a separate EMF blob that contains a single metric named ColdStart
    • Add function_name and service dimensions

    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.

    Returns void

    Example

    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.

    Returns boolean

    Example

    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

    Example

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

    const utility = new Utility();
    utility.isColdStart(); // true
    utility.isColdStart(); // false

    See

    getColdStart

  • Validate that the service name provided is valid. Used internally during initialization.

    Parameters

    • Optional serviceName: string

      Service name to validate

    Returns boolean

  • A decorator automating coldstart capture, throw on empty metrics and publishing metrics on handler exit.

    Parameters

    Returns HandlerMethodDecorator

    Example

    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);

    Decorator

    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.

    Returns void

    Example

    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.

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

    metrics as JSON object compliant EMF Schema Specification

  • Sets the function name to be added to the metric.

    Parameters

    • value: string

      The function name to be added to the metric.

    Returns void

  • 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.

    Returns Metrics

    the Metrics

    Example

    const singleMetric = metrics.singleMetric();
    singleMetric.addDimension('InnerDimension', 'true');
    singleMetric.addMetric('single-metric', MetricUnit.Percent, 50);
  • Throw an Error if the metrics buffer is empty.

    Returns void

    Example

    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.
    };