Usage statistics from nginx access logs, as a reusable Python module:
- fast regex parser for the
combinedformat and its virtual-host variant ($remote_addr $host $remote_user [...]), plain or gzipped files - classification of requests (API, page, asset, scanner) and clients (bots and monitors, browsers, scripts, service-specific clients by User-Agent)
- sessions (30 min inactivity per IP + User-Agent), capped request counts
- IP enrichment without slow whois queries: ASN, AS name and country from the offline iptoasn.com table, concurrent reverse DNS with a persistent cache (~2 min for 20k IPs), optional legacy whois cache; classification of academic (universities, research institutes, hospitals, research and education networks) and cloud/hosting networks, and identification of academic institutions
- summary of a time window and annualization of per-day rates
The summaries contain no IP addresses. Raw logs and the reverse DNS cache are personal data (GDPR): keep them out of version control.
pip install git+https://github.com/saezlab/nginx_stats
from nginx_stats import Classifier, IpInfo, summarize, annualize
clf = Classifier(
api_segments = {'interactions', 'annotations'},
clients = [('python-client', r'^mypkg-user'), ('r-client', r'^R \(')],
)
summary, institutions = summarize(
'logs/2025-10', '2025-10-05', '2025-11-02', clf, IpInfo(),
hosts = {'example.org'}, pattern = 'example.org.access.log*',
)
print(annualize({'2025': summary}))Command line:
nginx-stats update-asn
nginx-stats summarize logs/2025-10 --from 2025-10-05 --to 2025-11-02 \
--host example.org --api-segment interactions \
--client 'python-client=^mypkg-user' --out summary.json
The cache directory (ASN table, reverse DNS cache) is $NGINX_STATS_CACHE,
or ~/.cache/nginx_stats.
- If nginx writes the same requests into two logs (e.g. an access log and a
cache log), read only one, with
pattern. Version 0.1 of this repo (stats.py) read both and counted every request twice. - Use full days in the window; trim partially covered first/last days.
- A uniform
daily_caplimits the weight of runaway monitoring loops or CI jobs in request counts; sessions are robust to them by construction.
Tests: uv run pytest.