上一篇文章,讲了通过textfile collector收集业务数据,今天讲用代码方式实现(本文只写Python示例,其他语言见官方文档)
先安装Prometheus Python客户端 pip install prometheus-client
Counter
counter(计数器)是一种只增不减(或者可以被重置为0)的数据类型。
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记录某个url的访问次数,和发生异常的次数
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')
# 发生了多少次异常
c2 = Counter('exception', 'exception count')
# 发生了多少次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)
运行程序,多次访问Ip:8000制造一些数据,访问 ip:8000/metrics 就能看见上面代码的结果:总共访问了31次,发生了22次异常,其中有17次是ValueError异常
将其添加到Prometheus的target中(参考我之前的文章),然后用grafana显示出来:
Gauge
Gauge也是记录单个数值的,和counter的区别是,Gauge的数值可增可减
A gauge is a metric that represents a single numerical value that can arbitrarily go up and down.
例:记录正在运行的线程数量
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:
# 提交一些任务到线程池
for i in range(100):
executor.submit(process_request, randint(30, 40))
time.sleep(1)
time.sleep(60)
访问 ip:8000/metrics 就能看见上面代码的数据:
运行中的线程数量会从0逐步上升到max_workers然后稳定一小下,最后下降到0,添加到grafana图表展示:
Histogram
Histogram用于观察数据的分布情况。它可以自定义配置多个范围的bucket,观测的数据会落到属于它范围内的bucket,然后prometheus会对桶里的数据进行计数,同时还提供了所有观测值的总和。
先看下图的例子(接口响应时间的统计),然后我会对上面这段话进行一一解释:
- 指标名称是
request_latency_seconds
,此外Histogram类型的指标,后面会自动加上_bucket
,代表桶的范围 - bucket 默认的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)
,意思是 请求响应时间在0.5秒内、1秒内、1.5秒内……对应指标后面的le=
- 指标名称+
_count
代表所有的数据量(这个例子中,代表接口调用的次数,100次) - 指标名称+
_sum
代表所有数据观测值的和 (这个例子中,代表这100次请求中共花费的时间)
对上图整个例子进行解释就是:我发起了100次接口请求,总共耗时156.038秒,这100次请求中,有10次请求的响应时间是在0.5秒内,有33次请求的响应时间在1秒内(包括了0.5秒内的数量),有49次请求的响应时间在1.5秒内(包括了0.5秒内和1秒内的数量)……这就类似于统计学中的分位值
上图对应的代码:
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 (假设 这个请求耗时 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 计算分位值
例如计算80分位值 histogram_quantile(0.8, rate(request_latency_seconds_bucket[10m]))
结果是2.49 和上面/metrics
数据(le="2.5"
)是吻合的
添加到grafana 使用Heatmap图表展示:(这个主题中,白色代表数值最大,越黑代表数值越小)
Summary
Summary和Histogram类似,只是没有Histogram那么详细的数据。Summary只有一个观测值计数<basename>_count
和一个测值总和<basename>_sum
。如下图
上图对应的代码:
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 (假设 这个请求耗时 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
粗略统计平均值
另外,本文用到的fastapi 只是为了方便阐述这几种数据类型,全是用的单进程(官方给的多进程例子,我没跑起来,暂时没深入研究)不适用于多进程的生产环境,多进程下可能用Pushgateway更合适。