上一篇文章,講了通過(guò)textfile collector收集業(yè)務(wù)數(shù)據(jù),今天講用代碼方式實(shí)現(xiàn)(本文只寫(xiě)Python示例谨垃,其他語(yǔ)言見(jiàn)官方文檔)
先安裝Prometheus Python客戶端 pip install prometheus-client
Counter
counter(計(jì)數(shù)器)是一種只增不減(或者可以被重置為0)的數(shù)據(jù)類(lèi)型叠荠。
A counter is a cumulative metric that represents a single monotonically increasing counter whose value can only increase or be reset to zero on restart. For example, you can use a counter to represent the number of requests served, tasks completed, or errors. Do not use a counter to expose a value that can decrease.
例:基于fastapi記錄某個(gè)url的訪問(wèn)次數(shù),和發(fā)生異常的次數(shù)
from random import randint
from fastapi import FastAPI
from prometheus_client import make_asgi_app, Counter
import uvicorn
# Create app
app = FastAPI(debug=False)
# Add prometheus asgi middleware to route /metrics requests
metrics_app = make_asgi_app()
app.mount("/metrics", metrics_app)
# 訪問(wèn)量
c1 = Counter('pv', 'page view')
# 發(fā)生了多少次異常
c2 = Counter('exception', 'exception count')
# 發(fā)生了多少次ValueError異常
c3 = Counter('valueerror_exception', 'ValueError exception count')
@app.get("/")
@c2.count_exceptions()
def root():
c1.inc() # Increment by 1
# c1.inc(1.6) # Increment by given value
# c1.reset() # reset to zero
with c3.count_exceptions(ValueError):
random_num = randint(1, 100)
if random_num % 2 == 0:
raise ValueError
if random_num % 3 == 0:
raise ZeroDivisionError
return {"Hello": "World"}
if __name__ == '__main__':
uvicorn.run(app, host="0.0.0.0", port=8000)
運(yùn)行程序龄章,多次訪問(wèn)Ip:8000制造一些數(shù)據(jù),訪問(wèn) ip:8000/metrics 就能看見(jiàn)上面代碼的結(jié)果:總共訪問(wèn)了31次襟诸,發(fā)生了22次異常瓦堵,其中有17次是ValueError異常
將其添加到Prometheus的target中(參考我之前的文章),然后用grafana顯示出來(lái):
Gauge
Gauge也是記錄單個(gè)數(shù)值的歌亲,和counter的區(qū)別是菇用,Gauge的數(shù)值可增可減
A gauge is a metric that represents a single numerical value that can arbitrarily go up and down.
例:記錄正在運(yùn)行的線程數(shù)量
from random import randint
import time
from concurrent.futures import ThreadPoolExecutor
from prometheus_client import start_http_server, Gauge
g = Gauge('my_inprogress_requests', 'Description of gauge')
# g.inc() # Increment by 1
# g.inc(6.6) # Increment by given value
# g.dec() # Decrement by 1
# g.dec(10) # Decrement by given value
# g.set(4.2) # Set to a given value
@g.track_inprogress() # Increment when entered, decrement when exited.
def process_request(t):
"""A dummy function that takes some time."""
time.sleep(t)
# with g.track_inprogress():
# pass
if __name__ == '__main__':
# Start up the server to expose the metrics.
start_http_server(8000)
with ThreadPoolExecutor(max_workers=60) as executor:
# 提交一些任務(wù)到線程池
for i in range(100):
executor.submit(process_request, randint(30, 40))
time.sleep(1)
time.sleep(60)
訪問(wèn) ip:8000/metrics 就能看見(jiàn)上面代碼的數(shù)據(jù):
運(yùn)行中的線程數(shù)量會(huì)從0逐步上升到max_workers然后穩(wěn)定一小下,最后下降到0陷揪,添加到grafana圖表展示:
Histogram
Histogram用于觀察數(shù)據(jù)的分布情況惋鸥。它可以自定義配置多個(gè)范圍的bucket,觀測(cè)的數(shù)據(jù)會(huì)落到屬于它范圍內(nèi)的bucket悍缠,然后prometheus會(huì)對(duì)桶里的數(shù)據(jù)進(jìn)行計(jì)數(shù)卦绣,同時(shí)還提供了所有觀測(cè)值的總和。
先看下圖的例子(接口響應(yīng)時(shí)間的統(tǒng)計(jì))飞蚓,然后我會(huì)對(duì)上面這段話進(jìn)行一一解釋:
- 指標(biāo)名稱是
request_latency_seconds
,此外Histogram類(lèi)型的指標(biāo)滤港,后面會(huì)自動(dòng)加上_bucket
,代表桶的范圍 - bucket 默認(rèn)的bucket范圍是
(.005, .01, .025, .05, .075, .1, .25, .5, .75, 1.0, 2.5, 5.0, 7.5, 10.0, INF)
(INF 是infinity 無(wú)窮大)。下圖的例子 我把范圍改成了(.5, 1.0, 1.5, 2.0, 2.5, 3.0)
趴拧,意思是 請(qǐng)求響應(yīng)時(shí)間在0.5秒內(nèi)溅漾、1秒內(nèi)、1.5秒內(nèi)……對(duì)應(yīng)指標(biāo)后面的le=
- 指標(biāo)名稱+
_count
代表所有的數(shù)據(jù)量(這個(gè)例子中著榴,代表接口調(diào)用的次數(shù)添履,100次) - 指標(biāo)名稱+
_sum
代表所有數(shù)據(jù)觀測(cè)值的和 (這個(gè)例子中,代表這100次請(qǐng)求中共花費(fèi)的時(shí)間)
對(duì)上圖整個(gè)例子進(jìn)行解釋就是:我發(fā)起了100次接口請(qǐng)求脑又,總共耗時(shí)156.038秒暮胧,這100次請(qǐng)求中锐借,有10次請(qǐng)求的響應(yīng)時(shí)間是在0.5秒內(nèi),有33次請(qǐng)求的響應(yīng)時(shí)間在1秒內(nèi)(包括了0.5秒內(nèi)的數(shù)量)往衷,有49次請(qǐng)求的響應(yīng)時(shí)間在1.5秒內(nèi)(包括了0.5秒內(nèi)和1秒內(nèi)的數(shù)量)……這就類(lèi)似于統(tǒng)計(jì)學(xué)中的分位值
上圖對(duì)應(yīng)的代碼:
from random import uniform
import time
from fastapi import FastAPI
import uvicorn
from prometheus_client import make_asgi_app, Histogram
h = Histogram('request_latency_seconds', 'Description of histogram', buckets=(.5, 1.0, 1.5, 2.0, 2.5, 3.0))
# h.observe(4.7) # Observe 4.7 (假設(shè) 這個(gè)請(qǐng)求耗時(shí) 4.7秒)
app = FastAPI(debug=False)
# Add prometheus asgi middleware to route /metrics requests
metrics_app = make_asgi_app()
app.mount("/metrics", metrics_app)
@app.get("/")
@h.time()
def root():
time.sleep(uniform(0, 3))
return {"Hello": "World"}
if __name__ == '__main__':
uvicorn.run(app, host="0.0.0.0", port=8000)
除此之外Histogram還可以使用histogram_quantile 計(jì)算分位值
例如計(jì)算80分位值 histogram_quantile(0.8, rate(request_latency_seconds_bucket[10m]))
結(jié)果是2.49 和上面/metrics
數(shù)據(jù)(le="2.5"
)是吻合的
添加到grafana 使用Heatmap圖表展示:(這個(gè)主題中钞翔,白色代表數(shù)值最大,越黑代表數(shù)值越小)
Summary
Summary和Histogram類(lèi)似席舍,只是沒(méi)有Histogram那么詳細(xì)的數(shù)據(jù)嗅战。Summary只有一個(gè)觀測(cè)值計(jì)數(shù)<basename>_count
和一個(gè)測(cè)值總和<basename>_sum
。如下圖
上圖對(duì)應(yīng)的代碼:
from random import uniform
import time
from fastapi import FastAPI
import uvicorn
from prometheus_client import make_asgi_app, Summary
s = Summary('request_latency_summary', 'Description of summary')
# s.observe(4.7) # Observe 4.7 (假設(shè) 這個(gè)請(qǐng)求耗時(shí) 4.7秒)
app = FastAPI(debug=False)
# Add prometheus asgi middleware to route /metrics requests
metrics_app = make_asgi_app()
app.mount("/metrics", metrics_app)
@app.get("/")
@s.time()
def root():
time.sleep(uniform(0, 3))
return {"Hello": "World"}
if __name__ == '__main__':
uvicorn.run(app, host="0.0.0.0", port=8000)
添加到grafana面板:
可以用 basename_sum / basename_count
粗略統(tǒng)計(jì)平均值
另外俺亮,本文用到的fastapi 只是為了方便闡述這幾種數(shù)據(jù)類(lèi)型,全是用的單進(jìn)程(官方給的多進(jìn)程例子疟呐,我沒(méi)跑起來(lái)脚曾,暫時(shí)沒(méi)深入研究)不適用于多進(jìn)程的生產(chǎn)環(huán)境,多進(jìn)程下可能用Pushgateway更合適启具。