Amazon CloudWatch via SDK: Metrics & Alarms
CloudWatch is how you see what your systems are doing - metrics, logs, and alarms in one place.
Busca en todas las páginas de la documentación
CloudWatch is how you see what your systems are doing - metrics, logs, and alarms in one place.
This page publishes a custom metric from code, then creates an alarm that watches it and fires an SNS notification when a threshold is crossed. It closes by reading and deleting the alarm.
Quick-reference recipe card - copy-paste ready.
# --- Python (boto3) ---
import boto3
cw = boto3.client("cloudwatch", region_name="us-east-1")
cw.put_metric_data(
Namespace="MyApp",
MetricData=[{
"MetricName": "OrdersFailed",
"Value": 1, "Unit": "Count",
"Dimensions": [{"Name": "Service", "Value": "checkout"}],
}],
)
print("metric published")// --- TypeScript (AWS SDK v3) ---
import { CloudWatchClient, PutMetricDataCommand } from "@aws-sdk/client-cloudwatch";
const cw = new CloudWatchClient({ region: "us-east-1" });
await cw.send(new PutMetricDataCommand({
Namespace: "MyApp",
MetricData: [{
MetricName: "OrdersFailed",
Value: 1, Unit: "Count",
Dimensions: [{ Name: "Service", Value: "checkout" }],
}],
}));
console.log("metric published");When to reach for this:
Publish a custom metric, create an alarm on it that notifies an SNS topic, read the alarm state, then clean up.
# --- Python (boto3) ---
import boto3
cw = boto3.client("cloudwatch", region_name="us-east-1")
NS, METRIC = "MyApp", "OrdersFailed"
dims = [{"Name": "Service", "Value": "checkout"}]
# 1. Publish the metric.
cw.put_metric_data(Namespace=NS, MetricData=[
{"MetricName": METRIC, "Value": 3, "Unit": "Count", "Dimensions": dims}])
# 2. Create an alarm: >= 5 failures summed over one 5-minute period.
cw.put_metric_alarm(
AlarmName="checkout-failures",
Namespace=NS, MetricName=METRIC, Dimensions=dims,
Statistic="Sum", Period=300, EvaluationPeriods=1,
Threshold=5, ComparisonOperator="GreaterThanOrEqualToThreshold",
TreatMissingData="notBreaching",
AlarmActions=["arn:aws:sns:us-east-1:111122223333:alerts"],
)
# 3. Read the alarm state.
alarm = cw.describe_alarms(AlarmNames=["checkout-failures"])["MetricAlarms"][0]
print(alarm["StateValue"]) # OK / ALARM / INSUFFICIENT_DATA
# 4. Clean up.
cw.delete_alarms(AlarmNames=["checkout-failures"])// --- TypeScript (AWS SDK v3) ---
import {
CloudWatchClient, PutMetricDataCommand, PutMetricAlarmCommand,
DescribeAlarmsCommand, DeleteAlarmsCommand,
} from "@aws-sdk/client-cloudwatch";
const cw = new CloudWatchClient({ region: "us-east-1" });
const NS = "MyApp", METRIC = "OrdersFailed";
const dims = [{ Name: "Service", Value: "checkout" }];
// 1. Publish the metric.
await cw.send(new PutMetricDataCommand({
Namespace: NS,
MetricData: [{ MetricName: METRIC, Value: 3, Unit: "Count", Dimensions: dims }],
}));
// 2. Create an alarm: >= 5 failures summed over one 5-minute period.
await cw.send(new PutMetricAlarmCommand({
AlarmName: "checkout-failures",
Namespace: NS, MetricName: METRIC, Dimensions: dims,
Statistic: "Sum", Period: 300, EvaluationPeriods: 1,
Threshold: 5, ComparisonOperator: "GreaterThanOrEqualToThreshold",
TreatMissingData: "notBreaching",
AlarmActions: ["arn:aws:sns:us-east-1:111122223333:alerts"],
}));
// 3. Read the alarm state.
const out = await cw.send(new DescribeAlarmsCommand({ AlarmNames: ["checkout-failures"] }));
console.log(out.MetricAlarms![0].StateValue); // OK / ALARM / INSUFFICIENT_DATA
// 4. Clean up.
await cw.send(new DeleteAlarmsCommand({ AlarmNames: ["checkout-failures"] }));What this demonstrates:
PutMetricData - there is no separate "create metric" call.Dimensions scope a metric (here, per service) and must match between publish and alarm.PutMetricAlarm binds a statistic, period, threshold, and comparison into a watch.AlarmActions points at an SNS topic ARN so the alarm notifies you when it fires.PutMetricData both creates and appends to a metric; the first write brings it into existence.Sum, Average, p99) over a period, then compares the result to a threshold across some number of evaluation periods.OK, ALARM, and INSUFFICIENT_DATA, and it triggers actions on transitions.Raw counts are noisy. A metric-math alarm can watch a ratio - like error percentage - which is far more meaningful.
# --- Python (boto3) ---
cw.put_metric_alarm(
AlarmName="checkout-error-rate",
ComparisonOperator="GreaterThanThreshold",
EvaluationPeriods=1, Threshold=5, # alarm if error rate > 5%
Metrics=[
{"Id": "errors", "MetricStat": {"Metric": {"Namespace": "MyApp",
"MetricName": "OrdersFailed"}, "Period": 300, "Stat": "Sum"},
"ReturnData": False},
{"Id": "total", "MetricStat": {"Metric": {"Namespace": "MyApp",
"MetricName": "OrdersTotal"}, "Period": 300, "Stat": "Sum"},
"ReturnData": False},
{"Id": "rate", "Expression": "errors / total * 100", "Label": "ErrorRate%"},
],
)// --- TypeScript (AWS SDK v3) ---
await cw.send(new PutMetricAlarmCommand({
AlarmName: "checkout-error-rate",
ComparisonOperator: "GreaterThanThreshold",
EvaluationPeriods: 1, Threshold: 5, // alarm if error rate > 5%
Metrics: [
{ Id: "errors", MetricStat: { Metric: { Namespace: "MyApp",
MetricName: "OrdersFailed" }, Period: 300, Stat: "Sum" }, ReturnData: false },
{ Id: "total", MetricStat: { Metric: { Namespace: "MyApp",
MetricName: "OrdersTotal" }, Period: 300, Stat: "Sum" }, ReturnData: false },
{ Id: "rate", Expression: "errors / total * 100", Label: "ErrorRate%" },
],
}));Metric math lets one alarm combine several metrics into a single, more useful signal.
PutMetricData accepts up to 1,000 metric data items per call. Batch your metrics into one request instead of one call each to cut request count and cost.
PutMetricData and PutMetricAlarm.INSUFFICIENT_DATA when no data arrives, which may hide or over-fire depending on intent. Fix: set TreatMissingData deliberately (notBreaching, breaching, or ignore).AlarmActions changes state silently. Fix: attach an SNS topic (or other action) so someone is notified.PutMetricData calls waste requests. Fix: batch up to 1,000 data items per call.| Alternative | Use When | Don't Use When |
|---|---|---|
| CloudWatch metrics + alarms (this page) | Monitoring and alerting on numeric signals | You need full-text log search or tracing |
| CloudWatch Logs + metric filters | Deriving metrics from log patterns | The value is already a first-class metric |
| CloudWatch Synthetics | Proactive endpoint/canary checks | Alerting on internal application metrics |
| AWS X-Ray | Distributed tracing across services | Simple threshold alerting |
| Third-party (Datadog, Grafana) | Cross-cloud dashboards and advanced analytics | A single-account, AWS-native setup |
No. PutMetricData creates the metric on its first write. There is no separate creation call - the namespace, name, and dimensions define it implicitly.
Dimensions are name/value pairs that slice a metric, such as by service or instance. They are part of a metric's identity, so an alarm must use the exact same dimensions to watch it.
It aggregates the metric with a statistic over a period, then compares the result to a threshold across the evaluation periods. If the condition holds, it transitions to ALARM and runs its actions.
Set AlarmActions to an SNS topic ARN. When the alarm enters ALARM, CloudWatch publishes to that topic, which can email you, hit a webhook, or invoke a function.
The state when there is not enough data in the evaluation window to decide. Control how it is handled with TreatMissingData, choosing whether missing data should breach, not breach, or be ignored.
Counts scale with traffic and are noisy, causing flapping alarms. A rate or percentage - built with metric math - stays meaningful across traffic levels and gives a stabler signal.
Yes. Use the Metrics array with metric math, referencing each source metric by Id and computing an expression like errors / total * 100. Only the expression returns data for the alarm.
Match the period you can act on - usually 60 or 300 seconds. Sub-minute (high-resolution) metrics cost more and add noise, so use them only when you truly need that granularity.
Yes. Each call accepts up to 1,000 metric data items. Batch multiple metrics and data points into one request instead of calling once per metric.
A metric is a numeric time series you alarm and graph on. A log is a text record you search and derive insight from. Metric filters can turn log patterns into metrics when needed.
Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+).
Revisado por Chris St. John·Última actualización: 24 jul 2026