簡體   English   中英

python 解析日志文件:在不同的行中找到兩個特定的字符串並連接到一個並寫入另一個文件! 避免空行

[英]python parse log file: find two specific strings in different lines and concatenate in one and write to another file! Avoiding blank lines

我的日志喜歡這個文件

我需要看起來像什么:

行:5,錯誤:帳戶維度的成員不是基本級別。|>>>>>>A1399
行:6,錯誤:沒有這樣的成員|>>>>>>401700

我需要解析一個日志文件,只找到感興趣的錯誤並將它們寫入另一個文件。 下面是使用兩個標簽( 'Line:','>>>>>>' )的代碼我需要獲取這兩個標簽之后的所有字符串並連接到一個新行中。
我得到很多空行,兩個標簽在不同的行中。
先感謝您!

def main():
    fo = open("C:\\Users\\yannis\\py_script\\1198.log", "r", encoding="ISO-8859-1")
    ofile = open("C:\\Users\\yannis\\py_script\\out.txt",'a', newline='')
    member = ""
    erro = ""

    f1 = fo.readlines()
    for x in f1:
        erro = (x[x.find('Line:'):])
        member = (x[x.find('>>>>>>'):])

        linha = (erro + member)
        print(linha)
        ofile.write(linha)
        continue




    fo.close()
    ofile.close()



main()
def log_parser(path):
    with open(path, 'r', encoding='utf-8') as f:
        temp = dict()
        for index, line in enumerate(f.readlines()):
            _line_except = line[:-1]
            [day, time, level, something, *arg] = _line_except.split(' ')

            if 'Error:' in arg and 'Line:' in arg:
                temp = {
                    "log_info": " ".join([day, time, level, something]),
                    "log_str": " ".join(arg)
                }
            elif len(arg) == 1:
                print("{log_info} {log_str} || {other_args}".format(
                    log_info=temp['log_info'],
                    log_str=temp['log_str'],
                    other_args=arg[0])
                )
            else:
                continue


if __name__ == '__main__':
    log_parser("log.txt")

你會得到..

"""
OUTPUT : 
2020-07-03 15:21:58,962 ERROR [AIF]: Line: 5, Error: The member of the Account dimension is not base level. || >>>>>>A1399
2020-07-03 15:21:58,962 ERROR [AIF]: Line: 6, Error: No such member || >>>>>>401700
2020-07-03 15:21:58,962 ERROR [AIF]: Line: 7, Error: The member of the Account dimension is not base level. || >>>>>>A1399
2020-07-03 15:21:58,962 ERROR [AIF]: Line: 15, Error: The member of the Account dimension is not base level. || >>>>>>A2090
2020-07-03 15:21:58,962 ERROR [AIF]: Line: 16, Error: The member of the Account dimension is not base level. || >>>>>>A2090
2020-07-03 15:21:58,962 ERROR [AIF]: Line: 26, Error: No such member || >>>>>>101020
2020-07-03 15:21:58,962 ERROR [AIF]: Line: 27, Error: No such member || >>>>>>10132
"""

當您不在日志文件中寫入“>>>>12345”時,將會發生錯誤。 -> 它將在臨時字符串之前被丟棄。 你應該認出它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM