Options
All
  • Public
  • Public/Protected
  • All
Menu

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

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:

  • create cold start metric
  • flush buffered metrics
  • throw on empty metrics
example
import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics';
import { Callback, Context } from 'aws-lambda';

const metrics = new Metrics({namespace:"MyService", serviceName:"withDecorator"});

export class MyFunctionWithDecorator {

// FYI: Decorator might not render properly in VSCode mouse over due to https://github.com/microsoft/TypeScript/issues/39371 and might show as *@metrics* instead of `@metrics.logMetrics`

@metrics.logMetrics({captureColdStartMetric: true, throwOnEmptyMetrics: true, })
public handler(_event: any, _context: Context, _callback: Callback<any>): void | Promise<any> {
// ...
metrics.addMetric('test-metric', MetricUnits.Count, 10);
// ...
}
}

export const handlerClass = new MyFunctionWithDecorator()
export const handler = handlerClass.handler

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, MetricUnits } from '@aws-lambda-powertools/metrics';

const metrics = new Metrics({namespace: "MyService", serviceName: "MyFunction"});

export const handler = async (_event: any, _context: any) => {
metrics.captureColdStart();
metrics.addMetric('test-metric', MetricUnits.Count, 10);
metrics.publishStoredMetrics();
};

Hierarchy

  • Metrics

Implements

Index

Constructors

constructor

Methods

addDimension

  • addDimension(name: string, value: string): void

addDimensions

  • addDimensions(dimensions: {}): void

addMetadata

  • addMetadata(key: string, value: string): 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
    • value: string

    Returns void

addMetric

  • addMetric(name: string, unit: MetricUnit, value: number): void

captureColdStartMetric

  • captureColdStartMetric(): void
  • Create a singleMetric to capture cold start. If it's a cold start invocation, this feature will:

    • Create a separate EMF blob solely containing a 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.

    example
    import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics';
    import { Context } from 'aws-lambda';

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

    export const handler = async (event: any, context: Context) => {
    metrics.captureColdStartMetric();
    }

    Returns void

clearDefaultDimensions

  • clearDefaultDimensions(): void

clearDimensions

  • clearDimensions(): void

clearMetadata

  • clearMetadata(): void

clearMetrics

  • clearMetrics(): void

logMetrics

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

    example
    import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics';
    import { Callback, Context } from 'aws-lambda';

    const metrics = new Metrics({namespace:"CdkExample", serviceName:"withDecorator"});

    export class MyFunctionWithDecorator {

    @metrics.logMetrics({captureColdStartMetric: true})
    public handler(_event: any, _context: Context, _callback: Callback<any>): void | Promise<any> {
    // ...
    }
    }

    export const handlerClass = new MyFunctionWithDecorator()
    export const handler = handlerClass.handler
    decorator

    Class

    Parameters

    Returns <internal>.HandlerMethodDecorator

publishStoredMetrics

  • publishStoredMetrics(): void
  • 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.

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

    const metrics = new Metrics({namespace: "CdkExample", serviceName: "MyFunction"}); // Sets metric namespace, and service as a metric dimension

    export const handler = async (_event: any, _context: any) => {
    metrics.addMetric('test-metric', MetricUnits.Count, 10);
    metrics.publishStoredMetrics();
    };

    Returns void

serializeMetrics

setDefaultDimensions

  • setDefaultDimensions(dimensions: undefined | Dimensions): void

setFunctionName

  • setFunctionName(value: string): void

singleMetric

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

    example
    const singleMetric = metrics.singleMetric();
    singleMetric.addDimension('InnerDimension', 'true');
    singleMetric.addMetric('single-metric', MetricUnits.Percent, 50);

    Returns Metrics

    the Metrics

throwOnEmptyMetrics

  • throwOnEmptyMetrics(): void
  • Throw an Error if the metrics buffer is empty.

    example
    import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics';
    import { Context } from 'aws-lambda';

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

    export const handler = async (event: any, context: Context) => {
    metrics.throwOnEmptyMetrics();
    metrics.publishStoredMetrics(); // will throw since no metrics added.
    }

    Returns void

Generated using TypeDoc