ToB企服应用市场:ToB评测及商务社交产业平台
标题:
利用 Prometheus 和 Grafana 监控 FastAPI 服务
[打印本页]
作者:
小秦哥
时间:
2024-8-10 20:26
标题:
利用 Prometheus 和 Grafana 监控 FastAPI 服务
在当代应用开辟中,监控和可视化服务的运行状态和性能指标对于保证系统稳定性至关重要。本文将介绍怎样利用 Prometheus 和 Grafana 对 FastAPI 服务进行监控和可视化,并展示怎样通过 prometheus_fastapi_instrumentator 将 FastAPI 应用与 Prometheus 集成。
1. 环境预备
首先,你需要预备以下环境:
Docker
: 用于快速部署 Prometheus 和 Grafana。
python
: 当地安装好python环境
2. 安装 Prometheus
创建 Prometheus 设置文件
在服务器上创建一个 prometheus.yml 文件,定义需要监控的目的:
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'fastapi_service'
static_configs:
- targets: ['localhost:8000'] # 替换为你的 FastAPI 服务地址和端口
复制代码
利用 Docker 运行 Prometheus
在服务器上执行以下命令启动 Prometheus:
docker run -d \
--name prometheus \
-p 9090:9090 \
-v /path/to/prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus
复制代码
-v /your_path/prometheus.yml:/etc/prometheus/prometheus.yml:将当地设置文件映射到容器内。
-p 9090:9090:将 Prometheus 的 9090 端口袒露出来。
访问 Prometheus
在浏览器中访问 http://<your-server-ip>:9090,确保 Prometheus 正常运行。
3. 安装 Grafana
利用 Docker 运行 Grafana
在服务器上执行以下命令启动 Grafana:
docker run -d \
--name=grafana \
-p 3000:3000 \
grafana/grafana
复制代码
-p 3000:3000:将 Grafana 的 3000 端口袒露出来。
访问 Grafana
在浏览器中访问 http://<your-server-ip>:3000,默认用户名为 admin,密码也是 admin。首次登录后,系统会提示你修改密码。
4. 设置 Prometheus 数据源
登录 Grafana 后,点击左侧菜单栏的 “Configuration” -> “Data Sources”。
点击 “Add data source”。
选择 “Prometheus”。
在 “URL” 栏中填入 http://<your-server-ip>:9090。
点击 “Save & Test” 确保设置乐成。
5. 集成 Prometheus 到 FastAPI
要将 Prometheus 与 FastAPI 集成,你可以利用 prometheus_fastapi_instrumentator 库。
安装 prometheus_fastapi_instrumentator
执行以下命令安装:
pip install prometheus-fastapi-instrumentator
复制代码
修改 FastAPI 应用
在你的 FastAPI 应用中,导入并利用 PrometheusInstrumentator:
from fastapi import FastAPI
from prometheus_fastapi_instrumentator import Instrumentator
app = FastAPI()
# 添加 Prometheus 监控
instrumentator = Instrumentator()
instrumentator.instrument(app).expose(app)
复制代码
验证指标端点
启动 FastAPI 应用,并访问 http://localhost:8000/metrics,确保 Prometheus 格式的指标数据正常展示。
6. 创建 Grafana 仪表盘
添加面板
点击左侧菜单栏的 “+” -> “Dashboard”。
点击 “Add new panel” 创建新的面板。
在 “Query” 部分选择 Prometheus 数据源,填写 PromQL 查询语句,比方 rate(http_requests_total[1m]) 用于监控 HTTP 哀求速率。
设置完毕后,点击 “Apply” 保存面板,一个监控哀求数的图表就做好了。
7. 设置告警
在 Prometheus 中定义告警规则并设置告警管理器(Alertmanager)来处置惩罚告警。
在 Grafana 中基于 Prometheus 的数据源设置告警阈值,并设置通知渠道(如邮件、Slack)。
总结
通过上述步调,你可以乐成实现 Prometheus 和 Grafana 的集成,对 FastAPI 服务进行全面的监控和可视化。Prometheus 负责采集和存储指标数据,Grafana 提供强大的可视化功能,当地搭建监控环境可以帮我们当地压测提供数据支撑。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4