#!/usr/bin/env python3
"""
Apache Log Analyzer
Parses Apache access logs (Common or Combined Log Format) and provides key statistics.
Usage:
python3 apache_log_analyzer.py <logfile> [options]
Options:
-h, --help Show this help
--top-ips N Top N IP addresses (default: 10)
--top-agents N Top N user agents (default: 10)
--json Output as JSON
"""
import argparse
import json
import re
import sys
from collections import Counter, defaultdict
from datetime import datetime
from typing import Dict, Any, Optional
# Regex for Combined/Common Log Format
LOG_PATTERN = re.compile(
r'^(?P<host>\S+)' # host (IP or hostname)
r'\s+(?P<logname>-|\S+)' # logname (often -)
r'\s+(?P<user>-|\S+)' # user
r'\s+\[(?P<timestamp>[^\]]+)\]' # timestamp
r'\s+"(?:' # request start
r'(?P<method>\S+)' # method
r'\s+(?P<url>\S+)' # url
r'\s+(?P<protocol>\S+)' # protocol
r')?"' # request end
r'\s+(?P<status>\d{3}|-)' # status
r'\s+(?P<size>-|\d+)' # size
r'(?:\s+"(?P<referrer>-|"[^"]*")"' # referrer (combined)
r'\s+"(?P<useragent>-|"[^"]*")")?' # useragent (combined)
r'\s*$'
)
def parse_log_line(line: str) -> Optional[Dict[str, Any]]:
"""
Parse a single Apache log line into a dictionary.
Returns None if parsing fails.
"""
match = LOG_PATTERN.match(line.strip())
if not match:
return None
data = match.groupdict()
# Convert numeric fields
data['status'] = int(data['status']) if data['status'] != '-' else None
data['size'] = int(data['size']) if data['size'] != '-' else 0
# Parse timestamp
try:
ts_str = data['timestamp']
# Handle timezone offset like +0000 or -0400
dt = datetime.strptime(ts_str[:-6], '%d/%b/%Y:%H:%M:%S')
data['datetime'] = dt
data['hour'] = dt.hour
data['date'] = dt.date()
except ValueError:
data['datetime'] = None
data['hour'] = None
data['date'] = None
# Clean up quoted fields
for field in ['referrer', 'useragent']:
if data[field] and data[field].startswith('"') and data[field].endswith('"'):
data[field] = data[field][1:-1]
return data
def analyze_log(logfile: str, top_ips: int = 10, top_agents: int = 10) -> Dict[str, Any]:
"""
Analyze the log file and return statistics as a dict.
"""
stats = defaultdict(lambda: Counter())
total_requests = 0
total_bytes = 0
valid_lines = 0
errors = 0
with open(logfile, 'r', encoding='utf-8', errors='ignore') as f:
for line_num, line in enumerate(f, 1):
parsed = parse_log_line(line)
if not parsed:
errors += 1
continue
valid_lines += 1
total_requests += 1
# Counters
stats['by_status'][parsed['status']] += 1
stats['by_ip'][parsed['host']] += 1
stats['by_hour'][parsed['hour']] += 1 if parsed['hour'] is not None else 0
stats['by_date'][parsed['date']] += 1 if parsed['date'] is not None else 0
stats['by_method'][parsed['method']] += 1
# Bytes
total_bytes += parsed['size']
# User agent (top N later)
ua = parsed['useragent'] or '-'
stats['by_useragent'][ua] += 1
# Compute derived stats
results = {
'summary': {
'total_requests': total_requests,
'valid_lines': valid_lines,
'error_lines': errors,
'total_bytes': total_bytes,
'avg_response_size': total_bytes / total_requests if total_requests > 0 else 0,
},
'status_codes': dict(stats['by_status'].most_common()),
'top_ips': dict(stats['by_ip'].most_common(top_ips)),
'top_useragents': dict(stats['by_useragent'].most_common(top_agents)),
'requests_by_hour': dict(stats['by_hour']),
'requests_by_date': {str(k): v for k, v in stats['by_date'].items()},
'top_methods': dict(stats['by_method'].most_common()),
}
return results
def print_stats(stats: Dict[str, Any]):
"""Print statistics in a human-readable format."""
s = stats['summary']
print(f"Summary:")
print(f" Total Requests: {s['total_requests']:,}")
print(f" Valid Lines: {s['valid_lines']:,}")
print(f" Error Lines: {s['error_lines']:,}")
print(f" Total Bytes Served: {s['total_bytes']:,}")
print(f" Average Response Size: {s['avg_response_size']:.1f} bytes")
print()
print("Status Codes:")
for code, count in stats['status_codes'].items():
pct = (count / s['total_requests']) * 100
print(f" {code}: {count:,} ({pct:.1f}%)")
print()
print(f"Top 10 IPs:")
for ip, count in stats['top_ips'].items():
print(f" {ip}: {count:,}")
print()
print(f"Top 10 User Agents:")
for ua, count in stats['top_useragents'].items():
print(f" {ua[:60]}...: {count:,}")
print()
print("Requests by Hour (0-23):")
for hour, count in sorted(stats['requests_by_hour'].items()):
print(f" {hour:2d}:00 - {hour:2d}:59: {count:,}")
print()
print("Requests by Date:")
for date, count in sorted(stats['requests_by_date'].items()):
print(f" {date}: {count:,}")
def main():
parser = argparse.ArgumentParser(description="Analyze Apache access logs.")
parser.add_argument('logfile', help="Path to the Apache log file")
parser.add_argument('--top-ips', type=int, default=10, help="Top N IPs to show")
parser.add_argument('--top-agents', type=int, default=10, help="Top N user agents to show")
parser.add_argument('--json', action='store_true', help="Output as JSON")
args = parser.parse_args()
try:
stats = analyze_log(args.logfile, args.top_ips, args.top_agents)
if args.json:
print(json.dumps(stats, indent=2, default=str))
else:
print_stats(stats)
except FileNotFoundError:
print(f"Error: File '{args.logfile}' not found.", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error analyzing log: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()
Features
- Parses Common/Combined Log Formats: Handles IP, user, timestamp, request, status, size, referrer, user-agent.
- Robust Parsing: Skips invalid lines, handles missing fields (
-), quoted strings.
- Key Statistics:
- Total requests, bytes served, average size.
- Breakdown by status code (with %).
- Top IPs and User-Agents (configurable).
- Requests by hour and date.
- Top HTTP methods.
- CLI Options:
--top-ips N, --top-agents N, --json for machine-readable output.
- Error Handling: Ignores encoding issues, invalid lines; reports counts.
- Performance: Efficient with
Counter; streams large files.
Example Usage
python3 apache_log_analyzer.py /var/log/apache2/access.log
python3 apache_log_analyzer.py access.log --top-ips 5 --json > stats.json
Sample Output (Console)
Summary:
Total Requests: 1,234,567
Valid Lines: 1,234,550
Error Lines: 17
Total Bytes Served: 1,234,567,890
Average Response Size: 1,000.0 bytes
Status Codes:
200: 1,100,000 (89.1%)
404: 50,000 (4.0%)
...
This script is production-ready for typical Apache logs. Test with your logs and extend as needed (e.g., bot detection via user-agent patterns).