使用Python编写Prometheus监控的方法
要使用python编写Prometheus监控,需要你先开启Prometheus集群。可以参考//www.nhooo.com/article/148895.htm安装。在python中实现服务器端。在Prometheus中配置请求网址,Prometheus会定期向该网址发起申请获取你想要返回的数据。
使用Python和Flask编写Prometheus监控
Installation
pipinstallflask pipinstallprometheus_client
Metrics
Prometheus提供4种类型Metrics:Counter,Gauge,Summary和Histogram
Counter
Counter可以增长,并且在程序重启的时候会被重设为0,常被用于任务个数,总处理时间,错误个数等只增不减的指标。
importprometheus_client fromprometheus_clientimportCounter fromprometheus_client.coreimportCollectorRegistry fromflaskimportResponse,Flask app=Flask(__name__) requests_total=Counter("request_count","Totalrequestcoutofthehost") @app.route("/metrics") defrequests_count(): requests_total.inc() #requests_total.inc(2) returnResponse(prometheus_client.generate_latest(requests_total), mimetype="text/plain") @app.route('/') defindex(): requests_total.inc() return"HelloWorld" if__name__=="__main__": app.run(host="0.0.0.0")
运行该脚本,访问youhost:5000/metrics
#HELPrequest_countTotalrequestcoutofthehost #TYPErequest_countcounter request_count3.0
Gauge
Gauge与Counter类似,唯一不同的是Gauge数值可以减少,常被用于温度、利用率等指标。
importrandom importprometheus_client fromprometheus_clientimportGauge fromflaskimportResponse,Flask app=Flask(__name__) random_value=Gauge("random_value","Randomvalueoftherequest") @app.route("/metrics") defr_value(): random_value.set(random.randint(0,10)) returnResponse(prometheus_client.generate_latest(random_value), mimetype="text/plain") if__name__=="__main__": app.run(host="0.0.0.0")
运行该脚本,访问youhost:5000/metrics
#HELPrandom_valueRandomvalueoftherequest #TYPErandom_valuegauge random_value3.0
Summary/Histogram
Summary/Histogram概念比较复杂,一般exporter很难用到,暂且不说。
LABELS
使用labels来区分metric的特征
fromprometheus_clientimportCounter c=Counter('requests_total','HTTPrequeststotal',['method','clientip']) c.labels('get','127.0.0.1').inc() c.labels('post','192.168.0.1').inc(3) c.labels(method="get",clientip="192.168.0.1").inc()
使用Python和asyncio编写Prometheus监控
fromprometheus_clientimportCounter,Gauge fromprometheus_client.coreimportCollectorRegistry REGISTRY=CollectorRegistry(auto_describe=False) requests_total=Counter("request_count","Totalrequestcoutofthehost",registry=REGISTRY) random_value=Gauge("random_value","Randomvalueoftherequest",registry=REGISTRY)
importprometheus_client fromprometheus_clientimportCounter,Gauge fromprometheus_client.coreimportCollectorRegistry fromaiohttpimportweb importaiohttp importasyncio importuvloop importrandom,logging,time,datetime asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) routes=web.RouteTableDef() #metrics包含 requests_total=Counter("request_count","Totalrequestcoutofthehost")#数值只增 random_value=Gauge("random_value","Randomvalueoftherequest")#数值可大可小 @routes.get('/metrics') asyncdefmetrics(request): requests_total.inc()#计数器自增 #requests_total.inc(2) data=prometheus_client.generate_latest(requests_total) returnweb.Response(body=data,content_type="text/plain")#将计数器的值返回 @routes.get("/metrics2") asyncdefmetrics2(request): random_value.set(random.randint(0,10))#设置值任意值,但是一定要为整数或者浮点数 returnweb.Response(body=prometheus_client.generate_latest(random_value),content_type="text/plain")#将值返回 @routes.get('/') asyncdefhello(request): returnweb.Response(text="Hello,world") #使用labels来区分metric的特征 c=Counter('requests_total','HTTPrequeststotal',['method','clientip'])#添加lable的key, c.labels('get','127.0.0.1').inc()#为不同的label进行统计 c.labels('post','192.168.0.1').inc(3)#为不同的label进行统计 c.labels(method="get",clientip="192.168.0.1").inc()#为不同的label进行统计 g=Gauge('my_inprogress_requests','Descriptionofgauge',['mylabelname']) g.labels(mylabelname='str').set(3.6)#value自己定义,但是一定要为整数或者浮点数 if__name__=='__main__': logging.info('serverstart:%s'%datetime.datetime.now()) app=web.Application(client_max_size=int(2)*1024**2)#创建app,设置最大接收图片大小为2M app.add_routes(routes)#添加路由映射 web.run_app(app,host='0.0.0.0',port=2222)#启动app logging.info('serverclose:%s'%datetime.datetime.now())
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接