prometheus自定义监控指标——实战

上一节介绍了pushgateway的做用、优劣以及部署使用,本机经过几个实例来重温一下自定义监控指标是如何使用的。python


1、监控容器启动时间(shell)linux

  使用prometheus已经两个月了,但从未找到容器运行时间的指标(有一个相似的指标是容器建立时间)。学会自定义监控指标后,第一个实例就应该来搞定它。web

  前提条件是,部署好pushagateway!docker

  在被监控机器上(linux),建立如下脚本shell

#!/bin/bash
  
allname=`docker ps --format "{{.Names}}"`              #获取全部运行的容器名称

function dockerruntime(){
    t=`docker inspect -f '{{.State.StartedAt}}' $1`          #获取各个容器的启动时间
    t1=`date +%s -d "$t"`                                    #将时间转成时间戳
    t2=`date +%s`                                            #获取当前时间的时间戳
    let tt=t2-t1                                             #计算运行时间
    echo $tt
}

sudo rm -f a
echo """# TYPE docker_runtime gauge
# HELP docker_runtime time sec""" >> a                       #将往pushgateway上传的数据写入a文件

for i in ${allname}
do
    t=`dockerruntime $i`
    echo "docker_runtime{name=\"$i\"} $t" >> a               #格式化写入数据  不能使用单引号  会屏蔽$i的
done

curl --data-binary "@a" http://pushgatewayIP:9091/metrics/job/docker_runtime/instance/xa-lsr-billubuntu       #修改地址和参数名向特定的url上传数据 数在a文件中

sudo rm -f a    #清空临时文件

  给该脚本加执行权限,执行后,登录pushgateway的webUIflask

能够看到被监控机器给pushgateway,PUSH了数据,意思是在被监控机器上搜索到了三个容器,每一个job的名称叫“docker_runtime”ubuntu

将该脚本加入周期性计划任务中,每分钟执行一次,若对时间有要求,能够将上述脚本稍加修改,每15s或30s执行一次。windows

此时在prometheus中的query的查询框中输入“docker_runtime”即可获取上述数据。bash

【注意】app

注意上传数据的类型

若是上传的数据类型是 UNTYPE 那么 prometheus将没法识别,致使整个pushgateway数据没法接受!所以须要格外关注发送的数据格式。
数据类型只有四种 counter gauge summary histogram

2、python向pushgateway发送数据

安装prometheus客户端

  pip install prometheus_client

一、counter类型

#counter是可增加的,重启时候会被置成0,用于任务个数,只增不减
#使用flask构建一个建议的网页

     import prometheus_client
	from prometheus_client import Counter
	from prometheus_client.core import CollectorRegistry
	from flask import Response, Flask
	
	app = Flask(__name__)
	
	requests_total = Counter("request_count", "Total request cout of the host")
	
	@app.route("/metrics")
	def requests_count():
	    requests_total.inc()
	    # requests_total.inc(2)	每一次刷新会增长2
	    return Response(prometheus_client.generate_latest(requests_total),
	                    mimetype="text/plain")
	
	@app.route('/')
	def index():
	    requests_total.inc()
	    return "Hello World"
	
	if __name__ == "__main__":
	    app.run(host="0.0.0.0")

结果: 

 

二、gauage类型

	import prometheus_client
	from prometheus_client import Counter,Gauge
	from prometheus_client.core import CollectorRegistry
	from flask import Response, Flask
	
	app = Flask(__name__)
	
	g = Gauge("random_value", "Random value of the request")
	
	@app.route("/metrics")
	def s():
	    with open("a.txt",'r') as f:
	        num=f.read()
	    g.set(num)
	    return Response(prometheus_client.generate_latest(g),
	                    mimetype="text/plain")
	
	
	@app.route('/')
	def index():
	    requests_total.inc()
	    return "Hello World"
	
	if __name__ == "__main__":
    app.run(host="0.0.0.0")

结果: 

 

以上做用是在本地生成一个小型网站,下一步是将选定的数据发送到pushgateway 

#在被监控机上写python代码
#CollectorRegistry能够同时注册多个自定义指标并返回给prometheus

	
importprometheus_client
fromprometheus_clientimportGauge
fromprometheus_client.coreimportCollectorRegistry
importrequests

defv1(): #获取监控数据的值
	return2.3

defv2():
	return3.60

n1=v1()
n2=v2()

REGISTRY=CollectorRegistry(auto_describe=False)
#自定义指标必须利用CollectorRegistry进行注册,注册后返回给prometheus
#CollectorRegistry必须提供register,一个指标收集器能够注册多个collectoryregistry


jin=Gauge("jin_kou","zhegezuoyongshijinkoudaxiao",["l1",'l2','instance'],registry=REGISTRY)
chu=Gauge("chu_kou","zhegezuoyongshichukoudaxiao",["l1",'l2','instance'],registry=REGISTRY)
	#“jin_kou” 指标名称
	# "zhegezuoyongshichukoudaxiao"  指标的注释信息
	# "[]"  定义标签的类别及个数

jin.labels(l1="label1",l2="label2",instance="windows1").inc(n1)
chu.labels(l1="label1",l2="label2",instance="windows1").inc(n2)
	#“[]”中有几个,就须要写几个个数要彻底一致

requests.post("http://pushgatewayIP:9091/metrics/job/python/",data=prometheus_client.generate_latest(REGISTRY))
	#向指定的API发送post信息,将注册的信息发过去
	#API中的 “python”是 job的名字

 结果:

相关文章
相关标签/搜索