我正在查看以下格式的日志消息
datetime log_message_type message_type server {json_string}
因此,每一行都由空格分隔,每行始终具有相同的字段,最后在json块中包含一个json字符串,其中包含各种字段。
我考虑过用一个简单的方法
with open('test.log', 'r') as f:
for x in f:
line = x.split()
datetime = line[0]
log_message_type = line[1]
message_type = line[2]
server = line[3]
json_string = line[4]
这会行得通,除非我的json字符串中有空格,例如,像这样的东西。
{ "foo" : "bar" }
因此,以这种方式进行操作会在空格处拆分我的json字符串。有什么方法可以使用正则表达式或仅在到达行的“ json字符串”部分,然后保留其余部分之前在空格上分割的内容?我尝试做类似的事情
line = re.compile(".*\s.*\s.*\s.*\s").split(x)
为了尝试根据json字符串部分之前的4个空格来解析行,但是恐怕我对python中的regex系统是如何工作的还不够了解。有人可以帮我吗?
编辑:忘了提,我为此停留在python 2.7。
尝试这样的事情。正则表达式会很快失去控制。
log_line = "datetime log_message_type message_type server {json_string}"
json_part = log_line.split(None, 4)[-1]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句