Prometheus 4種數(shù)據(jù)類型和自定義監(jiān)控指標(biāo)

上一篇文章,講了通過textfile collector收集業(yè)務(wù)數(shù)據(jù),今天講用代碼方式實(shí)現(xiàn)(本文只寫Python示例,其他語言見官方文檔

先安裝Prometheus Python客戶端 pip install prometheus-client

Counter

counter(計(jì)數(shù)器)是一種只增不減(或者可以被重置為0)的數(shù)據(jù)類型。

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的訪問次數(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)

# 訪問量
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)行程序,多次訪問Ip:8000制造一些數(shù)據(jù),訪問 ip:8000/metrics 就能看見上面代碼的結(jié)果:總共訪問了31次,發(fā)生了22次異常,其中有17次是ValueError異常


將其添加到Prometheus的target中(參考我之前的文章),然后用grafana顯示出來:


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)

訪問 ip:8000/metrics 就能看見上面代碼的數(shù)據(jù):


運(yùn)行中的線程數(shù)量會(huì)從0逐步上升到max_workers然后穩(wěn)定一小下,最后下降到0,添加到grafana圖表展示:


Histogram

Histogram用于觀察數(shù)據(jù)的分布情況。它可以自定義配置多個(gè)范圍的bucket,觀測的數(shù)據(jù)會(huì)落到屬于它范圍內(nèi)的bucket,然后prometheus會(huì)對(duì)桶里的數(shù)據(jù)進(jìn)行計(jì)數(shù),同時(shí)還提供了所有觀測值的總和。

先看下圖的例子(接口響應(yīng)時(shí)間的統(tǒng)計(jì)),然后我會(huì)對(duì)上面這段話進(jìn)行一一解釋:


  • 指標(biāo)名稱是request_latency_seconds,此外Histogram類型的指標(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 無窮大)。下圖的例子 我把范圍改成了(.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ù)觀測值的和 (這個(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ù)量)……這就類似于統(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類似,只是沒有Histogram那么詳細(xì)的數(shù)據(jù)。Summary只有一個(gè)觀測值計(jì)數(shù)<basename>_count 和一個(gè)測值總和<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ù)類型,全是用的單進(jìn)程(官方給的多進(jìn)程例子,我沒跑起來,暫時(shí)沒深入研究)不適用于多進(jìn)程的生產(chǎn)環(huán)境,多進(jìn)程下可能用Pushgateway更合適。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容