Chapter 14: Logging and Light Observability
14.6 Searching — find the last error
Why: the problem
Suppose Flipkart's checkout shows 500 errors for five minutes during a sale. The on-call engineer has millions of log lines. Reading them one by one is impossible. She needs to search. On one server she uses grep, tail and awk. For JSON logs she uses jq. In CloudWatch she uses filter patterns and Logs Insights, which is a small query language. The goal is always the same: find the last error, see how many happened, and see the first one, because the first error is often the real cause. In this lesson you will practise the same search with all these tools.
What we will build
You will make a sample log file with good and bad lines, find the last error with grep and tail, count errors per minute with awk, search JSON logs with jq, and run the same search in CloudWatch with filter-log-events and a Logs Insights query.
What: every term in plain English
- grep — Linux command that prints lines that match a word or pattern.
- -i, -c, -n, -A — grep flags: ignore case, count, line number, lines after.
- tail / head — Show the last or first lines of a file.
- awk — A small tool to cut and count columns in text.
- jq — A tool to read and filter JSON on the command line.
- Filter pattern — CloudWatch syntax to match events, like ERROR or a JSON field.
- Logs Insights — CloudWatch query language: fields, filter, stats, sort, limit.
- First error — The earliest error in an incident. Often the root cause.
How: step by step
-
Make a sample log
for i in $(seq 1 50); do echo "2026-10-25 10:0$((i%10)):1$((i%6)) INFO GET /cart 200"; done > app.log; echo "2026-10-25 10:07:12 ERROR POST /pay 500 db timeout" >> app.log; echo "2026-10-25 10:09:40 ERROR POST /pay 500 db timeout" >> app.logWhat it does: 51 good lines and 2 errors.
Output
(no output) -
Find the last error
grep ERROR app.log | tail -n 1What it does: The latest error line.
Output
2026-10-25 10:09:40 ERROR POST /pay 500 db timeout -
Find the first error
grep -m 1 ERROR app.logWhat it does: -m 1 stops at the first match.
Output
2026-10-25 10:07:12 ERROR POST /pay 500 db timeout -
Count errors
grep -c ERROR app.logWhat it does: How many error lines.
Output
2 -
See context
grep -n -B 2 -A 1 "db timeout" app.log | headWhat it does: Line numbers and the lines around the error.
Output
50-2026-10-25 10:09:15 INFO GET /cart 200 52:2026-10-25 10:09:40 ERROR POST /pay 500 db timeout -
Errors per minute
grep ERROR app.log | awk '{print substr($2,1,5)}' | sort | uniq -cWhat it does: Groups errors by hour:minute.
Output
1 10:07 1 10:09
Example 1: Search JSON logs with jq
Stack. jq, JSON lines
Goal. Search JSON logs with jq.
app.jsonl
{"time":"2026-10-25T10:07:12Z","level":"ERROR","path":"/pay","status":500,"ms":3004,"msg":"db timeout"}
{"time":"2026-10-25T10:07:13Z","level":"INFO","path":"/cart","status":200,"ms":42,"msg":"ok"}
{"time":"2026-10-25T10:09:40Z","level":"ERROR","path":"/pay","status":500,"ms":3001,"msg":"db timeout"}
Commands
sudo apt-get install -y jq
jq -c 'select(.level=="ERROR")' app.jsonl
jq -r 'select(.status>=500) | .time + " " + .path + " " + .msg' app.jsonl
jq -s 'map(select(.level=="ERROR")) | length' app.jsonl
jq -s 'map(.ms) | add / length' app.jsonl
What each line does
select(.level=="ERROR")— Keep only objects whose level is ERROR.-c— Print each result on one line.-r— Raw text, no quotes.-s— Slurp: read all lines into one list, so we can count or average.map(.ms) | add / length— Average response time.
Green output
{"time":"2026-10-25T10:07:12Z","level":"ERROR","path":"/pay","status":500,"ms":3004,"msg":"db timeout"}
{"time":"2026-10-25T10:09:40Z","level":"ERROR","path":"/pay","status":500,"ms":3001,"msg":"db timeout"}
2026-10-25T10:07:12Z /pay db timeout
2026-10-25T10:09:40Z /pay db timeout
2
2016.3333333333333
Expected result. JSON logs are easy to filter by field. No fragile text matching.
Example 2: CloudWatch filter-log-events from the CLI
Stack. AWS CLI v2, CloudWatch Logs
Goal. CloudWatch filter-log-events from the CLI.
Commands
aws logs filter-log-events \
--log-group-name /loglab/wallet \
--start-time $(date -d "-30 min" +%s000) \
--filter-pattern "ERROR" \
--query "events[].[timestamp,message]" --output text | tail -n 3
aws logs filter-log-events --log-group-name /loglab/checkout \
--filter-pattern '{ $.status = 500 && $.path = "/pay" }' \
--query "length(events)"
What each line does
--start-time— Search only the last 30 minutes. Faster and cheaper.--filter-pattern "ERROR"— Text match on the word ERROR.'{ $.status = 500 ... }'— JSON filter: match fields inside JSON logs.--query "length(events)"— Count matches instead of printing them.
Green output
1761386832000 ERROR wallet debit failed order=77
1761386940000 ERROR upi timeout order=82
1761387001000 ERROR upi timeout order=90
14
Expected result. You found the last 3 wallet errors and 14 failed /pay calls.
Example 3: Logs Insights: errors per minute and the slowest calls
Stack. CloudWatch Logs Insights
Goal. Logs Insights: errors per minute and the slowest calls.
Query 1 (CloudWatch console > Logs Insights)
fields @timestamp, @message
| filter @message like /ERROR/
| sort @timestamp desc
| limit 20
Query 2: errors per minute
filter level = "ERROR"
| stats count(*) as errors by bin(1m)
| sort errors desc
Query 3: slowest paths
filter ispresent(ms)
| stats avg(ms) as avg_ms, max(ms) as max_ms, count(*) as calls by path
| sort max_ms desc
| limit 5
Run from CLI
QID=$(aws logs start-query --log-group-name /loglab/checkout \
--start-time $(date -d "-1 hour" +%s) --end-time $(date +%s) \
--query-string 'filter level = "ERROR" | stats count(*) by bin(1m)' \
--output text --query queryId)
sleep 5; aws logs get-query-results --query-id "$QID"
What each line does
fields— Pick which fields to show.filter— Keep only matching events.stats count(*) by bin(1m)— Count per one-minute bucket. Shows when the spike began.sort ... desc / limit— Biggest first, show only a few.start-query / get-query-results— Run Insights from the terminal; it is async, so we wait a bit.
Green output
bin(1m) errors
2026-10-25 10:07:00 9
2026-10-25 10:08:00 4
2026-10-25 10:09:00 1
path avg_ms max_ms calls
/pay 2210 3004 52
/cart 45 180 910
Expected result. The spike started at 10:07 and /pay is slow. Now you know where to look.
Verify: did it work?
-
Check jq is installed
jq --versionWhat it does: Prints the version.
Output
jq-1.7.1 -
Check Insights query status
aws logs describe-queries --status Complete --max-items 1 --query "queries[0].status"What it does: Your last query finished.
Output
"Complete"
When it is red 1
grep: app.log: No such file or directory
Cause. You are in the wrong folder.
Fix, step by step
- pwd
- cd ~/loglab
- ls *.log
When it is red 2
jq: error (at app.jsonl:2): Cannot index string with "level"
Cause. A line is plain text, not JSON.
Fix, step by step
- Find bad lines: grep -v "^{" app.jsonl
- Fix the app to always log JSON.
- Or skip bad lines: jq -R "fromjson? | select(.level==\"ERROR\")"
When it is red 3
Logs Insights: No data found for this time range
Cause. Wrong time range or wrong group selected.
Fix, step by step
- Pick the right log group in the drop down.
- Widen the time range to 3 hours.
- Run the query again.
Cleanup
-
Remove sample files
rm -f app.log app.jsonlWhat it does: Deletes the lab files.
Output
(no output)
Ravindra Bagale's Tip
Find the first error, not the last. The first error is often the real cause.
पहिला error शोधा, शेवटचा नाही. पहिला error बर्याचदा खरा कारण असतो.
पहला error खोजो, आखिरी नहीं. पहला error अक्सर असली कारण होता है.
Practice tasks
Easy Ignore case
Why: Some apps write error, some ERROR.
What to do: Use grep -i.
- grep -ic error app.log
Check: Count includes both.
Medium Top error messages
Why: Group by message to find the main problem.
What to do: Use Insights stats count(*) by msg.
- filter level="ERROR" | stats count(*) by msg | sort count(*) desc
Check: One message is clearly on top.
Hard Search two files by one time
Why: Match nginx and app at the same second.
What to do: grep "10:07:12" in both files.
- grep "10:07:12" /var/log/nginx/access.log app.log
Check: You see the same request in both.
Easy Say log search in two lines
Why: If you can say it simply, you understand it. Juniors and interviewers both want the short version first.
What to do: Write two short lines about log search for a fresher who knows only Linux, Git and Docker basics.
- Write the problem it solves.
- Write the one command or config line you use for it.
- Read it aloud to a friend.
Check: A fresher understands it without asking a question.
Easy Keep a throwaway log lab
Why: Practice needs a lab you can break. If it gets messy, you delete the containers and start again.
What to do: Run a small app in Docker that prints logs every second.
- docker run -d --name ticker busybox sh -c "while true; do date; sleep 1; done"
- docker logs -f ticker
- Press Ctrl+C, then docker rm -f ticker.
Check: You see one new time line every second.
Medium Do it on a second stack
Why: Logging ideas must work for Python, Node.js and Java. Only the library changes.
What to do: Repeat this lesson with a different language than the one you used first.
- If you used Python, use Node.js or Spring Boot now.
- Keep the same field names: time, level, msg, request_id.
- Compare the two outputs side by side.
Check: Both apps print the same fields in the same shape.
Medium Break it on purpose
Why: You must know the red error by face. In a real outage there is no time to read slowly.
What to do: Cause one error from the "When it is red" part of this lesson and fix it.
- Follow the error section.
- Copy the exact message into your notes.
- Write the fix in one line.
Check: You fixed it using only the steps, without searching the web.
Medium Write a one-page runbook
Why: At 2 a.m. nobody remembers log commands. A short page saves the on-call person.
What to do: Write a one-page runbook for this lesson.
- Title, when to use, exact commands, how to check, how to undo.
Check: A teammate can follow it alone.
Hard Explain it like an interview
Why: Interviewers want real stories, not definitions.
What to do: Record a 60 second answer about this lesson.
- Say the problem, the command you ran, the log line you found and the fix.
Check: Your answer has a real command and a real log line.
Hard Draw the flow top to bottom
Why: A drawing shows where a log line is born and where it ends up.
What to do: Draw this lesson as boxes from top to bottom.
- Start at the user click, go through the app, the log driver or agent, and end at the place you search.
Check: Each box matches a real command or file in this lesson.
Homework: try at home
Try at home
At home, write a Logs Insights query that shows the top 5 paths by count of status 500 in the last hour.
Recap
- grep, tail, awk and jq solve most searches on one server.
- JSON logs make field search exact.
- CloudWatch filter patterns search many servers.
- Logs Insights counts and groups like SQL.
- Find the first error, not only the last.
FAQ
Is Logs Insights expensive?
You pay per GB scanned. Use short time ranges and the right group.
Can I save Insights queries?
Yes, use Save in the console.
grep or jq for JSON?
jq, because it reads fields, not text.
Can Insights read plain text?
Yes, use parse to cut fields out of text.
What about Kibana or Grafana?
Same idea with other query languages: KQL in Kibana, LogQL in Grafana Loki.
Interview questions
-
How do you find the root cause in a big log?
Narrow the time window, filter errors, count per minute, read the first error and its context.
-
What is CloudWatch Logs Insights?
A query language for log groups with fields, filter, stats, sort and parse.
-
How do you search JSON logs on Linux?
With jq select on fields.
-
Filter pattern vs Insights?
Filter patterns match events and feed metric filters; Insights runs ad hoc analytics with stats.
-
How do you reduce query cost?
Short time range, specific log groups, filter early, limit results.
Quick quiz
Q1. How do you find the last error in a file?
grep ERROR app.log | tail -n 1.
Q2. How do you count errors?
grep -c ERROR.
Q3. Which tool filters JSON?
jq.
Q4. Which Insights command counts per minute?
stats count(*) by bin(1m).
Q5. Why look at the first error?
It is often the real cause; later errors are side effects.
Did you understand? Let us try it once more.
Revision card
Interview card