prometheus自定義監控指標——實戰


上一節介紹了pushgateway的作用、優劣以及部署使用,本機通過幾個實例來重溫一下自定義監控指標是如何使用的。


一、監控容器啟動時間(shell)

  使用prometheus已經兩個月了,但從未找到容器運行時間的指標(有一個類似的指標是容器創建時間)。學會自定義監控指標后,第一個實例就應該來搞定它。

  前提條件是,部署好pushagateway!

  在被監控機器上(linux),創建以下腳本

#!/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的webUI

可以看到被監控機器給pushgateway,PUSH了數據,意思是在被監控機器上搜索到了三個容器,每個job的名稱叫“docker_runtime”

將該腳本加入周期性計划任務中,每分鍾執行一次,若對時間有要求,可以將上述腳本稍加修改,每15s或30s執行一次。

此時在prometheus中的query的查詢框中輸入“docker_runtime”便可獲取上述數據。

【注意】

注意上傳數據的類型

如果上傳的數據類型是 UNTYPE 那么 prometheus將無法識別,導致整個pushgateway數據無法接受!因此需要格外關注發送的數據格式。
數據類型只有四種 counter gauge summary histogram

二、python向pushgateway發送數據

安裝prometheus客戶端

  pip install prometheus_client

1、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")

結果: 

 

2、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的名字

 結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM