python
#!/usr/bin/env python3
"""
Log Analyzer Tool
=================
A Python command-line tool to analyze and visualize log files using pandas and matplotlib.
Features:
- Parses standard log format: "YYYY-MM-DD HH:MM:SS [LEVEL] message"
- Computes statistics: total logs, level counts, peak activity times.
- Generates visualizations:
- Bar chart: Log level distribution
- Line chart: Logs per hour
- Pie chart: Log level proportions
- Bar chart: Top 10 error messages (if errors exist)
- Outputs plots as PNG files and prints summary stats to console.
Usage:
python log_analyzer.py /path/to/logfile.log
Requirements:
pip install pandas matplotlib
Author: Sherlock (Trailblazer Labs)
"""
import argparse
import re
from datetime import datetime
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
def parse_log_line(line: str) -> tuple | None:
"""
Parse a single log line using regex.
Expected format: "YYYY-MM-DD HH:MM:SS [LEVEL] message"
Returns (timestamp, level, message) or None if invalid.
"""
pattern = r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \[(INFO|WARN|ERROR|DEBUG)\] (.*)$'
match = re.match(pattern, line.strip())
if match:
ts_str, level, msg = match.groups()
try:
ts = datetime.strptime(ts_str, '%Y-%m-%d %H:%M:%S')
return ts, level, msg
except ValueError:
return None
return None
def load_log_data(logfile: str) -> pd.DataFrame:
"""Load and parse the log file into a pandas DataFrame."""
data = []
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 parsed:
data.append(parsed)
# Optional: print warning for unparsed lines
# else: print(f"Warning: Could not parse line {line_num}: {line.strip()[:100]}...")
if not data:
raise ValueError("No valid log entries found in the file.")
df = pd.DataFrame(data, columns=['timestamp', 'level', 'message'])
df['timestamp'] = pd.to_datetime(df['timestamp'])
return df
def analyze_data(df: pd.DataFrame) -> dict:
"""Perform analysis and return summary statistics."""
total_logs = len(df)
level_counts = df['level'].value_counts()
ts_df = df.set_index('timestamp')
hourly_counts = ts_df.resample('H').size()
peak_hour = hourly_counts.idxmax().hour if not hourly_counts.empty else None
error_df = df[df['level'] == 'ERROR']
top_errors = error_df['message'].value_counts().head(10) if not error_df.empty else pd.Series()
return {
'total_logs': total_logs,
'level_counts': level_counts,
'hourly_counts': hourly_counts,
'peak_hour': peak_hour,
'top_errors': top_errors,
}
def plot_visualizations(df: pd.DataFrame, output_dir: Path):
"""Generate and save matplotlib visualizations."""
output_dir.mkdir(parents=True, exist_ok=True)
level_counts = df['level'].value_counts()
ts_df = df.set_index('timestamp')
hourly_counts = ts_df.resample('H').size()
error_df = df[df['level'] == 'ERROR']
top_errors = error_df['message'].value_counts().head(10)
# 1. Bar chart: Log level distribution
plt.figure(figsize=(10, 6))
level_counts.plot(kind='bar', color=['green', 'orange', 'red', 'blue'])
plt.title('Log Level Distribution')
plt.xlabel('Log Level')
plt.ylabel('Count')
plt.xticks(rotation=0)
plt.tight_layout()
plt.savefig(output_dir / 'log_levels_bar.png', dpi=300, bbox_inches='tight')
plt.close()
# 2. Line chart: Logs per hour
plt.figure(figsize=(12, 6))
hourly_counts.plot(kind='line', marker='o', linewidth=2)
plt.title('Logs per Hour')
plt.xlabel('Hour')
plt.ylabel('Count')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(output_dir / 'logs_per_hour.png', dpi=300, bbox_inches='tight')
plt.close()
# 3. Pie chart: Log level proportions
plt.figure(figsize=(8, 8))
level_counts.plot(kind='pie', autopct='%1.1f%%', startangle=90)
plt.title('Log Level Proportions')
plt.ylabel('')
plt.tight_layout()
plt.savefig(output_dir / 'log_levels_pie.png', dpi=300, bbox_inches='tight')
plt.close()
# 4. Top 10 Errors (horizontal bar)
if not top_errors.empty:
plt.figure(figsize=(12, 6))
top_errors.plot(kind='barh', color='red')
plt.title('Top 10 Error Messages')
plt.xlabel('Count')
plt.tight_layout()
plt.savefig(output_dir / 'top_errors.png', dpi=300, bbox_inches='tight')
plt.close()
def print_summary(stats: dict):
"""Print analysis summary to console."""
print("\n" + "="*50)
print("LOG ANALYSIS SUMMARY")
print("="*50)
print(f"Total log entries: {stats['total_logs']:,}")
print("\nLog level counts:")
for level, count in stats['level_counts'].items():
print(f" {level}: {count:,}")
print(f"\nPeak activity hour: {stats['peak_hour']}:00" if stats['peak_hour'] is not None else "\nNo peak hour data.")
if not stats['top_errors'].empty:
print("\nTop 5 errors:")
for msg, count in stats['top_errors'].head().items():
print(f" {msg[:80]}...: {count}")
print("="*50 + "\n")
def main():
parser = argparse.ArgumentParser(description="Analyze and visualize log files.")
parser.add_argument('logfile', help='Path to the log file')
parser.add_argument('--output-dir', '-o', default='log_analysis_output',
help='Output directory for plots (default: log_analysis_output)')
args = parser.parse_args()
try:
# Load data
print("Parsing log file...")
df = load_log_data(args.logfile)
# Analyze
print("Analyzing data...")
stats = analyze_data(df)
# Print summary
print_summary(stats)
# Generate plots
print("Generating visualizations...")
plot_visualizations(df, Path(args.output_dir))
print(f"Plots saved to: {args.output_dir}/")
print("Done! 🎉")
except FileNotFoundError:
print(f"Error: Log file '{args.logfile}' not found.")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
if __name__ == '__main__':
main()