如何用Python正则表达式提取Windows事件查看器错误日志的报错详情
Windows事件日志错误描述提取方案
你遇到的问题本质是没有找到日志的结构化特征,你给出的两则示例日志均遵循Windows事件日志的标准字段结构,不需要匹配错误内容的特征,只要锚定前面的固定字段,截取剩余内容即可,两种实现方案如下:
方案1:字段分割法(优先推荐)
Windows事件查看器导出的日志默认使用制表符(\t)分隔所有字段,错误描述永远是最后一个字段,直接分割取最后一位即可,代码简单稳定性高:
# 示例日志行 log_line = 'Error 7/8/2021 12:34:04 PM Microsoft-Windows-DistributedCOM 10005 None "DCOM got error ""15612"" attempting to start the service GamingServices with arguments ""Unavailable"" in order to run the server:' # 按制表符分割后取最后一个元素,strip()去掉首尾多余空白 error_msg = log_line.split('\t')[-1].strip()
如果你的日志是用多个空格分隔的,可以先把连续多空格替换为制表符再分割:
import re # 替换连续2个以上的空格为制表符 log_line = re.sub(r'\s{2,}', '\t', log_line) error_msg = log_line.split('\t')[-1].strip()
方案2:正则匹配法(适配非标准分隔场景)
如果日志没有统一的分隔符,可以用固定字段作为锚点写正则捕获目标内容,核心锚点为纯数字格式的事件ID,正则表达式如下:r'^Error\s+[\d/]+\s+[\d:]+\s+[AP]M\s+.+?\s+\d+\s+(?:None\s+)?(.+)$'
Python使用示例:
import re # 预编译正则 log_pattern = re.compile(r'^Error\s+[\d/]+\s+[\d:]+\s+[AP]M\s+.+?\s+\d+\s+(?:None\s+)?(.+)$') # 测试示例1 log1 = 'Error 7/8/2021 12:34:04 PM Microsoft-Windows-DistributedCOM 10005 None "DCOM got error ""15612"" attempting to start the service GamingServices with arguments ""Unavailable"" in order to run the server:' res1 = log_pattern.match(log1) if res1: print(res1.group(1)) # 测试示例2 log2 = 'Error 6/29/2021 3:15:50 PM Killer Network Service 16 Configuration Files Version Check and Upgrade Version Failed for Configuration File oem.xml' res2 = log_pattern.match(log2) if res2: print(res2.group(1))
正则各部分说明:
^Error匹配行首的错误级别标识,需要适配其他级别可改为(Error|Warning|Information)\s+[\d/]+\s+[\d:]+\s+[AP]M匹配完整的日期+时间戳部分.+?\s+\d+非贪婪匹配日志来源字段,直到遇到纯数字格式的事件ID(?:None\s+)?匹配可选的None字段,非捕获组不占用结果位(.+)$捕获行内剩余所有内容,即为目标错误描述
内容的提问来源于stack exchange,提问作者JSchofi95
相关产品推荐
相关产品推荐

