Build a Log File Analyzer
This project builds logstat.sh, a command-line tool that reads web server access logs and prints a report: how many requests there were, how many distinct visitors, how much data was sent, the share of successful and failed responses, the most requested paths, the busiest client IPs, the most frequent errors, and a small bar chart of requests per hour. It reads plain and gzip-compressed logs, any number of files at once or standard input, skips lines it cannot parse instead of crashing on them, and processes a million lines in about a second.
Lesson 181 showed how to answer individual questions about application logs with grep, awk, sort and uniq. This project combines those techniques into one reusable tool and focuses on a design question that matters for every log tool: how to read a large file only once and still produce many different statistics.
The Log Format
Apache and Nginx write access logs in the combined log format by default. Each request is one line:
203.0.113.10 - - [02/Dec/2026:09:12:02 +0530] "GET /css/site.css HTTP/1.1" 200 1840 "https://example.com/" "Mozilla/5.0"
| Part | Example | Meaning |
|---|---|---|
| Client IP | 203.0.113.10 | Address the request came from |
| Identity, user | - - | Rarely used; - means empty |
| Time | [02/Dec/2026:09:12:02 +0530] | When the request arrived, with the time zone offset |
| Request line | "GET /css/site.css HTTP/1.1" | Method, path (with query string) and protocol, in double quotes |
| Status | 200 | HTTP response code |
| Size | 1840 | Bytes in the response body; - when there was none |
| Referer | "https://example.com/" | Page that linked here |
| User agent | "Mozilla/5.0" | Browser or client software |
The common log format is the same without the last two quoted fields; the analyzer handles both.
A Sample Log to Work With
Save the following 20 lines as access.log. They include normal page views, a vulnerability scanner probing for /wp-login.php and /.env, server errors, a request with no request line ("-", which servers log when a client connects and sends nothing useful), a response with size -, and one line that is not a log entry at all:
203.0.113.10 - - [02/Dec/2026:09:12:01 +0530] "GET / HTTP/1.1" 200 5120 "-" "Mozilla/5.0"
203.0.113.10 - - [02/Dec/2026:09:12:02 +0530] "GET /css/site.css HTTP/1.1" 200 1840 "https://example.com/" "Mozilla/5.0"
198.51.100.7 - - [02/Dec/2026:09:15:40 +0530] "GET /courses/bash HTTP/1.1" 200 8300 "-" "Mozilla/5.0"
198.51.100.7 - - [02/Dec/2026:09:16:05 +0530] "GET /courses/bash?page=2 HTTP/1.1" 200 7950 "-" "Mozilla/5.0"
192.0.2.44 - - [02/Dec/2026:09:47:13 +0530] "GET /wp-login.php HTTP/1.1" 404 312 "-" "python-requests/2.31"
192.0.2.44 - - [02/Dec/2026:09:47:14 +0530] "GET /.env HTTP/1.1" 404 312 "-" "python-requests/2.31"
192.0.2.44 - - [02/Dec/2026:09:47:15 +0530] "GET /admin HTTP/1.1" 403 290 "-" "python-requests/2.31"
203.0.113.10 - - [02/Dec/2026:10:02:30 +0530] "POST /api/login HTTP/1.1" 200 412 "-" "Mozilla/5.0"
203.0.113.10 - - [02/Dec/2026:10:02:31 +0530] "GET /dashboard HTTP/1.1" 200 15020 "-" "Mozilla/5.0"
198.51.100.23 - - [02/Dec/2026:10:20:11 +0530] "GET /courses/python HTTP/1.1" 200 9100 "-" "Mozilla/5.0"
198.51.100.23 - - [02/Dec/2026:10:21:45 +0530] "POST /api/enroll HTTP/1.1" 500 98 "-" "Mozilla/5.0"
198.51.100.23 - - [02/Dec/2026:10:21:52 +0530] "POST /api/enroll HTTP/1.1" 500 98 "-" "Mozilla/5.0"
198.51.100.23 - - [02/Dec/2026:10:22:30 +0530] "POST /api/enroll HTTP/1.1" 201 230 "-" "Mozilla/5.0"
203.0.113.99 - - [02/Dec/2026:10:58:02 +0530] "GET /courses/bash HTTP/1.1" 304 0 "-" "Mozilla/5.0"
203.0.113.99 - - [02/Dec/2026:11:05:17 +0530] "GET /images/logo.png HTTP/1.1" 200 22400 "-" "Mozilla/5.0"
192.0.2.44 - - [02/Dec/2026:11:30:00 +0530] "-" 400 0 "-" "-"
198.51.100.7 - - [02/Dec/2026:11:41:09 +0530] "GET /courses/bash HTTP/1.1" 200 8300 "-" "Mozilla/5.0"
198.51.100.7 - - [02/Dec/2026:11:41:30 +0530] "GET /api/progress HTTP/1.1" 502 166 "-" "Mozilla/5.0"
this line was written by a broken logger
203.0.113.10 - - [02/Dec/2026:11:59:59 +0530] "GET /logout HTTP/1.1" 302 - "-" "Mozilla/5.0"
The IP addresses come from the ranges reserved for documentation (RFC 5737), so they cannot belong to a real visitor.
Design Decisions
Why Not Loop Over the Lines in Bash?
A first attempt often looks like this: read each line, split it into an array, and count status codes in an associative array.
declare -A c
while IFS= read -r line; do
read -r -a f <<< "$line"
[[ ${f[8]:-} =~ ^[0-9]{3}$ ]] && c[${f[8]}]=$(( ${c[${f[8]}]:-0} + 1 ))
done < access.log
It works, but it is slow. On a test log of about 105,000 lines, this loop took 3.3 seconds; the equivalent awk '{c[$9]++} END {print c[200]}' took 0.02 seconds, more than a hundred times faster. Bash executes every line through its interpreter, and the here-string <<< creates a temporary file or pipe for every line. awk is a compiled program designed exactly for this kind of record processing. Lesson 191 discussed this rule in general: let Bash orchestrate and let specialized tools process bulk data.
One Pass, Many Statistics
The second temptation is to run a separate pipeline for each statistic: awk '{print $9}' | sort | uniq -c for status codes, another for paths, another for IPs. Each pipeline reads the entire log again, and with compressed logs each one decompresses it again.
The analyzer reads the log once. A single awk program updates several associative arrays per line, and at the end prints them as small tab-separated records:
TOTAL 19
CODE 200 9
CODE 404 2
PATH /courses/bash 4
IP 203.0.113.10 5
HOUR 09 7
...
These records are tiny compared with the log: one line per distinct status code, path, IP and hour. Bash then sorts and formats them with ordinary tools. This splits the work cleanly: awk does the heavy counting, and Bash and sort do the presentation, where their convenience matters more than speed.
Parsing Lines Robustly
Splitting the line on spaces, so that $9 is the status, works for well-formed lines but breaks when a request line contains unusual content. For example, "-" (no request) has one word instead of three, which shifts every following field. The analyzer instead splits the line on double quotes:
if (split($0, q, "\"") < 3 || $4 !~ /^\[/) { bad++; next }
split(q[3], sb, " ")
status = sb[1]; bytes = sb[2]
For a combined log line, q[1] is the part before the first quote (IP, identity, user, time), q[2] is the request line, and q[3] is the text between the request and the referer: 200 1840. Splitting q[3] on spaces gives the status and the size regardless of how many words the request contained.
Every line is validated before it is counted. A line with fewer than two quotes, a fourth field that does not start with [, or a status that is not a three-digit code from 100 to 599 increases the bad counter and is skipped with next. The report mentions how many lines were skipped, so problems in the log are visible without making the whole analysis fail.
Other details of the awk program:
substr($4, 14, 2)extracts the hour.$4is[02/Dec/2026:09:12:01, and the hour starts at character 14.sub(/\?.*/, "", path)removes the query string, so/courses/bash?page=2is counted as/courses/bash.if (bytes ~ /^[0-9]+$/) sent += bytesignores the-that servers log when no body was sent.status + 0 >= 400forces a numeric comparison. Errors are counted by the combination of status and path, because "500 on/api/enroll" is far more useful than "500" alone.LC_ALL=Crunsawkin the C locale, which avoids slow multibyte character handling and makes regular expression ranges behave the same everywhere.
The program uses only POSIX awk features, so it runs with mawk (the default on Debian and Ubuntu), GNU awk and BSD awk.
Embedding the awk Program
A long awk program inside single quotes on the command line is hard to read and cannot contain single quotes. The script stores it in a variable with a quoted here-document:
read -r -d '' AWK_PROGRAM <<'AWK' || true
BEGIN { OFS = "\t" }
...
AWK
The quotes around 'AWK' stop Bash from expanding $0, $4 and the other awk field references inside the program (lesson 63). read -d '' reads until a NUL byte; since the here-document contains none, read reaches the end of input and returns status 1, which || true absorbs under set -e. The variable now holds the whole program, and awk "$AWK_PROGRAM" runs it.
Reading Compressed and Plain Logs Alike
Log rotation (lesson 165) usually compresses older logs: access.log, access.log.1, access.log.2.gz, access.log.3.gz. The analyzer reads them all through one command:
gzip -cdf -- "$@"
-ddecompresses.-cwrites to standard output instead of replacing the file.-f("force") makesgzip -dcopy input that is not compressed to the output unchanged. This one option lets the same command handle.gzfiles and plain text.- With no file arguments,
gzipreads standard input, socat access.log | logstat.shandssh server cat /var/log/nginx/access.log | logstat.shwork too.
The whole pipeline runs under set -o pipefail. If gzip hits a truncated archive, the pipeline fails, and the script reports the problem instead of printing statistics for part of the data.
Querying the Records
Two small helpers extract records from the collected data. Both use awk with a tab as the field separator and a here-string as input:
value() { awk -F '\t' -v tag="$1" '$1 == tag { print $2; exit }' <<< "$data"; }
records() { awk -F '\t' -v tag="$1" 'BEGIN { OFS = "\t" } $1 == tag { print $2, $3 }' <<< "$data"; }
-v tag="$1" passes the tag into awk as a variable. This is safer than building the program text from the argument ("\$1 == \"$1\""), which would break, or worse, if the argument contained quotes (lesson 155). Comparing the whole first field with == is also more precise than grep "^CODE", which would match any tag starting with CODE.
Percentages Without Floating Point
Bash arithmetic only handles integers, yet the report shows percentages with one decimal place. The trick is to compute tenths of a percent and insert the decimal point while printing:
percent() {
local tenths=$(( ($1 * 1000 + total / 2) / total )) # rounded
printf '%d.%d%%' $(( tenths / 10 )) $(( tenths % 10 ))
}
For 9 out of 19 requests, 9 * 1000 / 19 is 473.68. Adding half the divisor before dividing (+ total / 2) rounds to the nearest integer instead of truncating, giving 474, which prints as 47.4%. %% in the printf format prints a literal percent sign.
Sorting the Top Lists
records "$2" | LC_ALL=C sort -t $'\t' -k2,2nr -k1,1 | head -n "$top"
-t $'\t'sets the field separator to a tab. Paths may contain spaces, so splitting on whitespace would be wrong.-k2,2nrsorts by the count, numerically and in reverse, so the most frequent entries come first.-k1,1is a tie-breaker: entries with equal counts are ordered by name. Without it, their order would depend on the order ofawk's arrays, which is unspecified and differs betweenawkimplementations. The tie-breaker makes the report identical on every system.
A Text Bar Chart
Each hour gets a bar of # characters scaled so that the busiest hour is 40 characters wide:
width=$(( count * 40 / max ))
(( width == 0 )) && width=1
printf -v bar '%*s' "$width" ''
printf ' %s:00 %-40s %d\n' "$hour" "${bar// /#}" "$count"
printf -v bar '%*s' "$width" '' stores a string of width spaces in bar: the * takes the field width from the next argument. ${bar// /#} then replaces every space with #. A minimum width of 1 keeps quiet hours visible. %-40s pads each bar to 40 characters so the counts line up in a column.
The Complete Script
#!/usr/bin/env bash
#
# logstat.sh - summarize web server access logs (Apache/Nginx combined format)
#
# Usage: logstat.sh [-n TOP] [FILE...]
#
# Options:
# -n TOP number of rows in each "top" list (default: 5)
# -h show this help
#
# FILEs may be plain text or gzip-compressed (access.log.2.gz). Without FILEs,
# the log is read from standard input.
#
# Exit status: 0 success, 1 no valid log lines or unreadable input, 2 usage error.
set -euo pipefail
readonly PROG=${0##*/}
usage() { sed -n '3,15s/^# \{0,1\}//p' "$0"; }
die() {
printf '%s: %s\n' "$PROG" "$1" >&2
exit "${2:-1}"
}
# One pass over the log. Instead of a report, awk prints small tab-separated
# records ("TAG<TAB>key<TAB>count"); Bash sorts and formats them afterwards.
read -r -d '' AWK_PROGRAM <<'AWK' || true
BEGIN { OFS = "\t" }
{
# split on double quotes: q[2] is the request, q[3] holds " status bytes "
if (split($0, q, "\"") < 3 || $4 !~ /^\[/) { bad++; next }
split(q[3], sb, " ")
status = sb[1]; bytes = sb[2]
if (status !~ /^[1-5][0-9][0-9]$/) { bad++; next }
total++
ips[$1]++
codes[status]++
classes[substr(status, 1, 1) "xx"]++
if (bytes ~ /^[0-9]+$/) sent += bytes
hours[substr($4, 14, 2)]++ # [02/Dec/2026:09:12:01 -> 09
if (total == 1) first = substr($4, 2)
last = substr($4, 2)
if (split(q[2], r, " ") >= 2) {
path = r[2]
sub(/\?.*/, "", path) # /a?page=2 counts as /a
} else {
path = "(no request line)"
}
paths[path]++
if (status + 0 >= 400) errors[status " " path]++
}
END {
print "TOTAL", total + 0
print "BAD", bad + 0
print "BYTES", sent + 0
print "FIRST", first
print "LAST", last
for (k in ips) { print "IP", k, ips[k]; unique++ }
print "UNIQUE", unique + 0
for (k in codes) print "CODE", k, codes[k]
for (k in classes) print "CLASS", k, classes[k]
for (k in hours) print "HOUR", k, hours[k]
for (k in paths) print "PATH", k, paths[k]
for (k in errors) print "ERROR", k, errors[k]
}
AWK
top=5
while getopts ':n:h' opt; do
case $opt in
n) top=$OPTARG ;;
h) usage; exit 0 ;;
:) die "option -$OPTARG needs a value" 2 ;;
*) die "unknown option -$OPTARG (try -h)" 2 ;;
esac
done
shift $((OPTIND - 1))
[[ $top =~ ^[1-9][0-9]*$ ]] || die "TOP must be a positive whole number" 2
for file in "$@"; do
[[ -f $file && -r $file ]] || die "cannot read $file"
done
# gzip -c -d -f decompresses .gz files and passes plain text through unchanged
data=$(gzip -cdf -- "$@" | LC_ALL=C awk "$AWK_PROGRAM") || die "could not read the log input"
# value TAG - print the value of a single-value record
value() {
awk -F '\t' -v tag="$1" '$1 == tag { print $2; exit }' <<< "$data"
}
# records TAG - print "key<TAB>count" for every record with TAG
records() {
awk -F '\t' -v tag="$1" 'BEGIN { OFS = "\t" } $1 == tag { print $2, $3 }' <<< "$data"
}
total=$(value TOTAL)
(( total > 0 )) || die "no valid log lines found"
# percent COUNT - print COUNT as a percentage of all requests, one decimal place
percent() {
local tenths=$(( ($1 * 1000 + total / 2) / total )) # rounded
printf '%d.%d%%' $(( tenths / 10 )) $(( tenths % 10 ))
}
# table TITLE TAG - print the TOP biggest records of TAG with counts and percentages
table() {
local key count
printf '\n%s\n' "$1"
while IFS=$'\t' read -r key count; do
printf ' %6d %6s %s\n' "$count" "$(percent "$count")" "$key"
done < <(records "$2" | LC_ALL=C sort -t $'\t' -k2,2nr -k1,1 | head -n "$top")
}
# --- report --------------------------------------------------------------------
bad=$(value BAD)
printf 'Requests: %d' "$total"
(( bad > 0 )) && printf ' (%d malformed line(s) skipped)' "$bad"
printf '\n'
printf 'Unique IPs: %d\n' "$(value UNIQUE)"
printf 'Data sent: %s\n' "$(numfmt --to=iec-i --suffix=B "$(value BYTES)")"
printf 'First entry: %s\n' "$(value FIRST)"
printf 'Last entry: %s\n' "$(value LAST)"
printf '\nStatus classes\n'
while IFS=$'\t' read -r class count; do
printf ' %s %6d %6s\n' "$class" "$count" "$(percent "$count")"
done < <(records CLASS | LC_ALL=C sort)
table "Status codes" CODE
table "Top paths" PATH
table "Top client IPs" IP
table "Top errors (status path)" ERROR
printf '\nRequests per hour\n'
max=$(records HOUR | cut -f2 | sort -n | tail -n 1)
while IFS=$'\t' read -r hour count; do
width=$(( count * 40 / max ))
(( width == 0 )) && width=1
printf -v bar '%*s' "$width" ''
printf ' %s:00 %-40s %d\n' "$hour" "${bar// /#}" "$count"
done < <(records HOUR | LC_ALL=C sort)
Running the Analyzer
A Full Report
$ ./logstat.sh access.log
Requests: 19 (1 malformed line(s) skipped)
Unique IPs: 5
Data sent: 79KiB
First entry: 02/Dec/2026:09:12:01
Last entry: 02/Dec/2026:11:59:59
Status classes
2xx 10 52.6%
3xx 2 10.5%
4xx 4 21.1%
5xx 3 15.8%
Status codes
9 47.4% 200
2 10.5% 404
2 10.5% 500
1 5.3% 201
1 5.3% 302
Top paths
4 21.1% /courses/bash
3 15.8% /api/enroll
1 5.3% (no request line)
1 5.3% /
1 5.3% /.env
Top client IPs
5 26.3% 203.0.113.10
4 21.1% 192.0.2.44
4 21.1% 198.51.100.23
4 21.1% 198.51.100.7
2 10.5% 203.0.113.99
Top errors (status path)
2 10.5% 500 /api/enroll
1 5.3% 400 (no request line)
1 5.3% 403 /admin
1 5.3% 404 /.env
1 5.3% 404 /wp-login.php
Requests per hour
09:00 ######################################## 7
10:00 ######################################## 7
11:00 ############################ 5
Reading the report:
- 19 requests, 1 malformed line skipped. The line from the broken logger was rejected; the request with
"-"as its request line was accepted, because its time and status are valid. It is listed as(no request line). - 79KiB of data.
numfmt --to=iec-iconverts the byte total (79,948) into binary units: 1 KiB is 1,024 bytes.numfmtrounds up by default, so 78.07 KiB is shown as 79KiB. - The status classes summarize health at a glance: about 16% server errors (5xx) is a clear sign of trouble in this sample.
- Top errors pinpoints the cause: two
500responses from/api/enroll. The404and403responses come from192.0.2.44probing for WordPress and environment files, typical scanner traffic. /courses/bashis the most requested path, counting the request with?page=2.
Shorter Lists
-n controls the length of each top list:
$ ./logstat.sh -n 3 access.log | sed -n '/Top paths/,/^$/p'
Top paths
4 21.1% /courses/bash
3 15.8% /api/enroll
1 5.3% (no request line)
(no request line) comes before / here because of the tie-breaker: all remaining paths have a count of 1, and in the C locale ( sorts before /.
Several Files, Compressed or Not
Rotated logs can be analyzed together. Here the sample is split into a compressed older part and a plain newer part, and the totals are the same as for the original file:
$ head -8 access.log > old.log && gzip old.log
$ tail -12 access.log > new.log
$ ./logstat.sh old.log.gz new.log | head -3
Requests: 19 (1 malformed line(s) skipped)
Unique IPs: 5
Data sent: 79KiB
On a real server, all the rotated logs of a site can be passed in one go: ./logstat.sh /var/log/nginx/access.log*.
Reading from Standard Input
$ cat access.log | ./logstat.sh | head -1
Requests: 19 (1 malformed line(s) skipped)
Errors
$ ./logstat.sh nope.log; echo "status $?"
logstat.sh: cannot read nope.log
status 1
$ ./logstat.sh -n 0 access.log; echo "status $?"
logstat.sh: TOP must be a positive whole number
status 2
$ printf 'garbage\n' > g.log; ./logstat.sh g.log; echo "status $?"
logstat.sh: no valid log lines found
status 1
$ head -c 100 old.log.gz > broken.log.gz; ./logstat.sh broken.log.gz; echo "status $?"
gzip: broken.log.gz: unexpected end of file
logstat.sh: could not read the log input
status 1
The last case shows pipefail at work: gzip failed in the middle of the pipeline, and the script refused to print statistics based on incomplete data.
Performance on a Large Log
To measure throughput, the sample was repeated until the file had about a million lines (98 MB):
$ wc -l big.log
1052640 big.log
$ time ./logstat.sh big.log > /dev/null
real 0m1.042s
user 0m0.943s
sys 0m0.104s
The same log compressed with gzip took 1.16 seconds; decompression runs in parallel with awk in the pipeline. Your timings will depend on the machine, but the shape of the result holds: the cost is one pass of awk over the data, and everything after that is negligible because it works on the small summary.
Using the Analyzer on a Server
A few practical patterns:
# today's report for an Nginx site, mailed to the administrator by cron
./logstat.sh /var/log/nginx/access.log | mail -s "Traffic report $(hostname)" admin@example.com
# analyze only the requests of one hour, filtering before the analyzer
grep '02/Dec/2026:10:' /var/log/nginx/access.log | ./logstat.sh
# analyze a remote server's logs without copying them first
ssh web1 'cat /var/log/nginx/access.log*' | ./logstat.sh
Because filtering is left to grep and other tools, the analyzer itself stays simple, and any filter can be combined with it. That is the Unix approach of small tools connected by pipes (lesson 61).
Reading /var/log/nginx usually requires membership in the adm group or sudo. Running the analyzer itself as root is not necessary; sudo cat /var/log/nginx/access.log | ./logstat.sh gives root access only to cat (lesson 159).
Ideas for Extending the Project
- Time-range options. Add
--fromand--tooptions and compare the time field insideawk. Converting02/Dec/2026:10:00:00into a sortable form (20261202100000) by mapping month names to numbers in aBEGINblock allows simple string comparison. - Response times. Many Nginx configurations add
$request_timeat the end of each line. With that field, the analyzer could report the slowest paths and percentiles. - Machine-readable output. A
-joption could print the records as JSON lines for other tools, or as CSV for a spreadsheet. - Bot detection. Count the user agents (
q[6]) and flag IPs that receive many 404 responses in a short time, a common sign of scanning. - Alerting. Combine the analyzer with lesson 173: if the 5xx share is above a threshold, send a notification. The report already computes the number; only the comparison and the message are missing.