通过一段python代码完成loki中存储的日志的查询。尝试了整整一天。因为汉化的教程很少,我阅读英语又比较慢,所以摸索了很长一段时间。

最后实现的代码:

'''
调用logcli,查询loki中存储的日志,每行日志作为一个字符串,保存在一个列表里
'''
import subprocess
from io import StringIO

# 构建logQL查询命令
# 官方说明:https://grafana.com/docs/loki/latest/query/logcli/
commands = [
    "logcli-windows-amd64.exe  query \"{host=\\\"127.0.0.1\\\"}\"  --org-id=tenant1 -o raw  --limit 1000  --since=8h"
]
# 日志查询结果列表,初始为空
raw_log = []

# 执行logQL查询命令,将结果保存在一个列表中
for cmd in commands:
    result = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,)
    # print(result.communicate()[0])
    result1 = str(result.communicate()[0], encoding='utf-8')

    # print(result1)

    result1_io = StringIO(result1)
    while True:
        line = result1_io.readline()
        if not line:
            break
        # print(line.strip())
        if line.startswith('timestamp='):
            raw_log = raw_log + [line.strip()]

print(raw_log)

运行结果:
运行结果

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐