模块
使用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时序存储。