import json
import os
import time
def tail(stream_file):
""" Read a file like the Unix command `tail`. Code from https://stackoverflow.com/questions/44895527/reading-infinite-stream-tail """
stream_file.seek(0, os.SEEK_END) # Go to the end of file
while True:
if stream_file.closed:
raise StopIteration
line = stream_file.readline()
yield line
def log_to_db(log_path, db):
""" Read log (JSON format) and insert data in db """
with open(log_path, "r") as log_file:
for line in tail(log_file):
try:
log_data = json.loads(line)
except ValueError:
# Bad json format, maybe corrupted...
continue # Read next line
# Do what you want with data:
# db.execute("INSERT INTO ...", log_data["level"], ...)
print(log_data["message"])
和一个测试文件:
测试_logtodb.py
^{pr2}$
我假设日志文件如下所示:
{"level": "ERROR", "message": "The program exit with the code '181'"}
{"level": "WARNING", "message": "The program exit with the code '51'"}
{"level": "ERROR", "message": "The program exit with the code '69'"}
要读取该文件,它类似于
tail
命令,我编写了一个小脚本:logtodb.py
和一个测试文件:
测试_logtodb.py
^{pr2}$我假设日志文件如下所示:
如果我的脚本格式不对,我可以帮你更新
相关问题 更多 >
编程相关推荐