ToB企服应用市场:ToB评测及商务社交产业平台

标题: 利用 Prometheus 和 Grafana 监控 FastAPI 服务 [打印本页]

作者: 小秦哥    时间: 2024-8-10 20:26
标题: 利用 Prometheus 和 Grafana 监控 FastAPI 服务
在当代应用开辟中,监控和可视化服务的运行状态和性能指标对于保证系统稳定性至关重要。本文将介绍怎样利用 Prometheus 和 Grafana 对 FastAPI 服务进行监控和可视化,并展示怎样通过 prometheus_fastapi_instrumentator 将 FastAPI 应用与 Prometheus 集成。
1. 环境预备

首先,你需要预备以下环境:

2. 安装 Prometheus

创建 Prometheus 设置文件

在服务器上创建一个 prometheus.yml 文件,定义需要监控的目的:
  1. global:
  2.   scrape_interval: 15s
  3. scrape_configs:
  4.   - job_name: 'fastapi_service'
  5.     static_configs:
  6.       - targets: ['localhost:8000']  # 替换为你的 FastAPI 服务地址和端口
复制代码
利用 Docker 运行 Prometheus

在服务器上执行以下命令启动 Prometheus:
  1. docker run -d \
  2.   --name prometheus \
  3.   -p 9090:9090 \
  4.   -v /path/to/prometheus.yml:/etc/prometheus/prometheus.yml \
  5.   prom/prometheus
复制代码

访问 Prometheus

在浏览器中访问 http://<your-server-ip>:9090,确保 Prometheus 正常运行。
3. 安装 Grafana

利用 Docker 运行 Grafana

在服务器上执行以下命令启动 Grafana:
  1. docker run -d \
  2.   --name=grafana \
  3.   -p 3000:3000 \
  4.   grafana/grafana
复制代码

访问 Grafana

在浏览器中访问 http://<your-server-ip>:3000,默认用户名为 admin,密码也是 admin。首次登录后,系统会提示你修改密码。
4. 设置 Prometheus 数据源

5. 集成 Prometheus 到 FastAPI

要将 Prometheus 与 FastAPI 集成,你可以利用 prometheus_fastapi_instrumentator 库。
安装 prometheus_fastapi_instrumentator

执行以下命令安装:
  1. pip install prometheus-fastapi-instrumentator
复制代码
修改 FastAPI 应用

在你的 FastAPI 应用中,导入并利用 PrometheusInstrumentator:
  1. from fastapi import FastAPI
  2. from prometheus_fastapi_instrumentator import Instrumentator
  3. app = FastAPI()
  4. # 添加 Prometheus 监控
  5. instrumentator = Instrumentator()
  6. instrumentator.instrument(app).expose(app)
复制代码
验证指标端点

启动 FastAPI 应用,并访问 http://localhost:8000/metrics,确保 Prometheus 格式的指标数据正常展示。
6. 创建 Grafana 仪表盘

7. 设置告警


总结

通过上述步调,你可以乐成实现 Prometheus 和 Grafana 的集成,对 FastAPI 服务进行全面的监控和可视化。Prometheus 负责采集和存储指标数据,Grafana 提供强大的可视化功能,当地搭建监控环境可以帮我们当地压测提供数据支撑。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4