如何解析用python实时编写的JSON文件?

2024-05-29 10:05:24 发布

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

我使用的是一个linux服务,它在/var/log中生成JSON格式的日志。日志文件几乎一直在增加。实际上,我正在使用的服务没有任何数据库连接器或包装器来将日志直接发送到数据库,因此我将不得不使用自己的服务进行解析和发送。在

哪种方式是不断解析文件并将新行上载到数据库的最佳方式?在

加:我不想使用任何与麋鹿堆有关的东西

谢谢!在


Tags: 文件log数据库jsonvarlinux格式方式
1条回答
网友
1楼 · 发布于 2024-05-29 10:05:24

要读取该文件,它类似于tail命令,我编写了一个小脚本:

logtodb.py

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'"}

如果我的脚本格式不对,我可以帮你更新

相关问题 更多 >

    热门问题