【踩坑记录】python-loki 日志查询

通过一段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)

运行结果:
运行结果

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值