flask编写prometheus采集指标脚本

import requests
from prometheus_client import Gauge,Counter, generate_latest
from prometheus_client.core import CollectorRegistry
from flask import Response, Flask
import json
import re


app = Flask(__name__)
# 实例化 REGISTRY
# 这里加了 labels,定义的 labels 一定要被用到,否则会报错
registry = CollectorRegistry(auto_describe=False)
nginx_status = Gauge("nginx_status","access_totol",['appid','apphost','env'],registry=registry)                      #现在这里定义多个指标,统一注册到register里面,后面直接返回register
#nginx_status:指标名称 access_totols指标的注释信息(必须的) []列表内是指标的标签
nginx_handle_access_tocal = Gauge("nginx_handle","nginx_handle_access_tocal",['appid','apphost','env'],registry=registry) url = "http://192.168.136.200/test_nginx_status" #r = requests.get(url,timeout=0.5) #str = r.text @app.route("/metrics") def requests_count(): r = requests.get(url,timeout=0.5) #为函数内置变量时,取的值是动态改变的,为全局变量时,取到的值是固定的 str = r.text list1 = str.splitlines(False)[0].split(':') list2 = str.splitlines(False)[1:3] int01 = list2[1].split(' ')[3] result1 = int(list1[1]) status1 = 'nginx01' status2 = 'nginx_handle02' status2 = 'handle01' nginx_status.labels(status1,"192.168.136.200","test").set(list1[1]) nginx_handle_access_tocal.labels(status2,"192.168.136.200","test").set(int01) return Response(generate_latest(registry),mimetype="text/plain") #所有注册的都在这里返回 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)

 

posted @ 2020-07-07 11:24  solomon123  阅读(708)  评论(0编辑  收藏  举报