如何匹配日志PROF_DETAILS条目提取字段值生成目标格式字典
控制台日志PROF_DETAILS解析方案
可直接运行的Python实现代码
def parse_prof_details(log_content: str) -> dict: prof_details = {} # 拆分日志行,过滤出以竖线开头的表格行 lines = [line.strip() for line in log_content.splitlines() if line.strip().startswith('|')] if not lines: return prof_details # 提取表头,去除多余空格和空值 headers = [h.strip() for h in lines[0].split('|') if h.strip()] # 逐行解析表格数据 for line in lines[1:]: fields = [f.strip() for f in line.split('|') if f.strip()] # 跳过字段数不匹配的异常行 if not fields or len(fields) != len(headers): continue prof_name = fields[headers.index('prof_name')] # 拼接内层字段字典 prof_item = {headers[i]: fields[i] for i in range(len(headers))} prof_details[prof_name] = prof_item return prof_details # 调用示例 if __name__ == '__main__': # 替换为实际读取到的原始日志内容 raw_log = """ > PROF_DETAILS: |prof_name | cnt| min| max| last| tot| avg| intvl| hist| pf_max| pf_avg| pf_tot|ignoredCnt| intHist|intMax| |PROF_1 | 16816| 0| 158| 0| 197893| 11| 500| 16816: 0: 0| 0| 0| 0| 72592|85578:3830: 0| 4| |PROF_2 |32436579| 0| 193| 0|936877226| 28| 500|32436571: 0: 0| 0| 0| 0| 0|32394220:42351: 0| 4| |PROF_3 |32511390| 0| 210| 0|2023670249| 62| 500|32511390: 0: 0| 0| 0| 0| 146|29121201:3390335: 0| 4| |PROF_4 | 3| 0| 7| 0| 20| 6| 500| 3: 0: 0| 0| 0| 0| 12| 15: 0: 0| 0| |PROF_5 | 0| 0| 0| 0| 0| 0| 500| 0: 0: 0| 0| 0| 0| 0| 0: 0: 0| 0| |PROF_6 | 0| 0| 0| 0| 0| 0| 500| 0: 0: 0| 0| 0| 0| 0| 0: 0: 0| 0| """ PROF_DETAILS = parse_prof_details(raw_log) print(PROF_DETAILS)
输出结构说明
运行代码后得到的PROF_DETAILS完全符合要求的嵌套字典格式,示例片段如下:
{ 'PROF_1': { 'prof_name': 'PROF_1', 'cnt': '16816', 'min': '0', 'max': '158', 'last': '0', 'tot': '197893', 'avg': '11', 'intvl': '500', 'hist': '16816: 0: 0', 'pf_max': '0', 'pf_avg': '0', 'pf_tot': '0', 'ignoredCnt': '72592', 'intHist': '85578:3830: 0', 'intMax': '4' }, 'PROF_2': { # PROF_2对应字段数据 } # 其余PROF条目自动补全 }
如果需要将数值类字段自动转换为int/float类型,只需要在生成内层字典时增加类型判断逻辑即可。
内容的提问来源于stack exchange,提问作者Dipankar
相关产品推荐
相关产品推荐

