CloudWatch Logs and Logs Insights

When something breaks at 2 a.m., the logs are what tell you what happened, but if they’re spread over ten servers and you have to log in to each one, they’re not much help. CloudWatch Logs Insights lets you query all of them from one place, in seconds, with a few lines of query language.

You’ll run a small app that writes JSON request logs, ship those logs with the CloudWatch agent and set retention, and then use them to answer real questions like which pages fail, how slow checkout is and what happened in the last five minutes. At the end you’ll turn the errors into a metric you can put an alarm on.

TimeYou needBy the end you can
60 minutes (one small instance and five interface endpoints for under an hour)Lesson 23 done (saat-alerts, the agent parameter and policy), Start-SsmEndpoints.ps1 and Stop-SsmEndpoints.ps1, your laptop signed in as saat-admin. Cost: about USD 0.20, mostly endpoints; the logs themselves are a few MB.Ship log files with the CloudWatch agent, set log retention, write Logs Insights queries using filter, stats and bin, and create a metric filter that counts errors.

What it is, in one line

CloudWatch Logs Insights is a query tool for the log data in CloudWatch Logs, where a short pipe-based query lets you filter, group and count log events from many servers at once.

In Simple Words

The school register

Every class in a school keeps a register of who came, when, and who was late. If the principal asks “how many children were late on Monday across all classes?”, somebody has to go through every register page by page. Now imagine all those registers get copied into one big book every few seconds, and the book comes with a helper who can answer “late on Monday, grouped by class” in seconds. CloudWatch Logs is that big book and Logs Insights is the helper, while retention is how many months you keep the book before you throw the old pages away.

Engineer's View

How CloudWatch Logs really works

Logs are kept in log groups, usually one per app or source such as /saat/app, and each group is made of log streams, usually one per instance or container. Every event has a timestamp and a message. You set retention on each log group, and the default is never expire, which is the thing that surprises people most when the bill arrives.

The CloudWatch agent tails files and sends the events with PutLogEvents, and logs also come in from Lambda, ECS, VPC Flow Logs, CloudTrail and Route 53 query logs. If the agent runs in a private subnet it needs either the logs interface endpoint or NAT.

A Logs Insights query is a set of commands joined with pipes: fields, filter, stats, sort, limit and parse. It picks up JSON fields on its own, and field names are case-sensitive. You pay for every GB it scans, so keep the time range and the list of log groups narrow.

Metric filters turn matching events into CloudWatch metrics that you can alarm on, and Live Tail shows you new events as they come in.

How it works, step by step

This is the path one log line takes in the lab.

1The app writes a JSON line

Every request becomes one line in /var/log/saat-app.log, for example {"path": "/checkout", "status": 503, "ms": 712}, and having structured logs like this makes every step after it easier.

CloudWatch Logs Insights flow: app log file, agent, log group, queries

2The agent ships it

The agent tails that file and sends batches through the logs endpoint to the /saat/app log group, with one stream per instance ID.

3Retention keeps the cost in check

The agent config sets 7 days. In production people often keep 30 to 90 days in CloudWatch and put long-term archives in S3.

4You ask questions

Most of your daily work is covered by these four queries:

Four CloudWatch Logs Insights queries: latest events, errors by page, speed, text search

Begin every investigation with the narrowest time range you can manage, because the query runs faster and costs less and old noise stays out of the answer.

✅ Checkpoint: You can explain log groups, streams and retention, why private servers need the logs endpoint, and how a pipe-based query is put together.

Hands-on lab: ship logs and query them with CloudWatch Logs Insights

Before you run any command, double-check it

Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.

Start the usual way. This lab adds two endpoints of its own, one for CloudWatch Logs and one for metrics:

cd C:\aws-lab
aws login --profile saat-admin
$env:AWS_PROFILE = 'saat-admin'
$env:Path += ';C:\Program Files\Amazon\SessionManagerPlugin\bin'
$v = Get-Content C:\aws-lab\saat-vpc.json | ConvertFrom-Json
.\Start-SsmEndpoints.ps1
$extra = foreach ($svc in 'logs', 'monitoring') {
  aws ec2 create-vpc-endpoint --vpc-id $v.VpcId --vpc-endpoint-type Interface --service-name com.amazonaws.ap-south-1.$svc --subnet-ids $v.PrivateA --security-group-ids $v.EndpointSg --private-dns-enabled --tag-specifications "ResourceType=vpc-endpoint,Tags=[{Key=Name,Value=saat-$svc-ep},{Key=course,Value=saatvedha-aws},{Key=lesson,Value=24}]" --query VpcEndpoint.VpcEndpointId --output text
}
do { Start-Sleep 15; $s = aws ec2 describe-vpc-endpoints --vpc-endpoint-ids $extra --query "VpcEndpoints[].State" --output text } until ($s -notmatch 'pending')
$s

You should see this:

available       available

1Add a logs section to the agent config

Paste this whole block:

@'
{
  "agent": { "metrics_collection_interval": 60 },
  "metrics": {
    "namespace": "CWAgent",
    "append_dimensions": { "InstanceId": "${aws:InstanceId}", "InstanceType": "${aws:InstanceType}" },
    "metrics_collected": { "mem": { "measurement": [ "mem_used_percent" ] } }
  },
  "logs": {
    "logs_collected": {
      "files": {
        "collect_list": [
          { "file_path": "/var/log/saat-app.log", "log_group_name": "/saat/app", "log_stream_name": "{instance_id}", "retention_in_days": 7 }
        ]
      }
    }
  }
}
'@ | Set-Content cwagent.json
aws ssm put-parameter --name AmazonCloudWatch-saat-linux --type String --value file://cwagent.json --overwrite --query Version --output text

You should see something like this:

2

Version 2 of the parameter now tells the agent to tail the app log, name the stream after the instance, and keep logs for 7 days.

2Launch log01 with the demo app

Paste this whole block:

$ud = @'
#!/bin/bash
dnf install -y amazon-cloudwatch-agent
cat > /usr/local/bin/saat-loggen.py <<'PY'
import json, random, time, datetime
paths = ['/', '/login', '/cart', '/checkout', '/api/orders']
codes = [200, 200, 200, 200, 200, 301, 404, 500, 503]
while True:
    s = random.choice(codes)
    rec = {"ts": datetime.datetime.now(datetime.timezone.utc).isoformat(), "level": "ERROR" if s >= 500 else "INFO",
           "path": random.choice(paths), "status": s, "ms": random.randint(5, 900), "user": "u" + str(random.randint(1, 40))}
    print(json.dumps(rec), flush=True)
    time.sleep(0.5)
PY
cat > /etc/systemd/system/saat-loggen.service <<'UNIT'
[Unit]
Description=saat demo log generator
[Service]
ExecStart=/usr/bin/python3 /usr/local/bin/saat-loggen.py
StandardOutput=append:/var/log/saat-app.log
Restart=always
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable --now saat-loggen
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c ssm:AmazonCloudWatch-saat-linux
'@
[IO.File]::WriteAllText('C:\aws-lab\log-userdata.sh', ($ud -replace "`r`n", "`n"))
$base = aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --query Parameter.Value --output text
$i = aws ec2 run-instances --image-id $base --instance-type t3.micro --subnet-id $v.PrivateA --security-group-ids $v.AppSg --iam-instance-profile Name=saat-ec2-ssm-profile --metadata-options HttpTokens=required --user-data file://log-userdata.sh --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=log01},{Key=course,Value=saatvedha-aws},{Key=lesson,Value=24}]' --query "Instances[0].InstanceId" --output text
do { Start-Sleep 20; $streams = aws logs describe-log-streams --log-group-name /saat/app --query "logStreams[].logStreamName" --output text 2>$null } until ($streams)
$streams
aws logs describe-log-groups --log-group-name-prefix /saat --query "logGroups[].[logGroupName,retentionInDays]" --output text

You should see something like this. It takes three or four minutes:

i-0e1f2a3b4c5d60031
/saat/app       7

The agent has created the log group with 7-day retention and opened a stream named after the instance. The demo app writes two lines a second, and roughly one in five is an error.

3Query the logs

Paste the helper function first and then the queries, but give it two or three minutes after step 2 so there’s some data to look at:

function Invoke-LogsQuery([string]$Group, [string]$Query, [int]$Minutes = 15) {
  $end = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
  $qid = aws logs start-query --log-group-name $Group --start-time ($end - $Minutes * 60) --end-time $end --query-string $Query --query queryId --output text
  do { Start-Sleep 2; $r = aws logs get-query-results --query-id $qid --output json | ConvertFrom-Json } until ($r.status -in 'Complete', 'Failed', 'Cancelled')
  if (-not $r.results) { '(no rows)'; return }
  foreach ($row in $r.results) { ($row | Where-Object { $_.field -ne '@ptr' } | ForEach-Object { "$($_.field)=$($_.value)" }) -join '  ' }
}
Invoke-LogsQuery /saat/app 'fields @timestamp, path, status, ms | sort @timestamp desc | limit 5'
Invoke-LogsQuery /saat/app 'filter status >= 500 | stats count(*) as errors by path | sort errors desc'
Invoke-LogsQuery /saat/app 'stats count(*) as requests, pct(ms, 95) as p95_ms by bin(5m)'

You should see something like this, though your numbers will be different:

@timestamp=2026-10-20 18:14:51.513  path=/cart  status=200  ms=118
@timestamp=2026-10-20 18:14:51.012  path=/checkout  status=503  ms=712
@timestamp=2026-10-20 18:14:50.511  path=/login  status=200  ms=64
@timestamp=2026-10-20 18:14:50.010  path=/api/orders  status=404  ms=331
@timestamp=2026-10-20 18:14:49.509  path=/  status=200  ms=27
path=/checkout  errors=31
path=/api/orders  errors=29
path=/login  errors=27
path=/cart  errors=26
path=/  errors=24
bin(5m)=2026-10-20 18:10:00.000  requests=600  p95_ms=856

Notice you never told CloudWatch about status, path or ms, because it found them in the JSON by itself. The helper removes the internal @ptr field and prints each row on one line. You can run the same queries in the console under Logs Insights and get charts too.

CloudWatch Logs Insights query on /saat/app counting errors by path with a bar chart
Here’s the same query in the console, where Logs Insights counts the errors by path and draws the chart for you.
CloudWatch Logs Insights lab output: errors by path, p95 latency, retention
Errors by page, p95 latency and retention. It should look something like this.

4Turn errors into a metric

Paste the whole block and wait three minutes:

aws logs put-metric-filter --log-group-name /saat/app --filter-name app-5xx --filter-pattern '{ $.status >= 500 }' --metric-transformations metricName=App5xx,metricNamespace=Saat/App,metricValue=1,defaultValue=0
Start-Sleep 180
aws cloudwatch get-metric-statistics --namespace Saat/App --metric-name App5xx --start-time (Get-Date).ToUniversalTime().AddMinutes(-10).ToString('o') --end-time (Get-Date).ToUniversalTime().ToString('o') --period 60 --statistics Sum --query "sort_by(Datapoints, &Timestamp)[].Sum" --output text

You should see something like this:

0.0     24.0    25.0    23.0

The first minute shows 0 because the filter only counts events that arrive after you create it. App5xx is now a normal CloudWatch metric, so an alarm like “more than 50 errors in 5 minutes, notify saat-alerts” is only one put-metric-alarm away.

✅ Checkpoint: /saat/app is getting logs with 7-day retention, the three queries return rows, and App5xx shows error counts per minute. Keep it all for the break lab.

Break It, Then Fix It

The first mistake gives you no answer at all, and the second gives you a bill that keeps growing every month.

1Break it: one capital letter

Run the error query again with Status in place of status:

Invoke-LogsQuery /saat/app 'filter Status >= 500 | stats count(*) as errors by path'

You should see this:

(no rows)
CloudWatch Logs problems: case-sensitive field returns no rows, log group that never expires
Both problems and their fixes. Something like this.

You get no error and no warning, only an empty result, because field names are case-sensitive and no event has a field called Status. In the middle of an incident that reads as “no errors happened”, which is about the worst wrong answer you could get.

Fix: check the real field names first, either with fields @message | limit 1 or from the discovered fields list in the console, and then filter:

Invoke-LogsQuery /saat/app 'fields @message | limit 1'
Invoke-LogsQuery /saat/app 'filter status >= 500 | stats count(*) as errors'

You should see something like this:

@message={"ts": "2026-10-20T18:19:02.811+00:00", "level": "INFO", "path": "/cart", "status": 200, "ms": 140, "user": "u17"}
errors=212

2Break it: a log group that never expires

Say someone creates a log group by hand for a new service:

aws logs create-log-group --log-group-name /saat/manual --tags course=saatvedha-aws,lesson=24
aws logs describe-log-groups --log-group-name-prefix /saat --query "logGroups[].[logGroupName,retentionInDays]" --output text

You should see this:

/saat/app       7
/saat/manual    None

None means it never expires, so every byte sent there is stored and billed forever, and in big accounts these forgotten groups add up to thousands of dollars a year. Fix: always set retention, and go looking for groups that don’t have it:

aws logs put-retention-policy --log-group-name /saat/manual --retention-in-days 30
aws logs describe-log-groups --query "logGroups[?retentionInDays==null].logGroupName" --output text

Once every log group has a retention period, the second command prints nothing.

Now clean up. When you delete a log group, its metric filters and stored events go with it:

aws logs delete-log-group --log-group-name /saat/app
aws logs delete-log-group --log-group-name /saat/manual
aws ec2 terminate-instances --instance-ids $i | Out-Null
aws ec2 delete-vpc-endpoints --vpc-endpoint-ids $extra | Out-Null
aws ec2 wait instance-terminated --instance-ids $i
.\Stop-SsmEndpoints.ps1
Remove-Item cwagent.json, log-userdata.sh
.\Find-LabResources.ps1

✅ Checkpoint: You watched a case mistake return “no rows” and fixed it by checking the field names, and you found a log group with no retention and fixed that too. The log groups, log01 and all the endpoints are gone.

This happened at work

The query that said there were no errors

This was during a concert ticket sale at a ticketing company, when checkout started failing for some customers. The on-call engineer ran a Logs Insights query for filter Level = "ERROR" over the last hour, got nothing back, told the incident channel the app was clean and went off to check the payment provider. Forty minutes later a developer ran the same query with level in lowercase and found 18,000 errors, all from a connection pool limit in the checkout service. The team had switched logging libraries a month before, and the field name had changed from Level to level without anyone noticing. After that the company set up a shared library of saved queries for each service that gets reviewed whenever logging changes, plus a metric filter and alarm for 5xx responses, so nobody has to hunt for errors by query in the first minutes of an incident.

Common mistakes and troubleshooting

MistakeWhat happensWhat to do
Wrong case in a field name“no rows”, which looks like “no errors”Check fields with fields @message | limit 1
Log groups with no retentionStorage grows and is billed foreverSet retention on every group; audit for null
Plain-text logs for apps you controlEvery query needs parse and regexLog JSON with consistent field names
Querying 30 days when you need 30 minutesSlow, expensive queriesNarrow time range and log groups first
Private servers without the logs endpoint or NATAgent can’t send; no streams appearAdd the logs interface endpoint
Finding errors only by querySlow response during incidentsMetric filter plus alarm for error counts

Interview questions

Click a question to open it. Each one is phrased the way an interviewer would ask it, and under it you’ll find why they ask it and one way you could answer in your own words.

Fresher level

1. Can you explain in simple words the difference between a log group and a log stream?

Why they ask this: They want to know you understand how CloudWatch Logs is laid out, since everything else you do with logs builds on it.

How you might answer: I think of a log group as a folder for one app or source, and the folder holds the retention setting and the permissions. Inside it, each log stream is the run of events from one source, usually one instance or one container, so if my web app runs on three servers I’d have one log group for the app with three log streams in it.

2. A developer asks you to get their application logs from an EC2 instance into CloudWatch. What would you do?

Why they ask this: They want to see you know the whole setup and not only the install step, because missing permissions or network access is the usual reason logs never turn up.

How you might answer: I’d install the CloudWatch agent on the instance and make sure the instance role is allowed to write logs, and then configure the agent with the files to collect, the log group name and the retention. After that I’d check the instance can reach the CloudWatch Logs endpoint and confirm new events are showing up in the log group.

3. You create a new log group and don’t change any settings. How long will AWS keep those logs?

Why they ask this: It’s a check on cost awareness, since a lot of teams pay for years of old logs only because nobody changed the default.

How you might answer: By default a log group never expires, so the logs stay forever and you keep paying to store them. So whenever I create a log group I set a retention period based on what the team needs.

2–5 years experience

4. The team wants to know which five pages of the app are the slowest. How would you find that with Logs Insights?

Why they ask this: They want proof you can write a query and not only say Logs Insights exists, and it helps if you mention scan cost.

How you might answer: I’d narrow the time range first, since Logs Insights charges for the data it scans, and then run something like stats avg(ms) as avg_ms, pct(ms, 95) as p95 by path | sort p95 desc | limit 5. I’d sort by p95 instead of the average, because the average hides the slow requests users complain about.

5. How would you explain a metric filter to a new team member, and when would you use one?

Why they ask this: They want to know you can turn logs into something you can alarm on, because linking logs to alerts is part of the daily job.

How you might answer: I’d tell them a metric filter watches the log events coming into a log group, and when an event matches a pattern it counts it or pulls a value out, then publishes that as a CloudWatch metric. So for example I’d count the lines containing ERROR, graph them, and put an alarm on the count so we hear about problems before users do.

6. Audit says you must keep application logs for seven years, but the budget is tight. How would you set that up?

Why they ask this: They want to see you know CloudWatch isn’t the cheap place for long-term storage, and that you can plan retention that meets the rule without blowing the budget.

How you might answer: I’d keep only a short retention in CloudWatch for day-to-day troubleshooting and stream the logs to S3 alongside, for example with a subscription filter and Firehose, or export them there. In S3 I’d add lifecycle rules that move older logs to Glacier, and turn on Object Lock if the auditors want proof the logs can’t be changed.

Senior level

7. Say you join a company with 40 microservices across 5 AWS accounts, and every team logs differently. How would you design logging for them?

Why they ask this: They’re looking for platform thinking across many teams, meaning standards, central visibility and cost control, and they’ll want to hear you thinking about sensitive data as well.

How you might answer: I’d start by agreeing a standard with the teams: structured JSON logs with a request ID, so you can follow one request across services, and a log group for each service and environment with retention enforced. Then I’d send the logs to a central log account using cross-account subscriptions or cross-account observability, and build saved queries and dashboards for each service. On top of that I’d add metric filters for the key errors and data protection policies to mask sensitive fields.

8. Your manager comes to you and says the CloudWatch Logs bill doubled this month. How would you find out why?

Why they ask this: They want a calm, data-driven approach to a cost problem, where you fix the source and not only the symptom.

How you might answer: I’d look at the IncomingBytes metric for each log group to see which groups and streams grew, and it’s usually debug logging left on after a release or an error stuck in a loop. I’d also check the retention settings and how much data Logs Insights queries are scanning. Then I’d fix the source, set retention, and consider the Infrequent Access log class for groups we rarely query.

Quick quiz

Q1. What is the default retention of a new log group?

  1. 1 day
  2. 30 days
  3. 1 year
  4. Never expire
Show answer

D — Always set retention explicitly.

Q2. Why did the Status query return no rows?

  1. No errors existed
  2. Field names are case-sensitive
  3. The log group was empty
  4. The agent was stopped
Show answer

B — The field is status, not Status.

Q3. Which command groups and counts results?

  1. fields
  2. filter
  3. stats
  4. limit
Show answer

C — stats count(*) by field groups and counts.

Q4. What do private-subnet servers need for the agent to send logs?

  1. A public IP
  2. The logs interface endpoint or NAT
  3. Port 22 open
  4. An S3 bucket
Show answer

B — The agent calls the CloudWatch Logs API.

Q5. What does a metric filter create?

  1. A dashboard
  2. A CloudWatch metric from matching events
  3. A log group
  4. An SNS topic
Show answer

B — You can then alarm on that metric.

Quick recap

  • Logs live in log groups and streams, and retention defaults to never expire.
  • The agent ships the files, and private servers need the logs endpoint to do it.
  • A Logs Insights query pipes together fields, filter, stats, sort and limit.
  • Field names are case-sensitive, so check them before you believe “no rows”.
  • Metric filters turn log patterns into metrics you can put alarms on.

Next lesson

Lesson 25: CloudTrail: who did what, and when → Next you’ll use CloudTrail to find out who changed a security group, set up a trail to S3, and query events the way an investigator would.

Further reading: CloudWatch Logs Insights

Want to go deeper into CloudWatch Logs Insights? Read Analyzing log data with CloudWatch Logs Insights and CloudWatch Logs Insights query syntax. You can also see the full plan for this course on the AWS Cloud Administration course page.

Scroll to Top

This website uses cookies

We use a few cookies to keep this site working. If you allow it, we also use Google Analytics to count visits so we can improve our lessons. You can accept all, deny the optional ones, or choose what to allow.