import re
from collections import Counter
def analyze_logs(log_file_path):
pattern = r' - .* - .* - (.*Error):'
error_counter = Counter()
with open(log_file_path, 'r', encoding='utf-8') as file:
for line in file:
match = re.search(pattern, line)
if match:
error_type = match.group(1)
error_counter[error_type] += 1
sorted_errors = sorted(error_counter.items(), key=lambda item: item[1], reverse=True)
for error_type, count in sorted_errors:
print(f'{error_type}: {count}')
log_file_path = 'your_log_file.log'
analyze_logs(log_file_path)
- 导入必要的模块:
re
用于正则表达式匹配,collections.Counter
用于统计不同类型异常出现的次数。
- 定义分析日志的函数
analyze_logs
:
- 使用正则表达式
r' - .* - .* - (.*Error):'
匹配日志中的异常类型。
- 初始化一个
Counter
对象error_counter
来统计异常类型出现的次数。
- 逐行读取日志文件,对每一行进行正则匹配,如果匹配成功,提取异常类型并更新
error_counter
。
- 使用
sorted
函数按照异常出现次数从高到低对error_counter
中的数据进行排序。
- 遍历排序后的结果并打印每种异常类型及其出现次数。
- 调用函数:将日志文件路径作为参数传入
analyze_logs
函数,如果日志文件路径不同,需要修改log_file_path
变量的值。