Skip to content

Metrics

Business metrics and KPIs can drive your business forward towards success.

Metrics consist of a key and a value; A value can be a number, percentage, rate, or any other unit. Typical metrics are the number of sessions, users, error rate, number of views, etc.

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.

Metrics

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

Usage in Handler

my_handler.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import json
from http import HTTPStatus
from typing import Any

from aws_lambda_powertools.metrics import Metrics, MetricUnit
from aws_lambda_powertools.utilities.typing import LambdaContext

SERVICE_NAME = 'service'

# namespace and service name can be set by environment variable "POWERTOOLS_METRICS_NAMESPACE" and "POWERTOOLS_SERVICE_NAME" accordingly
metrics = Metrics(namespace='my_product_kpi', service=SERVICE_NAME)


@metrics.log_metrics
def my_handler(event: dict[str, Any], context: LambdaContext) -> dict[str, Any]:
    metrics.add_metric(name='ValidEvents', unit=MetricUnit.Count, value=1)
    return {'statusCode': HTTPStatus.OK, 'headers': {'Content-Type': 'application/json'}, 'body': json.dumps({'message': 'success'})}

Blog Reference

Read more about the importance of the business KPis and metrics in my blog. Click HERE

More Details

You can find more information at the official documentation.

Go to https://docs.powertools.aws.dev/lambda-python/latest/core/metrics/