Learn / Linux / Text Processing
Lesson 15 of 74

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.

25 min read Report a problem Hands-on lab included 5-question quiz

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:

text
10.0.3.213 - - [24/Nov/2026:13:00:22 +0530] "POST /.env HTTP/1.1" 404 530 "-" "Mozilla/5.0" 0.148

With awk's default whitespace splitting, the fields are:

FieldValueMeaning
$110.0.3.213client IP address
$2, $3- -identity and user (almost always -)
$4[24/Nov/2026:13:00:22time (with the [), $5 is the time zone
$6"POSTmethod (with the ")
$7/.envthe requested path
$8HTTP/1.1"protocol
$9404status code
$10530response size in bytes
$11"-"referrer
$12+"Mozilla/5.0"user agent (can contain spaces!)
$NF0.148request time in seconds, if the server is configured to log it

HTTP status codes

RangeMeaningTypical cause
2xxsuccess
3xxredirectnormal (http to https, moved pages)
4xxclient error404 wrong URL, 401/403 not allowed, 429 too many requests
5xxserver error500 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

LogExample lineWhere
syslogNov 24 13:02:11 web-01 sshd[812]: Failed password for root from 203.0.113.9/var/log/syslog, /var/log/auth.log
application2026-11-24 13:02:11 ERROR [worker] payment failed order_id=ORD-200009app-specific
JSON{"time":"2026-11-24T13:02:11Z","level":"error","msg":"payment failed"}containers, cloud apps
journaldread with journalctlsystemd services

An investigation method

Random grepping wastes time. Answer these questions in order:

Four questions for every incident

1. How bad?error rate, is it still happening
2. Since when?the minute it started
3. Who / what?which endpoints, clients, servers
4. Why?correlate: deploys, config, errors in app logs

Below, each step uses a real 6,000-line access log from the lab.

1. How bad is it?

bash
wc -l < access.log
awk '{print $9}' access.log | sort | uniq -c | sort -rn
text
6000
   5553 200
    173 404
    136 502
     53 503
     52 504
     33 500

6,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:

bash
awk '$9 >= 500 {n++} END {printf "%d of %d requests failed (%.1f%%)\n", n, NR, n*100/NR}' access.log
text
274 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:

bash
awk '$7 ~ /api\/checkout/ && $9 >= 500 {print substr($4, 14, 5)}' access.log | sort | uniq -c | head -5
PartDoes
$7 ~ /api\/checkout/ && $9 >= 500checkout requests that returned a server error
substr($4, 14, 5)take HH:MM from the time field
sort | uniq -ccount errors per minute, in time order
text
      5 14:00
      4 14:01
      6 14:02
      3 14:03
      4 14:04

Checkout 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?

bash
awk '$9 >= 500 {print $7}' access.log | sort | uniq -c | sort -rn | head -3
text
    241 /api/checkout
     33 /api/search

Almost 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:

bash
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
PartDoes
sum[$7] += $NF; n[$7]++total time and request count per path
printf ... sum[p]/n[p]average time per path
sort -k2 -nrslowest first
text
/api/checkout         1.270 s
/admin                0.153 s
/.env                 0.139 s
/old-page             0.136 s

Checkout 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").
Try it · Task 1 of 3

How bad is it?

Count the total requests and how many of them failed with a 5xx error.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

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:

bash
head -5 /var/log/nginx/access.log
wc -l /var/log/nginx/access.log

Count requests per status code. This pipeline is worth memorising:

bash
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn

sort | uniq -c counts identical lines, and sort -rn puts the biggest numbers first.

2 · Your task
  1. Write the total number of requests into /root/answers/total.txt.
  2. 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
text
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.txt

What 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.
First start the lab machine in the terminal panel on the right.
Try it · Task 2 of 3

Who is hammering us?

Find the three IP addresses sending the most requests.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

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.

bash
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head

Someone is also scanning for well-known weak spots (/wp-login.php, /.env), which shows up as 404s:

bash
grep '" 404 ' /var/log/nginx/access.log | awk '{print $7}' | sort | uniq -c | sort -rn
2 · Your task

Write 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.

First start the lab machine in the terminal panel on the right.
Try it · Task 3 of 3

Which endpoints are failing and slow?

Identify the broken endpoint and the minute it started failing.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

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:

bash
awk '$9 >= 500 {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn

And compute the average response time per endpoint with an awk associative array:

bash
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 -rn

When did it start? Look at the errors per minute for the worst endpoint (field $4 holds the time):

bash
grep '/api/checkout' /var/log/nginx/access.log | awk '$9 >= 500 {print substr($4, 14, 5)}' | sort | uniq -c | head
2 · Your task
  1. Write the path of the endpoint with the most 5xx errors into /root/answers/broken-endpoint.txt.
  2. 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.

First start the lab machine in the terminal panel on the right.

Extracting a time window

Logs are in time order, so a time window is a range of lines:

text
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:09

For 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:

text
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 unchanged

JSON logs and jq

Modern applications and containers often log JSON, one object per line:

text
{"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:

text
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

QuestionCommand
total requestswc -l access.log
status code breakdownawk '{print $9}' access.log | sort | uniq -c | sort -rn
error rateawk '$9>=500{n++} END{print n*100/NR "%"}' access.log
errors per minuteawk '$9>=500{print substr($4,14,5)}' access.log | uniq -c
top failing pathsawk '$9>=500{print $7}' access.log | sort | uniq -c | sort -rn | head
top client IPsawk '{print $1}' access.log | sort | uniq -c | sort -rn | head
slowest requestsawk '{print $NF, $7}' access.log | sort -rn | head
first errorgrep -m1 '" 5[0-9][0-9] ' access.log
failed SSH loginsgrep "Failed password" /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn
all rotated logszgrep 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, $1 IP, $4 time, $7 path, $9 status, $NF request 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 -rn and awk arrays (sum[$7] += $NF) answer most questions.
  • zgrep and zcat -f search rotated logs; jq handles JSON logs.

Practise all of it now in the incident lab.

Check your understanding

Quick quiz

Feedback