loki: python3訪問loki介面的例子

刘宏缔的架构森林發表於2024-11-05

一,程式碼:

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)

相關文章