要使用python編寫Prometheus監(jiān)控,需要你先開啟Prometheus集群。在python中實現(xiàn)服務(wù)器端。在Prometheus中配置請求網(wǎng)址,Prometheus會定期向該網(wǎng)址發(fā)起申請獲取你想要返回的數(shù)據(jù)。
使用Python和Flask編寫Prometheus監(jiān)控
Installation
pip install flaskpip install prometheus_client
Metrics
Prometheus提供4種類型Metrics:Counter, Gauge, Summary和Histogram
Counter
Counter可以增長,并且在程序重啟的時候會被重設(shè)為0,常被用于任務(wù)個數(shù),總處理時間,錯誤個數(shù)等只增不減的指標(biāo)。
import prometheus_clientfrom prometheus_client import Counterfrom prometheus_client.core import CollectorRegistryfrom flask import Response, Flaskapp = 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) 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")運行該腳本,訪問youhost:5000/metrics
# HELP request_count Total request cout of the host# TYPE request_count counterrequest_count 3.0
Gauge
Gauge與Counter類似,唯一不同的是Gauge數(shù)值可以減少,常被用于溫度、利用率等指標(biāo)。
import randomimport prometheus_clientfrom prometheus_client import Gaugefrom flask import Response, Flaskapp = Flask(__name__)random_value = Gauge("random_value", "Random value of the request")@app.route("/metrics")def r_value(): random_value.set(random.randint(0, 10)) return Response(prometheus_client.generate_latest(random_value), mimetype="text/plain")if __name__ == "__main__": app.run(host="0.0.0.0")運行該腳本,訪問youhost:5000/metrics
# HELP random_value Random value of the request# TYPE random_value gaugerandom_value 3.0
Summary/Histogram
Summary/Histogram概念比較復(fù)雜,一般exporter很難用到,暫且不說。
LABELS
使用labels來區(qū)分metric的特征
from prometheus_client import Counterc = Counter('requests_total', 'HTTP requests total', ['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監(jiān)控
from prometheus_client import Counter, Gaugefrom prometheus_client.core import CollectorRegistryREGISTRY = CollectorRegistry(auto_describe=False)requests_total = Counter("request_count", "Total request cout of the host", registry=REGISTRY)random_value = Gauge("random_value", "Random value of the request", registry=REGISTRY)import prometheus_clientfrom prometheus_client import Counter,Gaugefrom prometheus_client.core import CollectorRegistryfrom aiohttp import webimport aiohttpimport asyncioimport uvloopimport random,logging,time,datetimeasyncio.set_event_loop_policy(uvloop.EventLoopPolicy())routes = web.RouteTableDef()# metrics包含requests_total = Counter("request_count", "Total request cout of the host") # 數(shù)值只增random_value = Gauge("random_value", "Random value of the request") # 數(shù)值可大可小@routes.get('/metrics')async def metrics(request): requests_total.inc() # 計數(shù)器自增 # requests_total.inc(2) data = prometheus_client.generate_latest(requests_total) return web.Response(body = data,content_type="text/plain") # 將計數(shù)器的值返回@routes.get("/metrics2")async def metrics2(request): random_value.set(random.randint(0, 10)) # 設(shè)置值任意值,但是一定要為 整數(shù)或者浮點數(shù) return web.Response(body = prometheus_client.generate_latest(random_value),content_type="text/plain") # 將值返回@routes.get('/')async def hello(request): return web.Response(text="Hello, world")# 使用labels來區(qū)分metric的特征c = Counter('requests_total', 'HTTP requests total', ['method', 'clientip']) # 添加lable的key,c.labels('get', '127.0.0.1').inc() #為不同的label進行統(tǒng)計c.labels('post', '192.168.0.1').inc(3) #為不同的label進行統(tǒng)計c.labels(method="get", clientip="192.168.0.1").inc() #為不同的label進行統(tǒng)計g = Gauge('my_inprogress_requests', 'Description of gauge',['mylabelname'])g.labels(mylabelname='str').set(3.6) #value自己定義,但是一定要為 整數(shù)或者浮點數(shù)if __name__ == '__main__': logging.info('server start:%s'% datetime.datetime.now()) app = web.Application(client_max_size=int(2)*1024**2) # 創(chuàng)建app,設(shè)置最大接收圖片大小為2M app.add_routes(routes) # 添加路由映射 web.run_app(app,host='0.0.0.0',port=2222) # 啟動app logging.info('server close:%s'% datetime.datetime.now())總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對VEVB武林網(wǎng)的支持。
新聞熱點
疑難解答
圖片精選