python 通过prometheus remote write 写入指标数据

模块

使用python 模块:prometheus-writer,schedule

原始代码

import time
import schedule
from configparser import RawConfigParser
from prometheus.Writer import Cwriter
import requests
requests.packages.urllib3.disable_warnings()

def get_config():
    config = RawConfigParser()
    config.read("auth.ini", encoding='UTF8')
    http_type = config.get('prometheus', 'http_type')
    host = config.get('prometheus', "host")
    port = config.get('prometheus', "port")
    username = config.get('prometheus', "auth_username")
    password = config.get('prometheus', "auth_password")
    return http_type, host, port, username, password
Meta = {"ID":"11111","avali":"zonw1","name":"cccc"}
def generate_metrics():
    for num in range(1, 100):
        Meta["Hello"]=str(num)
        yield ("random_test", Meta, 2)


def send_metrics(http_type, host, port, username, password):
    url = f"{http_type}://{host}:{port}/api/v1/write"
    w = Cwriter(url, auth=(username, password), verify=False)
    metrics_generator = generate_metrics()
    try:
        w.writes(metrics_generator)
    except Exception as e:
        print(f"写入错误:{e}")

def main():
    http_type, host, port, username, password = get_config()
    if http_type == 'https':
        print(f"这是{http_type}协议")
        schedule.every(5).seconds.do(lambda: send_metrics(http_type, host, port, username, password))
    while True:
        schedule.run_pending()
        time.sleep(1)

if __name__ == "__main__":
    main()

认证文件:auth.ini内容

[prometheus]
http_type = https
host = 10.10.10.1
port = 9090
auth_username = admin
auth_password = admin

注意

prometheus需要开启远程接收参数

--enable-feature=remote-write-receiver

待测试

对接victoria-metrics和greptime时序存储。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值