41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Log analyzer - counts log entries by level and outputs JSON summary."""
|
|
import json
|
|
import re
|
|
import sys
|
|
from collections import Counter
|
|
from pathlib import Path
|
|
|
|
def analyze_logs(file_path: str) -> dict:
|
|
"""Analyze a log file and return counts by log level."""
|
|
pattern = re.compile(r'\b(DEBUG|INFO|WARNING|ERROR|CRITICAL)\b', re.IGNORECASE)
|
|
counts = Counter()
|
|
total = 0
|
|
|
|
with open(file_path, 'r') as f:
|
|
for line in f:
|
|
matches = pattern.findall(line)
|
|
for match in matches:
|
|
counts[match.upper()] += 1
|
|
total += 1
|
|
|
|
return {
|
|
"file": Path(file_path).name,
|
|
"total_entries": total,
|
|
"by_level": dict(sorted(counts.items())),
|
|
"unique_levels": len(counts)
|
|
}
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) != 3:
|
|
print("Usage: log_analyzer.py <log_file> <output_json>")
|
|
sys.exit(1)
|
|
|
|
result = analyze_logs(sys.argv[1])
|
|
output_path = sys.argv[2]
|
|
|
|
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
|
|
with open(output_path, 'w') as f:
|
|
json.dump(result, f, indent=2)
|
|
|
|
print(f"Analyzed {result['total_entries']} entries to {output_path}") |