A fast, streaming nginx log analyzer script gives you immediate visibility into 5xx upstream failures, brute-force endpoint scanners, and sudden bandwidth spikes without deploying a heavy Elasticsearch or Loki cluster. When a reverse proxy serves thousands of requests per minute, grepping through /var/log/nginx/access.log and rotated .gz archives by hand wastes critical minutes during an outage. Worse, standard uptime pings only tell you whether the homepage returned HTTP 200—they miss targeted 404 vulnerability scans, bots hammering /wp-login.php or /api/auth, and intermittent 502 Bad Gateway bursts hitting real users. Built for Linux and macOS hosts running Python 3.10+, the script below streams plain and gzipped Nginx combined logs line-by-line in constant memory, flags high-volume client IPs, 404/5xx bursts, and suspicious URI probes, supports --dry-run and --json output, and dispatches concise Slack or Discord webhook summaries.
Key Takeaways & Script Specs
- Runtime & Dependencies: Python 3.10+ (uses standard library
re,gzip,ipaddress,collections) plus optionalrequestsfor webhook alerts. - Supported Log Formats: Standard Nginx
combinedformat (plain.logand rotated.gzfiles) with optional time-window filtering. - Memory Footprint: Streaming line-by-line parser uses O(unique IPs) memory even on multi-gigabyte access logs.
- Safety Controls: Read-only file inspection, private/loopback IP allowlisting, configurable thresholds,
--dry-runmode, and non-zero exit codes on threshold breaches.
Table of Contents
Why Raw Grep and Awk Fall Short on Modern Nginx Logs
Every engineer reaches for awk '{print $1}' access.log | sort | uniq -c during an incident, and for a quick five-second check on a small file, that pipeline works fine. Once your access logs grow past a few hundred megabytes or span rotated access.log.1 and access.log.2.gz archives, ad-hoc shell pipes hit three immediate walls. First, sort buffers lines in memory and temporary disk space, slowing down busy nodes right when CPU and I/O are already saturated. Second, raw IP counts cannot distinguish a legitimate CDN health checker from a scanner throwing 400 requests per minute at /.env, /xmlrpc.php, or /admin. Third, shell one-liners rarely normalize time windows, status-code ratios, or allowlisted internal subnet CIDRs.
According to the official Nginx ngx_http_log_module documentation, Nginx writes access logs in the predefined combined format by default unless overridden: $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent". By compiling a single strict regular expression against that exact schema and streaming each file lazily, Python parses hundreds of thousands of lines per second while maintaining per-IP error counters, URI probe tallies, and 5xx rate metrics in one pass.
Architecture and Streaming Analysis Pipeline
Instead of loading entire log files into memory or shelling out to zcat, our analyzer opens plain and .gz files transparently through a unified generator. Each matching log line flows through four deterministic stages before any summary or alert is emitted:
+-------------------------------------------------------------------+
| 1. Stream Log Lines (plain .log + rotated .gz via gzip.open) |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| 2. Parse Combined Format & Filter Time Window (--minutes N) |
| - Extract IP, timestamp, method, path, status, bytes, UA |
| - Skip allowlisted CIDRs (127.0.0.0/8, 10.0.0.0/8, etc.) |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| 3. Aggregate Metrics & Detect Anomalies |
| - High-rate IPs (>= --ip-threshold requests) |
| - High 404/403 scanner bursts & suspicious probe paths |
| - Global 5xx percentage (>= --max-5xx-pct) |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| 4. Emit Terminal Report or --json + Webhook (unless --dry-run) |
+-------------------------------------------------------------------+
Notice how this fits cleanly alongside other lightweight single-host monitors. If you already run a Docker health check script to restart wedged application containers and an SSL certificate expiry monitor script to guard your TLS edge, adding an Nginx log analyzer completes the edge-to-app observability loop without adding a single background database.
Comparing Nginx Log Analysis Options in 2027
Choosing the right log analysis tool depends on your fleet size, RAM budget, and whether you need real-time alerting or historical dashboards.
| Tool / Approach | RAM Overhead | Reads Rotated .gz | Automated Webhook Alerts | Setup Complexity |
|---|---|---|---|---|
Ad-hoc grep / awk | Medium–High (sort) | Requires zcat | Manual wrapper | Low (interactive only) |
| GoAccess Terminal UI | Low | Yes (via pipe) | None (reporting UI) | Low |
| ELK / Grafana Loki Stack | High (2–8+ GB RAM) | Yes (via Promtail/Agent) | Full alerting rules | High (multi-container) |
| Python Streaming Analyzer | Very Low (< 30 MB) | Yes (native gzip) | Native Slack/Discord | Low (single script) |
For single VPS nodes, staging environments, and lean production clusters, a Python streaming script keeps RAM usage under 30 MB while still delivering structured JSON reports and actionable Slack or Discord alerts. For interactive terminal exploration during live incidents, you can pair it with free developer CLI tools like goaccess or lnav.
Prerequisites and Virtual Environment Setup
Create an isolated directory and Python virtual environment so your automation dependencies remain separate from OS packages. The core parser uses only the Python standard library; installing requests is only needed for webhook notifications.
sudo mkdir -p /opt/nginx-log-analyzer
sudo chown "$USER":"$USER" /opt/nginx-log-analyzer
cd /opt/nginx-log-analyzer
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install "requests>=2.32.0,<3.0.0"
Make sure the user running the script has read access to /var/log/nginx/ (typically by adding the service user to the adm group on Debian/Ubuntu with sudo usermod -aG adm "$USER") so it never needs root privileges.
Complete Production Python Nginx Log Analyzer Script
Save the script below as /opt/nginx-log-analyzer/nginx_log_analyzer.py. It uses Python’s argparse CLI module to support multiple log paths (including globbed .gz files), sliding lookback windows in minutes, CIDR allowlisting, scanner-path signature matching, --dry-run webhook testing, and structured JSON output.
#!/usr/bin/env python3
"""
Production Nginx Access Log Analyzer & Anomaly Reporter (2027)
Streams plain and .gz Nginx combined logs, detects IP bursts, 404/5xx spikes,
and suspicious scanner probes, and dispatches optional Slack/Discord alerts.
"""
import argparse
import gzip
import ipaddress
import json
import logging
import os
import re
import sys
from collections import Counter, defaultdict
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Tuple
try:
import requests
except ImportError:
requests = None
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
stream=sys.stderr,
)
logger = logging.getLogger("nginx_log_analyzer")
Matches standard Nginx 'combined' log format
LOG_PATTERN = re.compile(
r'^(?P<ip>\S+)\s+\S+\s+\S+\s+'
r'[(?P<time>[^]]+)]\s+'
r'"(?P<method>[A-Z]+)\s+(?P<path>\S+)(?:\s+HTTP/[^"]+)?"\s+'
r'(?P<status>\d{3})\s+(?P<bytes>\d+|-)\s+'
r'"[^"]"\s+"(?P<ua>[^"])"'
)
SUSPICIOUS_PATHS = (
"/.env",
"/.git",
"/wp-login.php",
"/xmlrpc.php",
"/phpmyadmin",
"/actuator",
"../",
"union+select",
"union%20select",
)
def iter_log_lines(paths: List[Path]) -> Iterable[str]:
"""Yield lines from plain text and .gz compressed Nginx log files."""
for path in paths:
if not path.is_file():
logger.warning("Skipping missing file: %s", path)
continue
opener = gzip.open if path.suffix == ".gz" else open
try:
with opener(path, "rt", encoding="utf-8", errors="replace") as handle:
for line in handle:
yield line
except OSError as exc:
logger.error("Failed reading %s: %s", path, exc)
def parse_nginx_time(raw_ts: str) -> Optional[datetime]:
"""Parse Nginx $time_local (e.g. 29/Nov/2026:02:15:01 +0530) into UTC."""
try:
dt = datetime.strptime(raw_ts, "%d/%b/%Y:%H:%M:%S %z")
return dt.astimezone(timezone.utc)
except ValueError:
return None
def is_allowlisted(ip_str: str, networks: List[ipaddress._BaseNetwork]) -> bool:
"""Return True if the IP belongs to any configured allowlist CIDR."""
try:
addr = ipaddress.ip_address(ip_str)
except ValueError:
return False
return any(addr in net for net in networks)
def analyze_logs(
paths: List[Path],
minutes: Optional[int],
allowlist_cidrs: List[str],
ip_threshold: int,
err404_threshold: int,
max_5xx_pct: float,
) -> dict:
"""Stream logs and compute traffic, error, and anomaly summaries."""
networks = [ipaddress.ip_network(cidr, strict=False) for cidr in allowlist_cidrs]
cutoff = (
datetime.now(timezone.utc) - timedelta(minutes=minutes)
if minutes and minutes > 0
else None
)
total_requests = 0
unparsed_lines = 0
total_bytes = 0
status_buckets: Counter = Counter()
ip_counts: Counter = Counter()
ip_404_counts: Counter = Counter()
ip_probe_hits: Dict[str, Counter] = defaultdict(Counter)
top_5xx_paths: Counter = Counter()
for line in iter_log_lines(paths):
match = LOG_PATTERN.match(line)
if not match:
unparsed_lines += 1
continue
if cutoff is not None:
dt = parse_nginx_time(match.group("time"))
if dt is None or dt < cutoff:
continue
ip = match.group("ip")
if is_allowlisted(ip, networks):
continue
path = match.group("path")
status = int(match.group("status"))
bytes_raw = match.group("bytes")
resp_bytes = int(bytes_raw) if bytes_raw.isdigit() else 0
total_requests += 1
total_bytes += resp_bytes
status_buckets[f"{status // 100}xx"] += 1
ip_counts[ip] += 1
if status in (403, 404):
ip_404_counts[ip] += 1
if status >= 500:
top_5xx_paths[f"{status} {path.split('?', 1)[0]}"] += 1
lower_path = path.lower()
for sig in SUSPICIOUS_PATHS:
if sig in lower_path:
ip_probe_hits[ip][sig] += 1
break
count_5xx = status_buckets.get("5xx", 0)
pct_5xx = round((count_5xx / total_requests * 100.0), 2) if total_requests else 0.0
flagged_ips = []
for ip, count in ip_counts.most_common():
err404 = ip_404_counts.get(ip, 0)
probes = sum(ip_probe_hits[ip].values())
reasons = []
if count >= ip_threshold:
reasons.append(f"high_rate({count})")
if err404 >= err404_threshold:
reasons.append(f"403_404_burst({err404})")
if probes > 0:
reasons.append(f"scanner_probes({probes})")
if reasons:
flagged_ips.append(
{
"ip": ip,
"requests": count,
"errors_403_404": err404,
"probe_hits": probes,
"reasons": reasons,
}
)
anomalies_detected = bool(flagged_ips) or (pct_5xx >= max_5xx_pct and count_5xx > 0)
return {
"window_minutes": minutes or "all",
"total_requests": total_requests,
"total_megabytes": round(total_bytes / (1024 * 1024), 2),
"unparsed_lines": unparsed_lines,
"status_breakdown": dict(status_buckets),
"rate_5xx_pct": pct_5xx,
"top_5xx_endpoints": top_5xx_paths.most_common(5),
"flagged_ips": flagged_ips[:15],
"anomalies_detected": anomalies_detected,
}
def send_webhook(webhook_url: str, summary: dict, dry_run: bool) -> None:
"""Send anomaly alert summary to Slack or Discord."""
if not summary["anomalies_detected"]:
return
lines = [
f"*[Nginx Log Anomaly Alert]* Window: {summary['window_minutes']}m | "
f"Requests: {summary['total_requests']} | 5xx Rate: {summary['rate_5xx_pct']}%"
]
for item in summary["flagged_ips"][:5]:
lines.append(
f"- `{item['ip']}` | req={item['requests']} | {', '.join(item['reasons'])}"
)
for endpoint, hits in summary["top_5xx_endpoints"][:3]:
lines.append(f"- 5xx `{endpoint}` ({hits} hits)")
message = "\n".join(lines)
if dry_run:
logger.info("[DRY-RUN] Would send webhook alert:\n%s", message)
return
if requests is None:
logger.error("Install 'requests' to enable webhook alerts: pip install requests")
return
payload = {"text": message, "content": message}
try:
resp = requests.post(webhook_url, json=payload, timeout=5)
resp.raise_for_status()
logger.info("Sent Nginx anomaly alert to webhook.")
except requests.RequestException as exc:
logger.error("Webhook delivery failed: %s", exc)
def print_report(summary: dict) -> None:
"""Print a clean terminal summary table."""
print(
f"Window: {summary['window_minutes']}m | Requests: {summary['total_requests']} | "
f"Traffic: {summary['total_megabytes']} MB | 5xx: {summary['rate_5xx_pct']}%"
)
print(f"Status Breakdown: {summary['status_breakdown']}")
if summary["top_5xx_endpoints"]:
print("\nTop 5xx Endpoints:")
for ep, cnt in summary["top_5xx_endpoints"]:
print(f" {cnt:>6} {ep}")
if summary["flagged_ips"]:
print("\nFlagged Client IPs:")
print(f" {'IP ADDRESS':<20} {'REQS':<8} {'403/404':<9} {'PROBES':<8} {'REASONS'}")
for row in summary["flagged_ips"]:
print(
f" {row['ip']:<20} {row['requests']:<8} {row['errors_403_404']:<9} "
f"{row['probe_hits']:<8} {', '.join(row['reasons'])}"
)
else:
print("\nNo IP anomalies detected.")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Analyze Nginx access logs for IP anomalies, scanners, and 5xx spikes."
)
parser.add_argument(
"logs",
nargs="+",
help="Path(s) to Nginx access.log or rotated .gz files",
)
parser.add_argument(
"--minutes",
type=int,
default=60,
help="Analyze only entries from the last N minutes (0 = all lines, default: 60)",
)
parser.add_argument(
"--allowlist",
nargs="*",
default=["127.0.0.0/8", "::1/128"],
help="CIDR ranges to ignore (default: localhost)",
)
parser.add_argument(
"--ip-threshold",
type=int,
default=500,
help="Flag IPs exceeding N requests in window (default: 500)",
)
parser.add_argument(
"--err404-threshold",
type=int,
default=40,
help="Flag IPs exceeding N 403/404 responses in window (default: 40)",
)
parser.add_argument(
"--max-5xx-pct",
type=float,
default=2.0,
help="Trigger alert if 5xx error percentage reaches this threshold (default: 2.0)",
)
parser.add_argument("--json", action="store_true", help="Emit JSON summary")
parser.add_argument(
"--dry-run",
action="store_true",
help="Print summary and log webhook payload without sending HTTP requests",
)
return parser.parse_args()
def main() -> int:
args = parse_args()
paths = [Path(p) for p in args.logs]
summary = analyze_logs(
paths=paths,
minutes=args.minutes,
allowlist_cidrs=args.allowlist,
ip_threshold=args.ip_threshold,
err404_threshold=args.err404_threshold,
max_5xx_pct=args.max_5xx_pct,
)
if args.json:
print(json.dumps(summary, indent=2))
else:
print_report(summary)
webhook_url = os.getenv("WEBHOOK_URL")
if webhook_url and summary["anomalies_detected"]:
send_webhook(webhook_url, summary, dry_run=args.dry_run)
return 1 if summary["anomalies_detected"] else 0
if name == "main":
sys.exit(main())
Test the analyzer safely with --dry-run against your live and rotated logs before wiring up alerts:
chmod +x /opt/nginx-log-analyzer/nginx_log_analyzer.py
/opt/nginx-log-analyzer/.venv/bin/python /opt/nginx-log-analyzer/nginx_log_analyzer.py \
/var/log/nginx/access.log /var/log/nginx/access.log.1 --minutes 60 --dry-run
Scheduling Automated Sweeps With Systemd Timers or Cron
Running the analyzer every 15 minutes via a systemd timer catches brute-force scans and upstream 502/504 waves before users flood your support channels. Store your WEBHOOK_URL in a 0600 environment file so secrets never appear in ps aux output, and archive historical JSON reports alongside your automated Linux server backups.
cat <<'EOF' > /opt/nginx-log-analyzer/.env
WEBHOOK_URL=https://hooks.slack.com/services/REPLACE/ME/NOW
EOF
chmod 600 /opt/nginx-log-analyzer/.env
# Or run every 15 minutes via cron (using --minutes 15 to match cadence):
# */15 * * * * . /opt/nginx-log-analyzer/.env && /opt/nginx-log-analyzer/.venv/bin/python /opt/nginx-log-analyzer/nginx_log_analyzer.py /var/log/nginx/access.log --minutes 15 >/dev/null 2>&1
Troubleshooting and Security Hardening
Keep these three production details in mind when rolling the script out behind proxies or custom Nginx configurations:
- Cloudflare or Load Balancer Real IPs: If Nginx sits behind Cloudflare or an AWS ALB without
ngx_http_realip_moduleconfigured,$remote_addrlogs the proxy IP rather than the client IP. Enableset_real_ip_fromandreal_ip_header CF-Connecting-IP(orX-Forwarded-For) innginx.confso anomaly counts reflect true client addresses. - Custom Log Formats: If you use a custom
log_format(such as adding$request_timeor JSON escaping), checkunparsed_linesin the script output and adjustLOG_PATTERNto match your extra fields. - Webhook Timeouts and Least Privilege: Run the script under a dedicated non-root user in the
admgroup, and always keeptimeout=5onrequests.post()so a transient Slack or Discord outage never stalls your monitoring timer.
Frequently Asked Questions
Can this Nginx log analyzer script read compressed .gz logrotate archives?
Yes. The script detects the .gz extension automatically and streams compressed archives using Python’s built-in gzip module without requiring zcat or temporary disk extraction.
How much memory does the script use on multi-gigabyte access logs?
Because iter_log_lines() yields one line at a time, memory usage depends only on the number of unique IP addresses seen inside your –minutes window, typically staying under 30 MB even on multi-gigabyte files.
How do I exclude internal health checkers or monitoring IPs?
Pass one or more CIDR blocks to –allowlist (for example, –allowlist 127.0.0.0/8 10.0.0.0/8 192.168.1.50/32). Matching IPs are skipped before any request or error counters are incremented.
Does the script automatically ban IPs in iptables or Fail2Ban?
No. By design, the script is strictly read-only and non-destructive—it detects anomalies, returns exit code 1, and sends webhook alerts. You can pipe its –json output into your own firewall or Cloudflare API workflow if desired.
What does –dry-run do when testing alerts?
Passing –dry-run runs the full log parsing and anomaly detection pipeline, prints the terminal or JSON report, and logs the exact Slack/Discord webhook payload to stderr without making any outbound HTTP requests.
Why did unparsed_lines show a non-zero count?
A non-zero unparsed_lines count means your Nginx server uses a custom log_format rather than the default combined format, or contains malformed/truncated lines. Update LOG_PATTERN to match your nginx.conf log_format directive.