繁体   English   中英

在日志文件行中搜索多个关键字并找到返回错误字符串

[英]Search multiple keywords in log file line and return error string is all found

我正在尝试创建该程序,该程序打开一个.gz文件并查找多个异常。 当我只使用一个例外时,它正在工作。 但是我现在正在尝试获取多个异常,并且它不起作用。

有人可以帮忙吗?

import gzip
with gzip.open((raw_input("Enter File Name :")), 'r') as f:
     x1 = ['REBINFO', 'cocaLc']
     y1 = [False, False]
     x2 = ['dispute', 'peer', 'while', 'priority']
     y2 = [False, False, False, False]
     x3 = ['task cocaLc ASSERT failed', 'fhAssert', 'REBINFO', 'HARDREBOOT', '09.']
     y3 = [False, False, False, False, False]
     for line in f:
         for i in range(0, len(x1)):
             if (x1, x2, x3) [i] in line: #loop through x1, x2, x3 using index numbers
                 y1[i] = True
                 y2[i] = True
                 y3[i] = True

 if all(y1): #if every search string was detected, every value in y1 should be true
     print "Exception Found : " + "task cocaLc Requested reboot"
 if all(y2): #if every search string was detected, every value in y2 should be true
     print "\nException Found : " + "task tAlrmL1 Keep alive failed"
 if all(y3): #if every search string was detected, every value in y3 should be true
     print "\nException Found : task cocaLc ASSERT failed"

我相信这段代码符合您的问题陈述。 代码中的两个关键更改。

  1. 将错误消息和关键字放在同一数据结构中一起搜索。

  2. 遍历数据结构并直接确定是否存在所有关键字,如果不存在则存储错误消息以供以后显示

请注意:我没有实际测试此代码,因为我没有示例数据。

码:

import gzip

errors_to_find = (
    ('task cocaLc Requested reboot', 
     ('REBINFO', 'cocaLc')),
    ('task tAlrmL1 Keep alive failed',
     ('dispute', 'peer', 'while', 'priority')),
    ('task cocaLc ASSERT failed', 
     ('fhAssert', 'REBINFO', 'HARDREBOOT')),
)

found_exc = []
with gzip.open((raw_input("Enter File Name :")), 'r') as f:
    for line in f:
        for msg, key_words in errors_to_find:

            # for each keyword, test if it is in line 
            if sum([kw in line for kw in key_words]) == len(key_words):
                found_exc.append(msg)

for msg in found_exc:
    print "Exception Found : %s" % msg

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM