【问题标题】:How do I fetch lines in a log file如何获取日志文件中的行
【发布时间】:2022-08-02 17:03:30
【问题描述】:

我编写的程序将日志文件中的数据打印到 GUI。它通过选择一些特征来执行过滤操作。我正在逐行获取数据 我可以根据日期和时间格式获取带有单词的行。

但我想要的是获取我想要的行上方的行。 当我在条目中输入 5 时,我希望我要搜索的单词出现在上面的 5 行中。

例如,我的单词是\'Timer\'。当我在条目中写入 Timer 并选择前行复选框并在前行条目中写入 5 时。我想拿这个;

[01/01/70 02:00:18.699984 ] [debug  ] [1403] [DmTr069EventHandler.c:55] [dmTr069EventHandler_init] LEAVED 
[01/01/70 02:00:18.700122 ] [debug  ] [1403] [DmUkaEventHandler.c:50] [dmUkaEventHandler_init] ENTERED 
[01/01/70 02:00:18.700143 ] [debug  ] [1403] [DmUkaEventHandler.c:52] [dmUkaEventHandler_init] LEAVED 
[01/01/70 02:00:18.700154 ] [debug  ] [1403] [DmAppEventHandler.c:81] [dmAppEventHandler_init] ENTERED 
[01/01/70 02:00:18.700237 ] [debug  ] [1403] [Timer.c:441] [addTimerToSortedTimerList] ENTERED 

代码在这里。我尝试了一些东西,但它不适用于前线功能。

def search(msg, startingDate, endingDate, beforeLine, varBefore):
# clear current result
text.delete(\'1.0\', \'end\')
with open(\'OAM.log\', \'r\', encoding=\'latin1\') as fp:
    global l_no
    for l_no, line in enumerate(fp, 1):
        if msg and msg not in line:
            # does not contain search message, skip it
            continue
        if startingDate or endingDate:
            # get the timestamp
            timestamp = parse_date(line[1:25])
            # within startingDate and endingDate ?
            if startingDate and timestamp < startingDate:
                # before given starting date, skip it
                continue
            if endingDate and timestamp > endingDate:
                # after given ending date, skip it
                continue

        \"\"\"for count, beforeLine in enumerate(fp, 1):
            #bfline = fp.readlines(l_no - count)
            count -= 1
            text.insert(\'end\', \' \\n \')
            text.insert(\'end\', f\'Before Line Number: {l_no - beforeEntryVar.get()} Log: {beforeLine}\')
            text.insert(\'end\', \' \\n \')\"\"\"
            
        # insert the log
        text.insert(\'end\', \' \\n \')
        text.insert(\'end\', f\'Line Number: {l_no} Log: {line}\')
        text.insert(\'end\', \' \\n \')
  • 您是说因为第 5 行包含 Timer 而要获取第一行的示例数据?例如,如果 Timer 出现在文件的第 3 行,您会怎么做 - 即它前面的行少于 5 行?
  • 其实是这样的,如果这个词所在的行是第 5 行,我想让它去取它上面的 4 行。所以5-4-3-2-1。如果前面没有 5 行,那么要来多少行。

标签: python python-3.x python-2.7 tkinter


【解决方案1】:

最简单的方法是使用双端队列,如下所示:

import re
from collections import deque

d = deque([], 5)

with open('OAM.log') as log:
    for line in map(str.strip, log):
        d.append(line)
        m = re.findall(r'(?<=\[).+?(?=\])', line)
        if len(m) > 3 and m[3].startswith('Timer'):
            print(*d, sep='\n')

【讨论】:

    猜你喜欢
    • 2011-10-05
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多