通过一段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)
运行结果: