Bash script: a quick daily report from the Nginx access log (requests, errors, traffic, top clients)

Before installing a log analyser, try twenty lines of awk. This prints the numbers I usually want from an access log: how many requests, which status codes, how much was sent, who asked the most and what failed.

It expects the default “combined” log format.

#!/usr/bin/env bash
# nginx_report.sh - summary of an Nginx access log in combined format
# usage: ./nginx_report.sh [logfile] [top N]
set -u

LOG="${1:-/var/log/nginx/access.log}"
TOP="${2:-10}"

[ -r "$LOG" ] || { echo "cannot read $LOG" >&2; exit 2; }

total=$(wc -l < "$LOG")
echo "Log file : $LOG"
echo "Requests : $total"
[ "$total" -eq 0 ] && exit 0

awk '$10 ~ /^[0-9]+$/ { b += $10 } END { printf "Sent     : %.1f MB\n", b / 1048576 }' "$LOG"

echo
echo "Status codes"
awk '$9 ~ /^[0-9][0-9][0-9]$/ { s[$9]++ }
     END { for (k in s) printf "  %s  %d\n", k, s[k] }' "$LOG" | sort -k2 -nr

awk -v t="$total" '$9 ~ /^5/ { e++ } END { printf "  5xx share: %.2f%%\n", (e / t) * 100 }' "$LOG"

echo
echo "Top $TOP clients by requests (requests, MB, address)"
awk '{ c[$1]++; if ($10 ~ /^[0-9]+$/) b[$1] += $10 }
     END { for (k in c) printf "  %8d %10.1f  %s\n", c[k], b[k] / 1048576, k }' "$LOG" \
  | sort -k1 -nr | head -n "$TOP"

echo
echo "Top $TOP paths"
awk '{ p = $7; sub(/\?.*/, "", p); n[p]++ }
     END { for (k in n) printf "  %8d  %s\n", n[k], k }' "$LOG" | sort -k1 -nr | head -n "$TOP"

echo
echo "Top $TOP paths answered with 5xx"
awk '$9 ~ /^5/ { p = $7; sub(/\?.*/, "", p); n[p]++ }
     END { for (k in n) printf "  %8d  %s\n", n[k], k }' "$LOG" | sort -k1 -nr | head -n "$TOP"

Using it

./nginx_report.sh
./nginx_report.sh /var/log/nginx/access.log.1 20
zcat /var/log/nginx/access.log.2.gz > /tmp/a.log && ./nginx_report.sh /tmp/a.log

Yesterday’s numbers every morning:

5 7 * * * /opt/scripts/nginx_report.sh /var/log/nginx/access.log.1 > /var/log/nginx_report.txt

Pipe it into the Discord or Telegram scripts from this section if you want it in a channel.

Reading the output

5xx share is the number to watch. Under 1 percent is normal noise. If it jumps, the last block shows which addresses are failing.

Top clients catches scrapers and broken players. One address with a hundred times more requests than the next is either a monitor of yours or someone to rate limit.

Paths have the query string cut off, so the same file requested with different tokens is counted as one.

If your log format is different

The script reads field 1 as the client, 7 as the path, 9 as the status and 10 as the bytes sent. If you changed log_format, adjust those numbers. Behind a proxy, field 1 is the proxy unless you configured the real address, and then the client list is useless until you do.

It reads the file six times, which is fine up to a few gigabytes. Past that, a single awk pass or a real analyser such as GoAccess is the better tool.