如何获取日志字符串的最后一部分并将其解释为json?

2024-06-02 05:35:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在查看以下格式的日志消息

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字符串。有没有什么方法可以使用regex或其他东西只在空白处拆分,直到到达行的“json string”部分,然后保留其余部分?我试着做一些类似

line = re.compile(".*\s.*\s.*\s.*\s").split(x)

尝试基于json字符串部分前面的4个空格来解析行,但我恐怕对python中的regex系统的工作原理了解不够。谁能帮我一下吗?你知道吗

编辑:忘了提一下,我一直坚持使用Python2.7。你知道吗


Tags: 字符串logjson消息messagedatetimestringserver
3条回答

如果您使用的是python3,那么就可以利用extended iterable unpacking。你知道吗

long_string = "example example test test test test test test"
x1, x2, *tests = long_string.split()
tests = ' '.join(tests)
print(tests)
#test test test test test test

试试这样的。正则表达式很快就会失控。你知道吗

log_line = "datetime log_message_type message_type server {json_string}"
json_part = log_line.split(None, 4)[-1]

限制拆分的数目:

line = x.split(maxsplit=4)

>>> "a b c d my json expression".split(maxsplit=4)
['a', 'b', 'c', 'd', 'my json expression']

注意:python 2参数不同,您必须将then作为位置传递(顺便说一句,也适用于python 3):

line = x.split(None,4)

相关问题 更多 >