[示例]使用python編寫prometheus_export
環(huán)境:
python3.7

import subprocess
import prometheus_client
import time
request_count = prometheus_client.Counter('request_count', "啟動后到現(xiàn)在收集了幾數(shù)據(jù)")
job_count = prometheus_client.Gauge("job_count", "統(tǒng)計數(shù)量", ["user_name"])
# 執(zhí)行命令
def popen(cmd):
? ?try:
? ? ? ?result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?encoding="utf-8", shell=True, )
? ? ? ?return result.stdout
? ?except Exception as e:
? ? ? ?print(e)
? ? ? ?# 返回-1時為出錯
? ? ? ?return -1
def process_request(sleepTime):
? ?request_count.inc() ?# 數(shù)值+1
? ?job_count.labels(user_name="root").set(11)
? ?job_count.labels(user_name="testuser").set(22)
? ?time.sleep(sleepTime) ?# 睡眠
if __name__ == '__main__':
? ?prometheus_client.start_http_server(8080)
? ?print("啟動完成")
? ?while True:
? ? ? ?process_request(2) ?# 兩秒一次收集一次數(shù)據(jù)
