如何过滤各/vol实例过滤启动后的日志事件并生成字典?
问题
我有一个包含时间戳和事件的日志文件,内容如下:
Mon Jan 15 22:16:46 PST 2024 /vol/vol1 Sorting file records (120 entries) Mon Jan 15 22:16:46 PST 2024 /vol/vol2 Sorting file records (120 entries) Mon Jan 15 22:16:46 PST 2024 /vol/vol1 Sorting text records (120 entries) Mon Jan 15 22:16:46 PST 2024 /vol/vol2 Sorting file records (120 entries) Mon Jan 15 22:16:47 PST 2024 /vol/vol1 Sort (0 entries) Mon Jan 15 22:16:47 PST 2024 /vol/vol1 Pass (0 entries) Mon Jan 15 22:16:47 PST 2024 /vol/vol2 Sort (0 entries) Mon Jan 15 22:16:47 PST 2024 /vol/vol2 Pass (0 entries) **Mon Jan 15 22:16:47 PST 2024 /vol/vol1 ( Filetering start )** Mon Jan 15 22:51:46 PST 2024 /vol/vol1 Sorting file records (121 entries) Mon Jan 15 22:56:46 PST 2024 /vol/vol1 Sorting text records (122 entries) **Mon Jan 15 22:56:47 PST 2024 /vol/vol2 ( Filetering start )** Mon Jan 15 22:56:47 PST 2024 /vol/vol1 Sort (0 entries) Mon Jan 15 22:57:47 PST 2024 /vol/vol1 Pass (0 entries)
我需要解析日志,为每个/vol/*实例提取**“Filetering start”事件之后**的事件,生成包含实例名和事件的字典,预期结果示例如下:
For /vol/vol1: Mon Jan 15 22:51:46 PST 2024 /vol/vol1 Sorting file records (121 entries) Mon Jan 15 22:56:46 PST 2024 /vol/vol1 Sorting text records (122 entries) For /vol/vol2: No lines as after filetering start there arent any events logged.
我尝试了以下Python代码来生成字典,但该字典会包含“Filetering start”事件之前的无效事件,请问如何修改代码解决这个问题?
r = { 'vol':[], 'Sorting file':[], } with open(file) as fh: for line in fh: if "Sorting file records" in line: line = line.split(); r['Sorting File'].append(line[3]) for i in line: if "/vol/" in i: r['vol'].append(i)
解决方案
核心思路是跟踪每个卷的过滤起始状态,只收集对应卷触发“Filetering start”之后的事件,修改后的代码如下:
def parse_log(file_path): # 结果字典:键为卷名,值为该卷过滤后的事件列表 result = {} # 记录每个卷是否已触发过滤开始 filter_started = {} with open(file_path, 'r') as fh: for line in fh: line_clean = line.strip() if not line_clean: continue # 跳过空行 # 识别过滤开始事件,标记对应卷的状态 if "( Filetering start )" in line_clean: parts = line_clean.split() vol_name = next(p for p in parts if "/vol/" in p) filter_started[vol_name] = True # 初始化该卷的事件列表 if vol_name not in result: result[vol_name] = [] continue # 收集已触发过滤的卷的后续事件 for vol in filter_started: if vol in line_clean and filter_started[vol]: result[vol].append(line_clean) break # 按预期格式输出结果 for vol in result: print(f"For {vol}:") if result[vol]: for event in result[vol]: print(f" {event}") else: print(" No lines as after filetering start there arent any events logged.") print() # 替换为你的日志文件路径 parse_log("your_log_file.log")
代码说明
- 状态跟踪:用
filter_started字典精准控制每个卷的采集开关,只有当该卷触发过滤开始后,才会收集后续事件。 - 结果结构:
result字典直接以卷名为键,对应值是该卷过滤后的所有事件,完全匹配需求中的字典结构。 - 空行处理:跳过日志中的空行,避免无效解析。
- 输出匹配:最终输出格式和预期示例完全一致,便于直接查看结果。
内容的提问来源于stack exchange,提问作者user3555115
相关产品推荐
相关产品推荐

