Log Analysis in Practice
Put grep, sort, uniq, cut and awk together to investigate a real incident from raw logs. Learn the common log formats, a step-by-step investigation method (how bad, since when, who, what), error rates over time, slowest endpoints, rotated and compressed logs, and JSON logs.
Why logs, and why the command line
When something breaks in production, logs are the record of what actually happened. Dashboards and log platforms (Grafana, Kibana, Datadog, CloudWatch) are great, but they can be down, delayed, or not set up for the server in front of you. The command line always works, and interviewers love to test it with "here's a log file, tell me what's wrong".
This lesson brings together everything from this module: grep, cut, sort, uniq, awk and pipes.
Know your log format
Before analysing a log, look at a few lines and work out what each part means.
Web server access logs (nginx, Apache)
Most web servers use the combined log format:
10.0.3.213 - - [24/Nov/2026:13:00:22 +0530] "POST /.env HTTP/1.1" 404 530 "-" "Mozilla/5.0" 0.148With awk's default whitespace splitting, the fields are:
| Field | Value | Meaning |
|---|---|---|
$1 | 10.0.3.213 | client IP address |
$2, $3 | - - | identity and user (almost always -) |
$4 | [24/Nov/2026:13:00:22 | time (with the [), $5 is the time zone |
$6 | "POST | method (with the ") |
$7 | /.env | the requested path |
$8 | HTTP/1.1" | protocol |
$9 | 404 | status code |
$10 | 530 | response size in bytes |
$11 | "-" | referrer |
$12+ | "Mozilla/5.0" | user agent (can contain spaces!) |
$NF | 0.148 | request time in seconds, if the server is configured to log it |
HTTP status codes
| Range | Meaning | Typical cause |
|---|---|---|
2xx | success | |
3xx | redirect | normal (http to https, moved pages) |
4xx | client error | 404 wrong URL, 401/403 not allowed, 429 too many requests |
5xx | server error | 500 app crashed, 502 upstream down, 503 overloaded, 504 upstream too slow |
5xx is what wakes engineers up. A spike in 502/504 almost always means the application behind the web server is down or too slow.
Other formats you'll meet
| Log | Example line | Where |
|---|---|---|
| syslog | Nov 24 13:02:11 web-01 sshd[812]: Failed password for root from 203.0.113.9 | /var/log/syslog, /var/log/auth.log |
| application | 2026-11-24 13:02:11 ERROR [worker] payment failed order_id=ORD-200009 | app-specific |
| JSON | {"time":"2026-11-24T13:02:11Z","level":"error","msg":"payment failed"} | containers, cloud apps |
| journald | read with journalctl | systemd services |
An investigation method
Random grepping wastes time. Answer these questions in order:
Four questions for every incident
Below, each step uses a real 6,000-line access log from the lab.
1. How bad is it?
wc -l < access.log
awk '{print $9}' access.log | sort | uniq -c | sort -rn6000
5553 200
173 404
136 502
53 503
52 504
33 5006,000 requests. Most succeeded, but 502, 503, 504 and 500 add up to a few hundred server errors. The 404s are mostly bots probing for files like /.env, background noise on any public server.
Turn it into one number, the error rate:
awk '$9 >= 500 {n++} END {printf "%d of %d requests failed (%.1f%%)\n", n, NR, n*100/NR}' access.log274 of 6000 requests failed (4.6%)4.6% of all requests failed. "Checkout is broken" becomes a precise statement for the incident channel.
Is it still happening? Look at the end of the log: tail -n 50 access.log | awk '{print $9}' | sort | uniq -c, or follow it live with tail -f access.log | grep '" 50[0-9] '.
2. Since when?
Build a timeline: errors per minute. The time is in field 4 ([24/Nov/2026:13:00:22), and characters 14 to 18 of it are the hour and minute:
awk '$7 ~ /api\/checkout/ && $9 >= 500 {print substr($4, 14, 5)}' access.log | sort | uniq -c | head -5| Part | Does |
|---|---|
$7 ~ /api\/checkout/ && $9 >= 500 | checkout requests that returned a server error |
substr($4, 14, 5) | take HH:MM from the time field |
sort | uniq -c | count errors per minute, in time order |
5 14:00
4 14:01
6 14:02
3 14:03
4 14:04Checkout errors start at 14:00 exactly, and continue every minute. A clean start on the hour is a strong hint: a deployment, a cron job or a config change at 14:00. That's what to check next.
3. Who and what is affected?
Which endpoints fail?
awk '$9 >= 500 {print $7}' access.log | sort | uniq -c | sort -rn | head -3 241 /api/checkout
33 /api/searchAlmost all errors are on /api/checkout. The few /api/search errors are a separate, smaller problem (they started earlier: grep -m1 '" 50[0-9] ' access.log shows the first one at 13:10).
Which endpoints are slow? The request time is the last field:
awk '{sum[$7] += $NF; n[$7]++} END {for (p in sum) printf "%-20s %6.3f s\n", p, sum[p]/n[p]}' access.log | sort -k2 -nr | head -4| Part | Does |
|---|---|
sum[$7] += $NF; n[$7]++ | total time and request count per path |
printf ... sum[p]/n[p] | average time per path |
sort -k2 -nr | slowest first |
/api/checkout 1.270 s
/admin 0.153 s
/.env 0.139 s
/old-page 0.136 sCheckout averages 1.27 seconds when everything else answers in about 0.15. Its slowest requests take almost 5 seconds (awk '{print $NF, $7}' access.log | sort -rn | head): the backend is timing out, which matches the 504 errors.
Who is sending traffic? awk '{print $1}' access.log | sort | uniq -c | sort -rn | head shows the busiest client IPs. A single IP with a huge share could be an attack, a broken client in a retry loop, or simply your load balancer.
4. Why?
Access logs show what failed. The why is usually somewhere else:
- the application's own log at the same minute:
grep "14:00" /var/log/shop/app.log, - the service's journal:
journalctl -u shop --since "13:55" --until "14:05", - what changed at 14:00: deployments,
ls -lt /etc/shopapp,last(logins), cron (grep CRON /var/log/syslog), - system resources: disk full, memory (
dmesg | grep -i "out of memory").
How bad is it?
Count the total requests and how many of them failed with a 5xx error.
Why we do this: The first question in every incident is "how big is the impact?". Counting total requests and errors from the log gives the incident channel a real number within a minute.
Get a feel for the log first:
head -5 /var/log/nginx/access.log
wc -l /var/log/nginx/access.logCount requests per status code. This pipeline is worth memorising:
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rnsort | uniq -c counts identical lines, and sort -rn puts the biggest numbers first.
- Write the total number of requests into
/root/answers/total.txt. - Write the number of 5xx responses (status 500 to 599) into
/root/answers/errors-5xx.txt.
Each file should contain just the number.
Expected result: Two files in /root/answers, each containing a single number that matches the log.
Hint: the commands, explained
wc -l < /var/log/nginx/access.log > /root/answers/total.txt
awk '$9 >= 500 && $9 <= 599' /var/log/nginx/access.log | wc -l > /root/answers/errors-5xx.txtWhat each part does
wc -l < LOG: total number of lines = total requests.awk '$9 >= 500 && $9 <= 599': in the nginx log, field 9 is the HTTP status. Keep lines with a 5xx status (server errors).| wc -l: count them. Each number goes into its own answer file.
Who is hammering us?
Find the three IP addresses sending the most requests.
Why we do this: A handful of IP addresses sending most of the traffic usually means a scraper, a misbehaving client or an attack. Finding them tells us what to rate-limit or block at the load balancer.
A few IP addresses may be sending far more traffic than everyone else, a scraper or an attack. Find them.
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | headSomeone is also scanning for well-known weak spots (/wp-login.php, /.env), which shows up as 404s:
grep '" 404 ' /var/log/nginx/access.log | awk '{print $7}' | sort | uniq -c | sort -rnWrite the top 3 IP addresses by number of requests, one per line, most requests first, into /root/answers/top-ips.txt. Only the IPs, no counts.
Expected result: top-ips.txt lists three IP addresses, the busiest first.
Hint
Add | head -3 | awk '{print $2}' to the first pipeline, because after uniq -c the count is field 1 and the IP is field 2.
Which endpoints are failing and slow?
Identify the broken endpoint and the minute it started failing.
Why we do this: Knowing which endpoint broke and when it started points straight at the cause: a deployment, a dependency outage or a config change made at that minute.
Now find what's actually broken. Count 5xx errors per endpoint:
awk '$9 >= 500 {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rnAnd compute the average response time per endpoint with an awk associative array:
awk '{sum[$7] += $NF; n[$7]++} END {for (p in sum) printf "%.3f %s\n", sum[p]/n[p], p}' /var/log/nginx/access.log | sort -rnWhen did it start? Look at the errors per minute for the worst endpoint (field $4 holds the time):
grep '/api/checkout' /var/log/nginx/access.log | awk '$9 >= 500 {print substr($4, 14, 5)}' | sort | uniq -c | head- Write the path of the endpoint with the most 5xx errors into
/root/answers/broken-endpoint.txt. - Write the time (HH:MM) of its first 5xx error into
/root/answers/first-error.txt.
Expected result: broken-endpoint.txt contains the path, and first-error.txt contains a time like 14:00.
Extracting a time window
Logs are in time order, so a time window is a range of lines:
awk '$4 >= "[24/Nov/2026:14:00" && $4 < "[24/Nov/2026:14:30"' access.log # string comparison works here
sed -n '/24\/Nov\/2026:14:00/,/24\/Nov\/2026:14:30/p' access.log # from first match to first match
grep "24/Nov/2026:14:0[0-9]" access.log # 14:00 to 14:09For syslog-style logs, journalctl --since "2026-11-24 14:00" --until "14:30" is easier.
Rotated and compressed logs
Log files are rotated (usually nightly by logrotate): access.log is today, access.log.1 yesterday, then access.log.2.gz, access.log.3.gz and so on, compressed. To search across all of them:
zgrep '" 502 ' /var/log/nginx/access.log* # handles .gz and plain files
zcat -f /var/log/nginx/access.log* | awk '$9 >= 500' | wc -l # -f passes plain files through unchangedJSON logs and jq
Modern applications and containers often log JSON, one object per line:
{"time":"2026-11-24T14:00:03Z","level":"error","route":"/api/checkout","ms":4990,"msg":"upstream timeout"}grep can find text in it, but jq understands the structure:
jq -c 'select(.level == "error")' app.json # only error entries
jq -r '.route' app.json | sort | uniq -c | sort -rn # requests per route
jq -r 'select(.ms > 1000) | [.time, .route, .ms] | @tsv' app.json # slow requests as columns-c prints each result on one line, -r prints raw strings without quotes, and select() filters. On Kubernetes, kubectl logs pod-name | jq ... works the same way.
A cheat sheet
| Question | Command |
|---|---|
| total requests | wc -l access.log |
| status code breakdown | awk '{print $9}' access.log | sort | uniq -c | sort -rn |
| error rate | awk '$9>=500{n++} END{print n*100/NR "%"}' access.log |
| errors per minute | awk '$9>=500{print substr($4,14,5)}' access.log | uniq -c |
| top failing paths | awk '$9>=500{print $7}' access.log | sort | uniq -c | sort -rn | head |
| top client IPs | awk '{print $1}' access.log | sort | uniq -c | sort -rn | head |
| slowest requests | awk '{print $NF, $7}' access.log | sort -rn | head |
| first error | grep -m1 '" 5[0-9][0-9] ' access.log |
| failed SSH logins | grep "Failed password" /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn |
| all rotated logs | zgrep PATTERN /var/log/nginx/access.log* |
Build every pipeline step by step, checking the output at each stage, and write down what you find with times as you go ("14:00 checkout 5xx starts, 241 errors, avg 1.27 s"). During an incident, a clear timeline is worth more than any single command.
"Here's an access log. Find the top 10 IPs." awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10.
"How many 5xx errors per minute?" awk '$9 >= 500 {print substr($4, 14, 5)}' access.log | sort | uniq -c.
"What's the difference between a 502 and a 504?" Both mean the web server couldn't get a good answer from the application behind it: 502 means it got an invalid response or none at all (the app is down or crashed), 504 means the app didn't answer in time (too slow).
"How do you search compressed rotated logs?" zgrep, or zcat -f access.log* | grep ....
Summary
- Learn the format first: in the nginx combined format,
$1IP,$4time,$7path,$9status,$NFrequest time (if logged). - Investigate in order: how bad (error rate), since when (errors per minute), who/what (paths, clients, slow endpoints), why (app logs, journal, recent changes).
sort | uniq -c | sort -rnand awk arrays (sum[$7] += $NF) answer most questions.zgrepandzcat -fsearch rotated logs;jqhandles JSON logs.
Practise all of it now in the incident lab.
Quick quiz
You've practised everything in this lesson
Every task was checked on your own machine. You can end the lab, or keep experimenting in the terminal.