繁体   English   中英

使用python将access.log文件转换为json文件

[英]Convert access.log file into json file using python

我正在尝试将 nginx 的 access.log 文件转换为 json 格式,但我面临以下错误

索引错误:列表索引超出范围

import json

i = 1
result = {}
with open('access.log') as f:
lines = f.readlines()
for line in lines:
    r = str.split('\\s+')
    result[i-1] = {'timestamp': r[0], 'monitorip': r[1], 'monitorhost': r[2], 'monitorstatus': 
    r[3], 'monitorid': r[4], 'resolveip': r[5]}
    i += 1 
    print(result) 
with open('data.json', 'w') as fp:
json.dump(result, fp)

以下是我要转换的日志格式

以下是我要转换的日志格式

我面临的错误是:

Traceback (most recent call last):
File "/home/test.py", line 10, in <module>

result[i-1] = {'timestamp': r[0], 'monitorip': r[1], 'monitorhost': 
r[2], 'monitorstatus': r[3], 'monitorid': r[4], 'resolveip': r[5]}

IndexError: list index out of range

使用line.split()而不是str.split('\\s+') split()将常规字符串作为分隔符,而不是正则表达式。 它默认使用任何空格作为分隔符。

在尝试使用它之前检查r是否有足够的字段。 这将跳过任何不完整的行。

import json

i = 0
result = {}

with open('access.log') as f:
    lines = f.readlines()

for line in lines:
    r = line.split()
    if len(r) >= 6:
        result[i] = {'timestamp': r[0], 'monitorip': r[1], 'monitorhost': r[2], 'monitorstatus': 
                     r[3], 'monitorid': r[4], 'resolveip': r[5]}
        i += 1
    print(result) 

with open('data.json', 'w') as fp:
    json.dump(result, fp)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM