AWS Embedded Metrics
The AWS Embedded Metrics Python library provides an easy way to emit custom metrics asynchronously, allowing users to consolidate logs and metrics into a single data stream without complex metric client setup. It formats metric data in a structured log format (EMF) for consumption by CloudWatch Logs and then CloudWatch. The current version is 3.5.0, and it follows an active release cadence with frequent updates.
Warnings
- breaking Version 3.0.0 introduced significant changes to dimension and metric validation, preventing duplicate dimensions, and altering how custom dimensions are cleared and preserved across flushes. Code relying on previous behavior might break.
- breaking Version 2.0.0 enforced a limit of 30 dimensions per dimension set. Exceeding this limit will now raise a `DimensionSetExceededError`.
- gotcha Metrics are emitted to `stdout` in Embedded Metric Format (EMF). For these metrics to appear in CloudWatch, you *must* have a CloudWatch Agent configured to collect logs from `stdout` and forward them to CloudWatch Logs, or run in an environment (like Lambda) where this is handled automatically.
- gotcha High-resolution metrics (1-second granularity) require explicit configuration. By default, metrics are collected at 1-minute resolution.
- gotcha When using `@metric_scope` with asynchronous functions or generators, ensure your Python version and library version are compatible, and be aware of potential context propagation issues in complex async workflows. Version 3.3.0 specifically fixed issues with async generator functions.
Install
-
pip install aws-embedded-metrics
Imports
- get_metrics
from aws_embedded_metrics import get_metrics
- metric_scope
from aws_embedded_metrics import metric_scope
Quickstart
from aws_embedded_metrics import metric_scope
@metric_scope
def process_data(metrics):
metrics.set_namespace("MyApplication")
metrics.put_dimensions({"Service": "DataProcessor", "Operation": "Transform"})
# Add multiple metric values for a single metric
metrics.put_metric("ProcessingLatency", 100, "Milliseconds")
metrics.put_metric("ProcessingLatency", 95, "Milliseconds")
metrics.put_metric("ProcessingLatency", 105, "Milliseconds")
metrics.set_property("Region", "us-east-1")
metrics.set_property("ContainerId", "abc-123")
print("Processing data...")
if __name__ == "__main__":
# In a deployed AWS environment, these metrics would be collected by the CloudWatch Agent
# and sent to CloudWatch. Locally, they are printed to stdout in EMF format.
process_data()