1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
| from collections import Counter import re from datetime import datetime import matplotlib.pyplot as plt from pathlib import Path
def analyze_log_file(log_path, pattern=None): """ 分析日志文件并生成报告 参数: log_path: 日志文件路径 pattern: 用于匹配日志行的正则表达式模式(默认为None,表示所有行) 返回: 包含分析结果的字典 """ log_path = Path(log_path) if not log_path.exists(): raise FileNotFoundError(f"日志文件不存在: {log_path}") results = { 'total_lines': 0, 'matched_lines': 0, 'errors': 0, 'warnings': 0, 'by_hour': Counter(), 'ip_addresses': Counter(), 'status_codes': Counter(), 'top_urls': Counter() } if pattern: regex = re.compile(pattern) ip_pattern = re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b') status_pattern = re.compile(r'\s(\d{3})\s') timestamp_pattern = re.compile(r'\[(\d{2}/\w{3}/\d{4}):(\d{2}):\d{2}:\d{2}\s[+\-]\d{4}\]') url_pattern = re.compile(r'"(?:GET|POST|PUT|DELETE)\s+([^\s"]+)') error_pattern = re.compile(r'ERROR|CRITICAL|FATAL', re.IGNORECASE) warning_pattern = re.compile(r'WARNING|WARN', re.IGNORECASE) with open(log_path, 'r', encoding='utf-8', errors='ignore') as f: for line in f: results['total_lines'] += 1 if pattern and not regex.search(line): continue results['matched_lines'] += 1 ip_matches = ip_pattern.findall(line) if ip_matches: results['ip_addresses'].update([ip_matches[0]]) status_match = status_pattern.search(line) if status_match: results['status_codes'].update([status_match.group(1)]) url_match = url_pattern.search(line) if url_match: results['top_urls'].update([url_match.group(1)]) time_match = timestamp_pattern.search(line) if time_match: date_str, hour = time_match.groups() results['by_hour'].update([int(hour)]) if error_pattern.search(line): results['errors'] += 1 elif warning_pattern.search(line): results['warnings'] += 1 return results
def generate_log_report(results, output_dir=None): """生成日志分析报告(文本和图表)""" output_dir = Path(output_dir) if output_dir else Path.cwd() if not output_dir.exists(): output_dir.mkdir(parents=True) report_path = output_dir / "log_analysis_report.txt" with open(report_path, 'w', encoding='utf-8') as f: f.write("=== 日志分析报告 ===\n") f.write(f"总行数: {results['total_lines']}\n") f.write(f"匹配行数: {results['matched_lines']}\n") f.write(f"错误数: {results['errors']}\n") f.write(f"警告数: {results['warnings']}\n\n") f.write("=== 按小时分布 ===\n") for hour in sorted(results['by_hour']): f.write(f"{hour}时: {results['by_hour'][hour]}行\n") f.write("\n=== 前10个IP地址 ===\n") for ip, count in results['ip_addresses'].most_common(10): f.write(f"{ip}: {count}次\n") f.write("\n=== HTTP状态码统计 ===\n") for status, count in results['status_codes'].most_common(): f.write(f"{status}: {count}次\n") f.write("\n=== 前10个URL ===\n") for url, count in results['top_urls'].most_common(10): f.write(f"{url}: {count}次\n") plt.figure(figsize=(10, 6)) hours = range(24) counts = [results['by_hour'].get(hour, 0) for hour in hours] plt.bar(hours, counts) plt.xlabel('小时') plt.ylabel('日志条目数') plt.title('日志按小时分布') plt.xticks(hours) plt.grid(True, axis='y', alpha=0.3) plt.savefig(output_dir / 'hourly_distribution.png') plt.figure(figsize=(8, 8)) status_codes = list(results['status_codes'].keys()) counts = list(results['status_codes'].values()) plt.pie(counts, labels=status_codes, autopct='%1.1f%%', startangle=140) plt.axis('equal') plt.title('HTTP状态码分布') plt.savefig(output_dir / 'status_codes_pie.png') plt.figure(figsize=(10, 6)) top_ips = results['ip_addresses'].most_common(5) ips = [ip for ip, _ in top_ips] counts = [count for _, count in top_ips] plt.barh(ips, counts) plt.xlabel('请求次数') plt.ylabel('IP地址') plt.title('前5个IP地址') plt.grid(True, axis='x', alpha=0.3) plt.tight_layout() plt.savefig(output_dir / 'top_ips.png') return report_path
|