The user wants a Python script to parse and analyze Apache log files. I need to think about what kind of analysis might be needed, like hits per IP or status codes. It seems important to offer a configurable script with command-line arguments using regex for log parsing. Features could include supporting common log formats, accepting file paths, and allowing options for metrics. I might define a regular expression to capture key log details while ensuring flexibility.Designing Log Analysis Script
I'm thinking about how to parse datetimes using datetime.strptime and designing various analysis features. I should consider total requests, unique IP addresses, top N IPs by hits, requests per status code, top requested paths, traffic over time, and bytes sent. However, I want to keep things straightforward.
The script will parse arguments like log file, optional flags for top N IPs, and maybe a timeframe, although that wasn’t requested. I’ll make sure to keep the explanation concise and focus on providing the code block with a brief description without adding generic phrases.Considering Log Formats
I think I should mention that logs can exist in different formats, but for this, I’ll default to the common or combined log format. I can start defining my imports, like Counter and defaultdict from collections. The regex pattern is key for parsing.
I’ll also need a way to parse the time, and even consider timezone offsets. For the command-line interface, I'll set up arguments for the log file, top IPs, top URLs, and requests per minute. The script will print total requests, unique IPs, top IPs, status code counts, and top URLs. I'll need to ensure it handles edge cases gracefully, processing lines one by one to accommodate larger files.Implementing Log Analysis Function
I’ll create the analyze_log function to handle the analysis of log files. I'll set up counters for IPs, URLs, and status codes, maintaining totals for requests and bytes. The function will iterate through the log lines, using the regex pattern to match each line and extract the data.
I need to keep track of per-minute requests, and when returning stats, I’ll show the top 10 busiest minutes for clarity. Also, I’ll ensure to import datetime correctly and include a shebang for running the script, providing a concise usage section at the end. Below is a self‑contained Python 3 script that parses Apache access logs (Common or Combined Log Format) and prints some useful statistics.
You can adjust or extend the analysis in the analyze_log() function.
python
Usage examples:
bash
# Basic summary with default top-10 lists
python apache_log_analyzer.py /var/log/apache2/access.log
# Show more detail
python apache_log_analyzer.py /var/log/apache2/access.log --top-ips 20 --top-urls 50
If you tell me your exact log format (or show a few sample lines), I can tailor the regex and analysis to match it precisely or add specific metrics you care about (e.g., per-virtual-host, per-user-agent, response time if logged, etc.).
#!/usr/bin/env python3
"""
apache_log_analyzer.py
Simple Apache log parser and analyzer for Common / Combined Log Format.
Usage:
python apache_log_analyzer.py /path/to/access.log
python apache_log_analyzer.py /path/to/access.log --top-ips 20 --top-urls 20
"""
import re
import sys
import argparse
from collections import Counter
from datetime import datetime
# Regex for Apache Common / Combined Log Format
# Example line (Combined):
# 127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326 \
# "http://www.example.com/start.html" "Mozilla/4.08 [en] (Win98; I ;Nav)"
LOG_PATTERN = re.compile(
r'(?P<ip>\S+)\s+' # IP address
r'(?P<ident>\S+)\s+' # RFC 1413 identity (usually '-')
r'(?P<userid>\S+)\s+' # userid (usually '-')
r'\[(?P<time>[^\]]+)\]\s+' # [day/month/year:hour:minute:second zone]
r'"(?P<request>[^"]*)"\s+' # "GET /path HTTP/1.1"
r'(?P<status>\d{3})\s+' # status code
r'(?P<size>\S+)' # size in bytes or '-'
r'(?:\s+"(?P<referrer>[^"]*)"\s+"(?P<agent>[^"]*)")?' # optional referrer and agent
)
TIME_FORMAT = "%d/%b/%Y:%H:%M:%S" # e.g. 10/Oct/2000:13:55:36
def parse_line(line):
"""Parse a single log line, return dict of fields or None on parse error."""
match = LOG_PATTERN.match(line)
if not match:
return None
data = match.groupdict()
# Parse timestamp: "10/Oct/2000:13:55:36 -0700"
raw_time = data["time"]
# Split off timezone if present
time_part = raw_time.split()[0]
try:
dt = datetime.strptime(time_part, TIME_FORMAT)
except ValueError:
dt = None
# Parse request: "GET /path?query HTTP/1.1"
req = data.get("request") or ""
method, path, protocol = None, None, None
parts = req.split()
if len(parts) == 3:
method, path, protocol = parts
elif len(parts) == 2:
method, path = parts
elif len(parts) == 1:
method = parts[0]
# Parse size
size_str = data.get("size", "-")
try:
size = int(size_str) if size_str != "-" else 0
except ValueError:
size = 0
return {
"ip": data.get("ip"),
"ident": data.get("ident"),
"userid": data.get("userid"),
"time": dt,
"raw_time": raw_time,
"method": method,
"path": path,
"protocol": protocol,
"status": data.get("status"),
"size": size,
"referrer": data.get("referrer"),
"agent": data.get("agent"),
}
def analyze_log(file_obj):
"""Stream through log file object and compute summary statistics."""
total_requests = 0
total_bytes = 0
ip_counts = Counter()
url_counts = Counter()
status_counts = Counter()
minute_counts = Counter() # requests per minute (datetime with second=0)
for line in file_obj:
parsed = parse_line(line)
if not parsed:
continue
total_requests += 1
total_bytes += parsed["size"]
# Count IPs
if parsed["ip"]:
ip_counts[parsed["ip"]] += 1
# Count URLs
if parsed["path"]:
url_counts[parsed["path"]] += 1
# Count status codes
if parsed["status"]:
status_counts[parsed["status"]] += 1
# Count per-minute traffic
if parsed["time"]:
minute = parsed["time"].replace(second=0, microsecond=0)
minute_counts[minute] += 1
return {
"total_requests": total_requests,
"total_bytes": total_bytes,
"ip_counts": ip_counts,
"url_counts": url_counts,
"status_counts": status_counts,
"minute_counts": minute_counts,
}
def print_top(counter, n, title):
"""Print top N items from a Counter."""
print(f"\n{title} (top {n}):")
for item, count in counter.most_common(n):
print(f"{count:8} {item}")
def format_bytes(num):
"""Human-readable bytes."""
for unit in ["B", "KB", "MB", "GB", "TB"]:
if num < 1024.0:
return f"{num:.2f} {unit}"
num /= 1024.0
return f"{num:.2f} PB"
def main():
parser = argparse.ArgumentParser(
description="Parse and analyze Apache access log files (Common/Combined)."
)
parser.add_argument("logfile", help="Path to Apache access log file")
parser.add_argument("--top-ips", type=int, default=10,
help="Number of top IPs to show (default: 10)")
parser.add_argument("--top-urls", type=int, default=10,
help="Number of top URLs to show (default: 10)")
parser.add_argument("--top-minutes", type=int, default=10,
help="Number of busiest minutes to show (default: 10)")
args = parser.parse_args()
try:
with open(args.logfile, "r", encoding="utf-8", errors="replace") as f:
stats = analyze_log(f)
except FileNotFoundError:
print(f"Error: file not found: {args.logfile}", file=sys.stderr)
sys.exit(1)
# Basic summary
print(f"Log file: {args.logfile}")
print(f"Total requests: {stats['total_requests']}")
print(f"Total bytes sent: {stats['total_bytes']} "
f"({format_bytes(stats['total_bytes'])})")
print(f"Unique IPs: {len(stats['ip_counts'])}")
print(f"Unique URLs: {len(stats['url_counts'])}")
# Status codes
print("\nStatus code distribution:")
for status, count in sorted(stats["status_counts"].items()):
pct = (count / stats["total_requests"] * 100) if stats["total_requests"] else 0
print(f"{status}: {count} ({pct:.2f}%)")
# Top IPs, URLs, busiest minutes
print_top(stats["ip_counts"], args.top_ips, "Top IP addresses by request count")
print_top(stats["url_counts"], args.top_urls, "Top URLs by request count")
# Busiest minutes
if stats["minute_counts"]:
print(f"\nBusiest minutes (top {args.top_minutes}):")
for minute, count in stats["minute_counts"].most_common(args.top_minutes):
print(f"{count:8} {minute.strftime('%Y-%m-%d %H:%M')}")
if __name__ == "__main__":
main()