Prometheus FastAPI Instrumentator 技术文档

Prometheus FastAPI Instrumentator 技术文档

prometheus-fastapi-instrumentator Instrument your FastAPI with Prometheus metrics. prometheus-fastapi-instrumentator 项目地址: https://gitcode.com/gh_mirrors/pr/prometheus-fastapi-instrumentator

Prometheus FastAPI Instrumentator 是一个专为 FastAPI 应用设计的可配置性仪表盘工具,它简化了将应用性能监控集成到Prometheus的过程。以下是详细的技术文档,涵盖安装、使用、API使用以及自定义配置。

安装指南

要开始使用 prometheus-fastapi-instrumentator,您需要通过Python包管理器pip进行安装。在终端运行以下命令:

pip install prometheus-fastapi-instrumentator

项目的使用说明

一旦安装完成,您可以开始集成Prometheus指标到您的FastAPI应用中。基本的使用流程包括导入Instrumentator类,然后对其应用和暴露指标。

快速上手

对于快速启动,只需简单地引入Instrumentator并在您的FastAPI应用上应用并暴露它:

from fastapi import FastAPI
from prometheus_fastapi_instrumentator import Instrumentator

app = FastAPI()

Instrumentator().instrument(app).expose(app)

如果您需要在应用启动事件中处理(例如异步应用),则可以这样操作:

@app.on_event("startup")
async def startup():
    instrumentator = Instrumentator().instrument(app)
    await instrumentator.expose(app)

默认情况下,这会为您提供一系列关键性能指标,包括请求总数、请求和响应大小的摘要、请求延迟的直方图等,并且自动对状态码进行了分组处理。

项目API使用文档

创建Instrumentator实例

创建时,可以通过参数高度定制行为,如忽略特定路由、环境变量控制开关等:

from prometheus_fastapi_instrumentator import Instrumentator, metrics

instrumentator = Instrumentator(
    should_group_status_codes=False,
    should_ignore_untemplated=True,
    should_respect_env_var='ENABLE_METRICS',
    # 更多自定义选项...
)

添加和创建指标

除了默认指标,还可以添加额外的指标或完全自定义指标。例如,增加自定义请求语言计数:

def http_requested_languages_total(info):
    # 自定义逻辑实现

instrumentator.add(http_requested_languages_total)

指定命名空间和子系统

为了更好的组织指标,可以在注册指标时指定命名空间和子系统:

instrumentator.instrument(app, namespace="myapp", subsystem="web")

显式暴露端点

如果您想要更细粒度地控制暴露指标的端点,可以直接调用:

instrumentator.expose(app, path="/metrics_custom")

结论

prometheus-fastapi-instrumentator 提供了一套强大而灵活的方法来集成Prometheus监控到您的FastAPI服务中,无论是通过预设的配置还是深度定制的解决方案,都能满足不同层次的监控需求。通过上述步骤,开发者能够轻松地获取到应用的性能数据,进而优化服务性能和稳定性。

prometheus-fastapi-instrumentator Instrument your FastAPI with Prometheus metrics. prometheus-fastapi-instrumentator 项目地址: https://gitcode.com/gh_mirrors/pr/prometheus-fastapi-instrumentator

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苗熠蔓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值