Prometheus 4种数据类型和自定义监控指标

时间:2024-10-07 17:49:29

上一篇文章,讲了通过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