1755 字
9 分钟
监控.ilikeyou
2026-02-01

前言#

最近接触了prometheus的metrics接口的编写(虽然写的是一个很简单的东西,调用一下接口拿到数据再加工一下就是了),就想着来复习并记录一下prometheus/grafana监控体系

prometheus 简单介绍#

Prometheus是一款时序(time series)数据库;可以使用PromQL表达式查询;但它的功能却并非止步于TSDB,而是一款设计用于进行目标(Target)监控的关键组件;结合生态系统内的其它组件,例如Pushgateway、Altermanager和Grafana等,可构成一个完整的IT监控系统。

一个标准的 Prometheus 系统包含以下部分:

  1. Prometheus Server (服务端):
    • 核心大脑。负责定时去抓取 (Scrape) 数据,存储数据,并响应查询请求。
  2. Exporters (导出器):
    • 关键组件! 因为很多软件(如 MySQL, Nginx, Linux 主机)本身不会暴露 Prometheus 格式的接口。
    • Exporter 是一个小插件,它负责从这些软件里拿数据,转换成 Prometheus 能懂的格式,暴露一个 /metrics 接口供 Server 抓取。
    • 常见 Exporter:node_exporter (监控主机), mysqld_exporter, redis_exporter,当然你也可以自己编写,暴露metrics接口即可。
  3. Pushgateway (推送网关):
    • 用于那些短生命周期的任务(比如一个脚本跑完就没了,Server 来不及抓)。脚本可以把数据推给 Pushgateway,然后 Server 再从网关里拉。
  4. Alertmanager (告警管理器):
    • Prometheus 只负责发现“出问题了”,具体的发送通知(发邮件、钉钉、微信、短信)是由 Alertmanager 负责的。
    • 它还负责告警降噪(比如 100 台机器同时挂,别发 100 条邮件,聚合成 1 条)。
  5. Grafana (可视化):
    • Prometheus 自带的网页界面很简陋。通常大家会搭配 Grafana,连接 Prometheus 数据源,画出炫酷的仪表盘 Dashboard。

下载#

下载可以跟着官方的看一下,我是docker部署的,简单方便注意一下配置就行

数据类型&时间序列数据#

类型英文名称变化特点典型应用场景常用 PromQL 函数
计数器Counter只增不减 (除非重启归零)请求总数、错误数、任务完成数rate(), increase()
仪表盘Gauge可增可减 (反映当前状态)CPU使用率、内存剩余、温度、当前连接数直接查询, avg(), delta()
直方图Histogram分桶统计 (服务端计算分布)请求耗时分布、数据包大小分布histogram_quantile()
摘要Summary分位数统计 (客户端计算)类似直方图,但直接在客户端算好分位数直接使用 (不支持跨实例聚合)

在 Prometheus 中,所有被采集的数据都以时间序列的形式存储。 一个时间序列由两部分唯一确定: 指标名称(Metric Name):表示被测量的特征(例如:http_requests_total)。 标签集合(Label Set):一组键值对(Key-Value pairs),用于区分该指标的不同维度(例如:{method=“POST”, handler=“/api/v1/login”, status=“200”})。

data

比如上图中的一些数据格式

PormQl#

PromQL (Prometheus Query Language) 是 Prometheus 的核心查询语言。它功能强大且灵活,专门用于从时间序列数据库中提取、聚合和分析监控数据,在grafana的面板也通过promql来查询并展示的

比如下面的几个例子

Terminal window
system_cpu_usage_percent # 展示当前 CPU 使用率
system_disk_bytes{type="free"} / 1024 / 1024 / 1024 # 将字节转换为更易读的 GB 单位
rate(system_network_bytes_total{direction="recv"}[1m]) # 用 rate() 函数瞬间将其转化为实时带宽

metrics接口编写#

这里就是我想要记录并分享的了,上面提到的数据都是外部接口提供的,然后prometheus自动拉取,下面我将展示一个简单的对外暴露代码

代码#

import psutil
import time
import threading
from flask import Flask, Response
from prometheus_client import generate_latest, CONTENT_TYPE_LATEST, Gauge
app = Flask(__name__)
# --- 1. 定义全局变量存储 CPU 数据 ---
# 初始化一个变量,默认 0.0
CURRENT_CPU_USAGE = 0.0
# --- 2. 定义指标 ---
cpu_usage_gauge = Gauge(
'my_app_cpu_usage_percent',
'Current CPU usage percentage of the application'
)
# --- 3. 后台任务:每秒更新一次 CPU 使用率 ---
def background_cpu_monitor():
global CURRENT_CPU_USAGE
while True:
CURRENT_CPU_USAGE = psutil.cpu_percent(interval=1)
cpu_usage_gauge.set(CURRENT_CPU_USAGE)
# --- 4. 启动后台线程 ---
# 设置为守护线程(daemon=True),这样主程序退出时它也会自动关闭
thread = threading.Thread(target=background_cpu_monitor, daemon=True)
thread.start()
# --- 5. 暴露 /metrics 接口 ---
@app.route('/metrics')
def metrics():
return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST)
# --- 6. 模拟业务接口 ---
@app.route('/')
def index():
return {"status": "running", "msg": "Check /metrics for real data"}
if __name__ == "__main__":
print("启动服务... 访问 http://127.0.0.1:5000/metrics")
app.run(host='127.0.0.1', port=5000, debug=False)

上面有数据的获取,封装,接口暴露三个部分

然后flask也有对应的扩展来帮助我们快速实现上面的部分

import psutil
import time
import threading
from flask import Flask
from prometheus_flask_exporter import PrometheusMetrics, Gauge
app = Flask(__name__)
# 1. 初始化扩展库
# 注意:这一步会自动注入默认的 Python/Process 指标,并自动注册 /metrics 路由
metrics = PrometheusMetrics(app)
# 2. 定义自定义指标
cpu_gauge = Gauge('cpu_usage_custom', 'Custom CPU Usage')
# 3. 定义后台更新函数
def update_cpu_loop():
while True:
cpu_percent = psutil.cpu_percent(interval=1)
# 更新指标
cpu_gauge.set(cpu_percent)
# 4. 启动后台线程
# 设置为守护线程 (daemon=True),这样主程序退出时,它也会自动关闭
thread = threading.Thread(target=update_cpu_loop, daemon=True)
thread.start()
# 5. 业务路由
@app.route('/')
def index():
return "Server is running. Check /metrics for data."
if __name__ == "__main__":
print("启动服务... 访问 http://127.0.0.1:5000/metrics")
app.run(port=5000)

启动#

首先需要下载对应的依赖
然后就可以直接启动并访问了

python app.py

在上面的接口信息里只有最后一条是我们监控的数据,其他的都是自动注入的 Python 内部运行数据

接入prometheus#

我的配置如下,注意下面的路径问题

docker-compose.yml

services:
prometheus:
image: prom/prometheus:latest
container_name: prometheus
restart: always
ports:
- 9090:9090
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--web.enable-lifecycle'

prometheus.yml

global:
scrape_interval: 15s # 全局抓取间隔
scrape_configs:
- job_name: "local_monitor"
static_configs:
- targets:
- "host.docker.internal:5000" # 目标地址
metrics_path: /metrics
scheme: http

然后登陆localhost:9090

记得要运行前面的python程序python app.py

点击status,然后在下拉栏点击target health就可以看到我们的python程序的数据了

使用pormql查询监控的cpu数据#

按下面的顺序点击或者输入就能看到监控的详情了

grafana面板#

grafana是一个功能强大的“数据仪表盘”或“控制面板”。它的核心作用是将来自不同数据源(如 Prometheus、MySQL、InfluxDB 等)的复杂数据,转化为直观、美观且易于理解的图表(如折线图、柱状图、仪表盘等)。

一个关键的特性是,Grafana 本身并不存储数据。它更像是一个查询和展示层,负责从你已有的数据库或监控系统中拉取数据,并将其漂亮地呈现出来。

在我们上面的查询显示的结果其实是有一点难看的,可以使用grafana来显示面板

结语#

上面展示了数据从产生到可视化的全过程,在实际中有许多的工具可以使用,比如数据的获取就有node expoter,监控告警有alert manager等等,本文更多的是展示一个完整的数据链流程

监控.ilikeyou
https://fuwari.vercel.app/posts/prometheus/监控/
作者
SiestaRem
发布于
2026-02-01
许可协议
CC BY-NC-SA 4.0