CloudWatch, Logs & Observability
Emit custom metrics, create alarms, query logs with Logs Insights, and trace requests with X-Ray.
Busque em todas as páginas da documentação
Emit custom metrics, create alarms, query logs with Logs Insights, and trace requests with X-Ray.
Publish a single datapoint to a custom namespace.
# --- Python (boto3) ---
import boto3
cw = boto3.client("cloudwatch", region_name="us-east-1")
cw.put_metric_data(
Namespace="MyApp",
MetricData=[{
"MetricName": "Orders",
"Value": 1,
"Unit": "Count"
}]
)// --- 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: "Orders",
Value: 1,
Unit: "Count"
}]
}));Send multiple datapoints in a single call.
# --- Python (boto3) ---
import boto3
cw = boto3.client("cloudwatch", region_name="us-east-1")
cw.put_metric_data(
Namespace="MyApp",
MetricData=[
{"MetricName": "Orders", "Value": 42, "Unit": "Count"},
{"MetricName": "Revenue", "Value": 1200.50, "Unit": "None"},
{"MetricName": "Latency", "Value": 150, "Unit": "Milliseconds"}
]
)// --- 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: "Orders", Value: 42, Unit: "Count" },
{ MetricName: "Revenue", Value: 1200.50, Unit: "None" },
{ MetricName: "Latency", Value: 150, Unit: "Milliseconds" }
]
}));Query aggregated metric data over a time window.
# --- Python (boto3) ---
import boto3
from datetime import datetime, timedelta
cw = boto3.client("cloudwatch", region_name="us-east-1")
end = datetime.utcnow()
start = end - timedelta(hours=1)
response = cw.get_metric_statistics(
Namespace="MyApp",
MetricName="Orders",
StartTime=start,
EndTime=end,
Period=300,
Statistics=["Sum", "Average"]
)// --- TypeScript (AWS SDK v3) ---
import { CloudWatchClient, GetMetricStatisticsCommand } from "@aws-sdk/client-cloudwatch";
const cw = new CloudWatchClient({ region: "us-east-1" });
const now = new Date();
const oneHourAgo = new Date(now.getTime() - 3600000);
const resp = await cw.send(new GetMetricStatisticsCommand({
Namespace: "MyApp",
MetricName: "Orders",
StartTime: oneHourAgo,
EndTime: now,
Period: 300,
Statistics: ["Sum", "Average"]
}));Create a CloudWatch alarm that triggers on metric thresholds.
# --- Python (boto3) ---
import boto3
cw = boto3.client("cloudwatch", region_name="us-east-1")
cw.put_metric_alarm(
AlarmName="HighLatency",
ComparisonOperator="GreaterThanThreshold",
EvaluationPeriods=2,
MetricName="Latency",
Namespace="MyApp",
Period=300,
Statistic="Average",
Threshold=500.0,
AlarmActions=["arn:aws:sns:us-east-1:123456789:alerts"]
)// --- TypeScript (AWS SDK v3) ---
import { CloudWatchClient, PutMetricAlarmCommand } from "@aws-sdk/client-cloudwatch";
const cw = new CloudWatchClient({ region: "us-east-1" });
await cw.send(new PutMetricAlarmCommand({
AlarmName: "HighLatency",
ComparisonOperator: "GreaterThanThreshold",
EvaluationPeriods: 2,
MetricName: "Latency",
Namespace: "MyApp",
Period: 300,
Statistic: "Average",
Threshold: 500.0,
AlarmActions: ["arn:aws:sns:us-east-1:123456789:alerts"]
}));Create a new CloudWatch Logs log group.
# --- Python (boto3) ---
import boto3
logs = boto3.client("logs", region_name="us-east-1")
try:
logs.create_log_group(logGroupName="/aws/lambda/my-function")
except logs.exceptions.ResourceAlreadyExistsException:
pass// --- TypeScript (AWS SDK v3) ---
import { CloudWatchLogsClient, CreateLogGroupCommand } from "@aws-sdk/client-cloudwatch-logs";
const logs = new CloudWatchLogsClient({ region: "us-east-1" });
try {
await logs.send(new CreateLogGroupCommand({
logGroupName: "/aws/lambda/my-function"
}));
} catch (e) {
if (e.name !== "ResourceAlreadyExistsException") throw e;
}Write log entries to a log stream.
# --- Python (boto3) ---
import boto3
import time
logs = boto3.client("logs", region_name="us-east-1")
logs.put_log_events(
logGroupName="/aws/lambda/my-function",
logStreamName="2026/07/23/[$LATEST]abc123",
logEvents=[
{"message": "Request started", "timestamp": int(time.time() * 1000)},
{"message": "Processing complete", "timestamp": int(time.time() * 1000)}
]
)// --- TypeScript (AWS SDK v3) ---
import { CloudWatchLogsClient, PutLogEventsCommand } from "@aws-sdk/client-cloudwatch-logs";
const logs = new CloudWatchLogsClient({ region: "us-east-1" });
const now = Date.now();
await logs.send(new PutLogEventsCommand({
logGroupName: "/aws/lambda/my-function",
logStreamName: "2026/07/23/[$LATEST]abc123",
logEvents: [
{ message: "Request started", timestamp: now },
{ message: "Processing complete", timestamp: now + 100 }
]
}));Begin an async Logs Insights query across log streams.
# --- Python (boto3) ---
import boto3
logs = boto3.client("logs", region_name="us-east-1")
response = logs.start_query(
logGroupName="/aws/lambda/my-function",
startTime=int((time.time() - 3600) * 1000),
endTime=int(time.time() * 1000),
queryString="fields @timestamp, @message | stats count() by @message"
)
query_id = response["queryId"]// --- TypeScript (AWS SDK v3) ---
import { CloudWatchLogsClient, StartQueryCommand } from "@aws-sdk/client-cloudwatch-logs";
const logs = new CloudWatchLogsClient({ region: "us-east-1" });
const now = Date.now();
const resp = await logs.send(new StartQueryCommand({
logGroupName: "/aws/lambda/my-function",
startTime: Math.floor((now - 3600000) / 1000),
endTime: Math.floor(now / 1000),
queryString: "fields @timestamp, @message | stats count() by @message"
}));
const queryId = resp.queryId;Retrieve results from a Logs Insights query.
# --- Python (boto3) ---
import boto3
import time
logs = boto3.client("logs", region_name="us-east-1")
while True:
resp = logs.get_query_results(queryId=query_id)
if resp["status"] in ["Complete", "Failed"]:
print(resp["results"])
break
time.sleep(1)// --- TypeScript (AWS SDK v3) ---
import { CloudWatchLogsClient, GetQueryResultsCommand } from "@aws-sdk/client-cloudwatch-logs";
const logs = new CloudWatchLogsClient({ region: "us-east-1" });
let status = "Running";
while (status === "Running") {
const resp = await logs.send(new GetQueryResultsCommand({ queryId }));
status = resp.status || "";
if (status === "Complete" || status === "Failed") {
console.log(resp.results);
}
await new Promise(r => setTimeout(r, 1000));
}Filter and stream log events from a log stream.
# --- Python (boto3) ---
import boto3
logs = boto3.client("logs", region_name="us-east-1")
response = logs.filter_log_events(
logGroupName="/aws/lambda/my-function",
logStreamNamePrefix="2026/07/23/",
filterPattern="[ERROR]",
limit=50
)
for event in response["events"]:
print(event["message"])// --- TypeScript (AWS SDK v3) ---
import { CloudWatchLogsClient, FilterLogEventsCommand } from "@aws-sdk/client-cloudwatch-logs";
const logs = new CloudWatchLogsClient({ region: "us-east-1" });
const resp = await logs.send(new FilterLogEventsCommand({
logGroupName: "/aws/lambda/my-function",
logStreamNamePrefix: "2026/07/23/",
filterPattern: "[ERROR]",
limit: 50
}));
resp.events?.forEach(evt => console.log(evt.message));Create a CloudWatch dashboard with metrics and graphs.
# --- Python (boto3) ---
import boto3
import json
cw = boto3.client("cloudwatch", region_name="us-east-1")
dashboard_body = {
"widgets": [{
"type": "metric",
"properties": {
"metrics": [["MyApp", "Orders", {"stat": "Sum"}]],
"period": 300,
"stat": "Sum",
"region": "us-east-1",
"title": "Order Count"
}
}]
}
cw.put_dashboard(
DashboardName="MyDashboard",
DashboardBody=json.dumps(dashboard_body)
)// --- TypeScript (AWS SDK v3) ---
import { CloudWatchClient, PutDashboardCommand } from "@aws-sdk/client-cloudwatch";
const cw = new CloudWatchClient({ region: "us-east-1" });
const dashboardBody = {
widgets: [{
type: "metric",
properties: {
metrics: [["MyApp", "Orders", { stat: "Sum" }]],
period: 300,
stat: "Sum",
region: "us-east-1",
title: "Order Count"
}
}]
};
await cw.send(new PutDashboardCommand({
DashboardName: "MyDashboard",
DashboardBody: JSON.stringify(dashboardBody)
}));Automatically delete logs after a retention period.
# --- Python (boto3) ---
import boto3
logs = boto3.client("logs", region_name="us-east-1")
logs.put_retention_policy(
logGroupName="/aws/lambda/my-function",
retentionInDays=7
)// --- TypeScript (AWS SDK v3) ---
import { CloudWatchLogsClient, PutRetentionPolicyCommand } from "@aws-sdk/client-cloudwatch-logs";
const logs = new CloudWatchLogsClient({ region: "us-east-1" });
await logs.send(new PutRetentionPolicyCommand({
logGroupName: "/aws/lambda/my-function",
retentionInDays: 7
}));Emit structured metrics using Embedded Metric Format as a log line.
# --- Python (boto3) ---
import json
# EMF log line emitted to stdout or structured logger
emf_log = {
"_aws": {
"CloudWatchMetrics": [{
"Namespace": "MyApp",
"Dimensions": [["Service"]],
"Metrics": [{"Name": "Latency", "Unit": "Milliseconds"}]
}]
},
"Service": "api-gateway",
"Latency": 145
}
print(json.dumps(emf_log))// --- TypeScript (AWS SDK v3) ---
// EMF log line emitted to stdout or structured logger
const emfLog = {
_aws: {
CloudWatchMetrics: [{
Namespace: "MyApp",
Dimensions: [["Service"]],
Metrics: [{ Name: "Latency", Unit: "Milliseconds" }]
}]
},
Service: "api-gateway",
Latency: 145
};
console.log(JSON.stringify(emfLog));Create an alarm that combines the state of multiple alarms.
# --- Python (boto3) ---
import boto3
cw = boto3.client("cloudwatch", region_name="us-east-1")
cw.put_composite_alarm(
AlarmName="SystemHealth",
AlarmRule="(arn:aws:cloudwatch:us-east-1:123456789:alarm:HighLatency OR arn:aws:cloudwatch:us-east-1:123456789:alarm:HighError)",
ActionsEnabled=True,
AlarmActions=["arn:aws:sns:us-east-1:123456789:alerts"]
)// --- TypeScript (AWS SDK v3) ---
import { CloudWatchClient, PutCompositeAlarmCommand } from "@aws-sdk/client-cloudwatch";
const cw = new CloudWatchClient({ region: "us-east-1" });
await cw.send(new PutCompositeAlarmCommand({
AlarmName: "SystemHealth",
AlarmRule: "(arn:aws:cloudwatch:us-east-1:123456789:alarm:HighLatency OR arn:aws:cloudwatch:us-east-1:123456789:alarm:HighError)",
ActionsEnabled: true,
AlarmActions: ["arn:aws:sns:us-east-1:123456789:alerts"]
}));Wrap an async operation to trace it as an X-Ray subsegment.
# --- Python (boto3) ---
from aws_xray_sdk.core import xray_recorder
@xray_recorder.capture("fetch_user")
def fetch_user(user_id):
# Your async or sync call here
# X-Ray subsegment automatically created and closed
return {"id": user_id, "name": "Alice"}
result = fetch_user("123")// --- TypeScript (AWS SDK v3) ---
import AWSXRay from "aws-xray-sdk-core";
// Wrap an async function to trace it
const fetchUser = AWSXRay.captureAsyncFunc("fetch_user", async (user_id) => {
// Your async operation here
return { id: user_id, name: "Alice" };
});
const result = await fetchUser("123");Enumerate custom metrics with pagination.
# --- Python (boto3) ---
import boto3
cw = boto3.client("cloudwatch", region_name="us-east-1")
paginator = cw.get_paginator("list_metrics")
for page in paginator.paginate(Namespace="MyApp"):
for metric in page["Metrics"]:
print(metric["MetricName"])// --- TypeScript (AWS SDK v3) ---
import { CloudWatchClient, ListMetricsCommand } from "@aws-sdk/client-cloudwatch";
const cw = new CloudWatchClient({ region: "us-east-1" });
let nextToken: string | undefined;
do {
const resp = await cw.send(new ListMetricsCommand({
Namespace: "MyApp",
NextToken: nextToken
}));
resp.Metrics?.forEach(m => console.log(m.MetricName));
nextToken = resp.NextToken;
} while (nextToken);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 atualização: 23 de jul. de 2026