CloudWatch for developers: Logs Insights queries, metric filters and alarms
Ten CloudWatch Logs Insights queries for JSON logs from a Go service, a metric filter that counts 5xx responses, and an alarm that emails you or posts to Slack through SNS. Terraform and Go, with Mumbai prices.
A lot of developers open CloudWatch only when something is already broken, scroll through a log stream for a while, give up and add more fmt.Println. CloudWatch can do a lot better than that if your logs are JSON. You can query them like a small database, turn a log pattern into a metric, and get an email or a Slack message when that metric goes bad.
In this blog we will look at three things. Ten Logs Insights queries I'd keep saved for any Go service. A metric filter that counts 5xx responses. And an alarm on it that goes to SNS, then to email or Slack. Level is intermediate. You need a service writing logs to CloudWatch, for example shorty on ECS from Deploying a Go API to ECS Fargate behind an ALB with Terraform.
Versions: Terraform 1.17.1, AWS provider 6.73.0, Go 1.27.3 with aws-sdk-go-v2 cloudwatchlogs 1.92.2. I validated the Terraform and built the Go code. I didn't run the queries or create the alarm against an account for this post, so if a query gives you a syntax error or you have any doubts, tell me. Prices are for ap-south-1 (Mumbai) from the AWS Price List API on 19 November 2026.
💻 The full code for this tutorial is on GitHub: FenixAra/tutorials/AWS/CloudWatch/cloudwatch-for-developers-logs-insights-queries-metric-filters-and-alarms. Clone it and run each step yourself.
What the logs look like
Shorty logs with log/slog and the JSON handler. Its request middleware writes one line per request:
log.InfoContext(r.Context(), "request",
"method", r.Method,
"path", r.URL.Path,
"status", rec.status,
"duration_ms", time.Since(start).Milliseconds(),
"request_id", RequestIDFrom(r.Context()),
)
I wrote a tiny program with the same calls to see the exact lines. This is the real output:
{"time":"2026-11-19T12:17:09.687515+05:30","level":"INFO","msg":"request","method":"GET","path":"/golang","status":302,"duration_ms":3,"request_id":"9f1c2a7e"}
{"time":"2026-11-19T12:17:09.687642+05:30","level":"INFO","msg":"request","method":"POST","path":"/links","status":503,"duration_ms":2004,"request_id":"4be0d913"}
{"time":"2026-11-19T12:17:09.687646+05:30","level":"ERROR","msg":"create link failed","err":"context deadline exceeded","request_id":"4be0d913"}
On ECS the awslogs log driver ships stdout to a log group. This is the part of the container definition that does it:
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/shorty",
"awslogs-region": "ap-south-1",
"awslogs-stream-prefix": "shorty",
"mode": "non-blocking",
"max-buffer-size": "25m"
}
}
Logs Insights finds the JSON keys by itself, so status, path, level and the rest become fields you can filter on. No parsing needed. This is actually the single best reason to log JSON.
One honest aside. My own blog doesn't send anything to CloudWatch. Ghost, MySQL and Caddy log through Docker's json-file driver with max-size: 10m and max-file: 3, and I read them with docker compose logs over SSM. For one box with one reader, that's enough. Once there are several tasks and they get replaced on every deploy, the logs have to live somewhere else, and that's where CloudWatch earns its money.
Ten Logs Insights queries
Pick the log group, pick a time range, paste. I keep all of these as saved queries, the list grow a bit every time something breaks.
Query 1, latest errors. The first thing I look at.
fields @timestamp, msg, err, request_id
| filter level = "ERROR"
| sort @timestamp desc
| limit 50
Query 2, status code breakdown.
filter msg = "request"
| stats count(*) as requests by status
| sort requests desc
Query 3, 5xx per minute. Switch to the Visualization tab and you get a chart.
filter msg = "request" and status >= 500
| stats count(*) as errors by bin(1m)
Query 4, error rate as a percentage. Counts lie when traffic changes. A percentage doesn't.
filter msg = "request"
| fields if(status >= 500, 1, 0) as is5xx
| stats sum(is5xx) * 100 / count(*) as error_pct by bin(5m)
Query 5, slowest endpoints, by p95.
filter msg = "request"
| fields if(startsWith(path, "/links") = 1, path, "/{code}") as route
| stats count(*) as n, avg(duration_ms) as avg_ms, pct(duration_ms, 95) as p95, max(duration_ms) as max_ms by method, route
| sort p95 desc
| limit 20
The if folds every short code redirect (/golang, /abc123) into one route. Without it you get one row per code and the table is useless. Do the same for any path with an ID in it.
Query 6, everything for one request. Take a request_id from query 1 and see the whole story.
fields @timestamp, level, msg, status, err
| filter request_id = "4be0d913"
| sort @timestamp asc
Query 7, top 404 paths. Broken links, or someone scanning you.
filter msg = "request" and status = 404
| stats count(*) as hits by path
| sort hits desc
| limit 20
Query 8, who logs the most. This one is about the bill. Ingestion costs $0.67 per GB in Mumbai, so a chatty task matters.
stats count(*) as lines, sum(messageSize(@message)) / 1000000 as mb by @logStream
| sort mb desc
| limit 20
Query 9, panics. Shorty's recover middleware logs msg as panic with the value and the path.
fields @timestamp, path, value
| filter msg = "panic"
| sort @timestamp desc
Query 10, lines that aren't JSON. Stack traces, a library that prints straight to stderr, startup noise. pattern groups similar lines so you see the ten kinds instead of ten thousand lines.
filter not ispresent(level)
| pattern @message
Insights charges per GB scanned, $0.0067 in Mumbai, and a query scans everything in the time range for the selected groups. See, short time range is cheaper and faster. I start with the last hour and widen only if I need to.
Running a query from Go
When I want a query in a script, say a daily report, I use the SDK. StartQuery returns an ID and you poll GetQueryResults until the status is Complete.
cw := cloudwatchlogs.NewFromConfig(cfg)
end := time.Now()
start, err := cw.StartQuery(ctx, &cloudwatchlogs.StartQueryInput{
LogGroupNames: []string{*group},
QueryString: aws.String(*query),
StartTime: aws.Int64(end.Add(-*since).Unix()),
EndTime: aws.Int64(end.Unix()),
})
if err != nil {
log.Fatal(err)
}
for {
time.Sleep(time.Second)
res, err := cw.GetQueryResults(ctx, &cloudwatchlogs.GetQueryResultsInput{QueryId: start.QueryId})
if err != nil {
log.Fatal(err)
}
switch res.Status {
case types.QueryStatusScheduled, types.QueryStatusRunning:
continue
case types.QueryStatusComplete:
printRows(res.Results)
if res.Statistics != nil {
fmt.Fprintf(os.Stderr, "scanned %.1f MB, %d records matched\n",
res.Statistics.BytesScanned/1e6, int64(res.Statistics.RecordsMatched))
}
return
default:
log.Fatalf("query ended with status %s", res.Status)
}
}
The times are Unix seconds, not milliseconds, which is a different unit from most other CloudWatch Logs APIs. printRows in the full code skips the @ptr field and prints a table with tabwriter. My first version called that helper print, which shadows Go's builtin. go vet didn't complain, but I renamed it anyway, it's the kind of thing that confuses the next reader.
go run ./cmd/insights -group /ecs/shorty -since 30m \
-query 'filter msg = "request" | stats count(*) by status'
A metric filter for 5xx
Queries are for when you're looking. For alerts you need a metric, and a metric filter makes one from log lines as they arrive. Here we count every request log with a status of 500 or more.
resource "aws_cloudwatch_log_group" "shorty" {
name = "/ecs/shorty"
retention_in_days = 30
}
resource "aws_cloudwatch_log_metric_filter" "http_5xx" {
name = "shorty-5xx"
log_group_name = aws_cloudwatch_log_group.shorty.name
pattern = "{ ($.msg = \"request\") && ($.status >= 500) }"
metric_transformation {
namespace = "Shorty"
name = "Http5xx"
value = "1"
default_value = "0"
unit = "Count"
}
}
default_value = "0" makes CloudWatch publish a zero when logs arrive but none match. Without it the metric has gaps, and alarms on gappy metrics behave strangely. You can't use default_value together with dimensions, so I keep this metric without any.
Set retention_in_days. A log group created by the awslogs driver keeps logs forever by default, and storage is $0.03 per GB-month. It's small per GB, but it never stops.
Before trusting pattern I check it against sample lines with test-metric-filter. It needs credentials but creates nothing.
aws logs test-metric-filter \
--filter-pattern '{ ($.msg = "request") && ($.status >= 500) }' \
--log-event-messages \
'{"level":"INFO","msg":"request","path":"/golang","status":302}' \
'{"level":"INFO","msg":"request","path":"/links","status":503}'
Only the second line should come back in matches.
The alarm and where it goes
resource "aws_sns_topic" "alerts" {
name = "shorty-alerts"
}
resource "aws_sns_topic_subscription" "email" {
topic_arn = aws_sns_topic.alerts.arn
protocol = "email"
endpoint = var.alert_email
}
resource "aws_cloudwatch_metric_alarm" "http_5xx" {
alarm_name = "shorty-5xx"
alarm_description = "shorty returned 5 or more 5xx responses a minute in 3 of the last 5 minutes"
namespace = "Shorty"
metric_name = "Http5xx"
statistic = "Sum"
period = 60
comparison_operator = "GreaterThanOrEqualToThreshold"
threshold = 5
evaluation_periods = 5
datapoints_to_alarm = 3
treat_missing_data = "notBreaching"
alarm_actions = [aws_sns_topic.alerts.arn]
ok_actions = [aws_sns_topic.alerts.arn]
}
"3 out of 5" (datapoints_to_alarm = 3, evaluation_periods = 5) is what keeps this quiet. One bad minute during a deploy doesn't page anyone. Three bad minutes in five does. ok_actions sends a second message when it recovers, which I like, because otherwise you're left wondering.
The email subscription stays PendingConfirmation until someone clicks the link AWS sends. Terraform says it's done well before that itself. Check your inbox and the spam folder.
For Slack, use Amazon Q Developer in chat applications, which is the new name for AWS Chatbot. The Terraform resource is still aws_chatbot_slack_channel_configuration. You have to authorise the Slack workspace once in the console, then:
resource "aws_chatbot_slack_channel_configuration" "alerts" {
count = local.slack ? 1 : 0
configuration_name = "shorty-alerts"
iam_role_arn = aws_iam_role.chatbot[0].arn
slack_team_id = var.slack_team_id
slack_channel_id = var.slack_channel_id
sns_topic_arns = [aws_sns_topic.alerts.arn]
guardrail_policy_arns = ["arn:aws:iam::aws:policy/ReadOnlyAccess"]
}
The role it assumes is in the full code. terraform fmt lined up the equals signs in that block for me, my hand-typed version was off by a couple of spaces. If you'd rather keep alert logic in the app, Sending Slack alerts only for golang errors that became 5xx responses does it from Go instead.
What it costs
Mumbai prices on 19 November 2026. Ingestion $0.67 per GB, storage $0.03 per GB-month, Insights $0.0067 per GB scanned. A custom metric like Http5xx is $0.30 a month and a standard alarm $0.10 a month. The free tier covers 5 GB of logs, 10 custom metrics and 10 alarms each month. SNS email is free for the first 1,000 notifications.
So a service that logs 10 GB a month pays about $3.35 for ingestion after the free 5 GB, plus a few cents for storage, and the alarm setup above fits in the free tier. The number to watch is ingestion. If query 8 shows one task logging most of it, look at what it logs at INFO level before you look at anything else.
Also put a budget alert on the account, as in Setting up a new AWS account safely. A debug flag left on in production is the classic way to find out what CloudWatch ingestion costs.