如何仅从消息中解析此日志的开头

时间:2016-12-12 22:02:32

标签: python parsing logfile

2015-05-22 16:46:46,985 - __main__ - INFO - Starting to Wait for Files
2015-05-22 16:46:56,645 - __main__ - INFO - Starting: Attempt 1 Checking for New Files from gs://folder/folder/
2015-05-22 16:47:46,488 - __main__ - INFO - Success: Downloading the Files from Cloud Storage: Return Code - 0 and FileCount 1
2015-05-22 16:48:48,180 - __main__ - ERROR - Failed: Waiting for files the Files from Cloud Storage: gs://folder/folder/

我需要用ERROR打印每条消息

Failed: Waiting for files the Files from Cloud Storage: gs://folder/folder/
...

2 个答案:

答案 0 :(得分:0)

使用简单的列表理解str.split()函数的解决方案:

err_mark = '- ERROR -'
with open('error.log', 'r') as fh:
    err_log = [l.split(err_mark)[1] for l in fh.readlines() if err_mark in l]

print(err_log)

输出:

[' Failed: Waiting for files the Files from Cloud Storage: gs://folder/folder/']

答案 1 :(得分:0)

import re
lines = [line for line in in_.splitlines() if "ERROR" in line]
x = [re.sub(".+ERROR - ",'', line ) for line in lines]
print(x)