loki: python3访问loki接口的例子

一,代码:

import requests

# loki的地址
loki_url="http://127.0.0.1:3100/loki/api/v1/query_range"

# 请求参数
query_params = {
    "query": "{job=\"devlogs\"} |= `dev.ERROR`",
    "start": "2024-11-04T00:00:00Z",
    "end": "2024-11-05T00:00:00Z",
    "limit": 1000
}

# 头信息
headers = {
    # 'X-Scope-OrgID': 'xxxxxxxxxxxxxxx'
    "Content-Type": "application/json"
}

# 发送GET请求到Loki服务器,并传递请求头
response = requests.get(loki_url, params=query_params, headers=headers)
print(response.status_code)

if response.status_code == 200:
    # 解析JSON响应
    data = response.json()

    # 提取日志数据
    logs = data['data']['result']
    lenNum = len(logs)
    print("lenNum:"+str(lenNum))
    #print(logs[0])
    #print()
    #print(logs[1])

    for result in logs:
        for value in result['values']:
            print(value)

    # 打印日志数据
    # print(df)
else:
    print('Error:', response.status_code)

二,说明

如果需要精确的时间,请使用unix时间戳

posted @ 2024-11-05 10:58  刘宏缔的架构森林  阅读(53)  评论(0编辑  收藏  举报