PromQL(Prometheus Query Language)是 Prometheus 监控系统中使用的一种查询语言。
它是一种专门设计用于从 Prometheus 时间序列数据库中提取、处理和分析监控数据的语言。PromQL 提供了强大的表达能力,可以对时间序列数据进行复杂的过滤、聚合和计算操作。
ps:PromQL 类似于 SQL 语言,但它是专门为时间序列数据设计的。
Prometheus 译名普罗米修斯
,是一个开源的监控和警报工具,用于收集、存储和分析时间序列数据。还有一个名为Thanos的扩展组件,中文译名 灭霸
🧐
PromQL 基础概念
数据类型
- 瞬时向量 (Instant Vector):某一时刻的指标快照(如
node_cpu_seconds_total
)
- 区间向量 (Range Vector):一段时间范围内的指标数据(如
node_cpu_seconds_total[5m]
)
- 标量 (Scalar):单一数值(如
count(node_cpu_seconds_total)
)
- 字符串 (String):字符串常量(日常使用较少)
时间序列选择器
瞬时向量选择器
匹配 job 为 api-server 且状态码非 4xx 的请求
1
| http_requests_total{job="api-server", status!~"4.."}
|
区间向量选择器
获取最近 5 分钟的数据点
过滤器运算符
运算符 |
说明 |
示例 |
= |
完全匹配 |
{status="500"} |
!= |
不等于 |
{method!="GET"} |
=~ |
正则匹配 |
{path=~"/api/.*"} |
!~ |
正则排除 |
{instance!~"10.0.0.1:.*"} |
核心操作符
算术运算符
计算内存空闲百分比
1
| node_memory_free_bytes / node_memory_total_bytes * 100
|
比较运算符
筛选请求量超过 1000 的序列
1
| http_requests_total > 1000
|
聚合运算符
按服务维度聚合总请求量
1
| sum(http_requests_total) by (service)
|
逻辑运算符
实例宕机或磁盘将在1小时内写满
1
| up == 0 or predict_linear(node_filesystem_free_bytes[1h], 3600) < 0
|
常用函数
函数 |
说明 |
示例 |
rate() |
计算每秒增长率 |
rate(http_requests_total[5m]) |
increase() |
计算区间增长量 |
increase(node_network_bytes[1h]) |
sum_over_time() |
区间内数值求和 |
sum_over_time(log_entries[24h]) |
histogram_quantile() |
计算分位数 |
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m])) |
label_replace() |
动态修改标签 |
label_replace(up, "new_label", "$1", "instance", "(.*):.*") |
实际应用示例
匹配指标名称
匹配所有具有非空指标名称的时间序列:
基于这行命令,我们可以得到:
{__name__=~"http_.*"}
:匹配以 http_ 开头的指标
{__name__=~"node_.*"}
:匹配以 node_ 开头的指标
{__name__=~".+"} and {endpoint="https"}
:匹配所有具有非空指标名称且端点为HTTPS的时间序列
再进一步,我们可以使用 !=
来排除某些指标,例如:
1
| {__name__=~"http_.*"} != {__name__="http_requests_total"}
|
错误率计算
1 2 3 4
| (sum(rate(http_requests_total{status=~"5.."}[5m])) / (sum(rate(http_requests_total[5m]))) * 100 # 计算 5xx 错误率百分比
|
预测磁盘写满时间
预测 1 小时后磁盘是否写满
1
| predict_linear(node_filesystem_free_bytes[1h], 3600) < 0
|
CPU 使用率
1
| 100 - (avg by (instance)(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
|
调试技巧
- 快速验证指标存在性
1 2
| count(up) # 返回监控目标数量 count(up == 1) # 筛选出所有在线的设备
|
- 查看最新数据点
查看 1 分钟前的数据
1
| http_requests_total offset 1m
|
- 多条件组合查询
联查生产环境非 Redis 容器内存
1 2 3
| {__name__=~"node_.*", environment="prod"} and ON (instance) container_memory_usage_bytes{image!~"redis.*"}
|
未完待续~~