简体   繁体   English

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

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

I'm trying to create this program which opens up a .gz file and looks for multiple exceptions. 我正在尝试创建该程序,该程序打开一个.gz文件并查找多个异常。 It was working when I just used one exception. 当我只使用一个例外时,它正在工作。 But I am now trying to get multiple exceptions, and it is not working. 但是我现在正在尝试获取多个异常,并且它不起作用。

Can anyone help? 有人可以帮忙吗?

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"

I believe this code meets your problem statement. 我相信这段代码符合您的问题陈述。 Two key changes from your code. 代码中的两个关键更改。

  1. Put error message and keywords to search for together in the same data structure. 将错误消息和关键字放在同一数据结构中一起搜索。

  2. Loop over the data structure and directly determine if all keywords are present, and if not store the error message for later display 遍历数据结构并直接确定是否存在所有关键字,如果不存在则存储错误消息以供以后显示

Please note: I did not actually test this code, as I had no sample data. 请注意:我没有实际测试此代码,因为我没有示例数据。

Code: 码:

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