metric_name裸指标名——选出该名称所有时间序列的即时向量。每个序列返回最近一个采样点。
up
node_cpu_seconds_total
http_requests_total
Prometheus 速查表,90+ 条目,覆盖 PromQL 选择器、聚合、函数、告警规则、录制规则、HTTP API 与 relabeling。
metric_name裸指标名——选出该名称所有时间序列的即时向量。每个序列返回最近一个采样点。
up
node_cpu_seconds_total
http_requests_total
metric{label="value"}精确标签等值匹配。把即时向量过滤到 `label` 等于 `value` 的序列。
⚠ 常见坑: 标签值区分大小写。`{job="API"}` 和 `{job="api"}` 是不同的序列。
up{job="prometheus"}http_requests_total{method="POST", status="200"}node_filesystem_avail_bytes{mountpoint="/"}metric{label!="value"}否定等值匹配。保留 `label` 不等于 `value` 的序列。标签不存在时也匹配。
up{job!="blackbox"}http_requests_total{env!="dev"}metric{label=~"regex"}RE2 正则匹配。匹配 `label` 符合正则的序列。正则自动在两端加锚点——`"5.."` 精确匹配三个字符。
⚠ 常见坑: 正则匹配会触发全索引扫描,比 `=` 慢。高基数标签尽量用精确匹配。
http_requests_total{status=~"5.."}node_cpu_seconds_total{mode=~"user|system"}up{instance=~"prod-.*:9090"}metric{label!~"regex"}否定正则匹配。保留 `label` 不符合正则的序列。
http_requests_total{env!~"dev|staging"}node_cpu_seconds_total{mode!~"idle|iowait"}metric[5m]范围向量选择器。返回每个序列过去 5 分钟内的所有样本。`rate()`、`increase()`、`delta()` 等范围函数必须接范围向量。
⚠ 常见坑: 范围向量不能直接画图,必须先传给 `rate()` 等函数处理。
rate(http_requests_total[5m])
increase(errors_total[1h])
delta(cpu_temp[10m])
metric offset 5moffset 修饰符。把查询时间往回移指定时长——读的是 5 分钟前的数据而不是当前。
http_requests_total offset 5m
rate(http_requests_total[5m] offset 1h)
# compare current vs one week ago: rate(requests[5m]) / rate(requests[5m] offset 7d)
metric @ 1609746000时间戳修饰符 (Prometheus ≥ 2.25)。在指定 Unix 时间戳处求值,与查询时间无关。
http_requests_total @ 1609746000
rate(http_requests_total[5m] @ start())
rate(http_requests_total[5m] @ end())
{__name__=~"go_.*"}用 `__name__` 当普通标签按名字模式选指标。适合探索性查询或跨指标操作。
⚠ 常见坑: 用 `__name__=~".*"` 一次选所有指标代价极高——务必缩小模式范围。
{__name__=~"go_.*", job="api"}{__name__=~"node_memory_.*"}metric{job="api", env="prod"}多个标签匹配器是 AND 关系。所有条件都满足才会选中这个序列。
up{job="api", env="prod", region="eu-west-1"}http_requests_total{method="GET", status=~"2..", handler!="/health"}rate(metric[1m])[10m:30s]子查询语法。以 `30s` 分辨率在过去 `10m` 内对内层表达式求值,返回范围向量。对范围表达式用 `_over_time` 函数时必须用子查询。
⚠ 常见坑: 子查询代价高,因为要多次求值内层表达式。高频使用的子查询应改用录制规则。
max_over_time(rate(http_requests_total[1m])[10m:30s])
avg_over_time(node_load1[1h:5m])
sum(metric)跨所有标签维度求和,返回单个标量结果。
⚠ 常见坑: 没有 `by` 子句时,`sum()` 会丢弃所有标签。结果没有任何可以 join 的标签。
sum(http_requests_total)
sum(rate(http_requests_total[5m]))
sum by (job) (metric)聚合时保留列出的标签,其余标签丢弃。等价于 SQL `GROUP BY job`。
sum by (job) (rate(http_requests_total[5m]))
max by (instance, device) (node_disk_read_bytes_total)
sum without (instance) (metric)聚合时丢弃列出的标签,保留其他所有标签。与 `by` 相反。
sum without (instance) (rate(http_requests_total[5m]))
avg without (cpu) (node_cpu_seconds_total)
avg(metric)跨所有序列或 `by`/`without` 定义的每个分组的算术平均值。
avg by (job) (rate(http_request_duration_seconds_sum[5m]) / rate(http_request_duration_seconds_count[5m]))
max(metric) / min(metric)所有匹配序列的最大值或最小值。适合集群级告警阈值。
max by (job) (rate(errors_total[5m]))
min(node_filesystem_avail_bytes / node_filesystem_size_bytes)
count(metric)统计结果向量里的序列数量。"当前有多少实例在运行"之类的查询很好用。
count(up{job="api"} == 1)count by (job) (up)
topk(5, metric)返回值最大的 K 个序列。找最活跃接口或最吵的实例特别好用。
⚠ 常见坑: `topk` 返回多个序列,不适合用在告警里(告警需要单一结果)。只用于仪表板。
topk(5, sum by (handler) (rate(http_requests_total[5m])))
topk(10, node_cpu_seconds_total{mode="user"})bottomk(3, metric)返回值最小的 K 个序列。找利用率最低的实例或响应最慢的目标很好用。
bottomk(3, sum by (instance) (rate(requests_total[5m])))
quantile(0.95, metric)跨所有序列值的 φ 分位数(不是跨时间)。这是跨序列聚合,不是跨样本。时间维度的百分位要用 `histogram_quantile()`。
⚠ 常见坑: 不要和 `histogram_quantile()` 混淆。这个是跨实例当前值的分位数,不是跨分布的。
quantile(0.95, rate(http_request_duration_seconds_sum[5m]))
count_values("label", metric)按序列的值计数,创建一个新标签存该值。统计各版本号有多少实例时很有用。
count_values("version", kube_pod_container_info)count_values("status_code", http_response_code)stddev(metric) / stdvar(metric)跨所有序列的标准差或方差。检测集群中异常实例时很有用。
stddev by (job) (rate(http_request_duration_seconds_sum[5m]))
rate(counter[5m])在范围窗口内用线性回归算出的每秒平均增速。仪表板和计数器告警的标准函数。
⚠ 常见坑: 范围窗口应至少是抓取间隔的 4 倍。15s 抓取间隔至少用 `[1m]`,更短会很嘈杂。
rate(http_requests_total[5m])
rate(node_network_receive_bytes_total[5m])
sum by (job) (rate(http_requests_total{status=~"5.."}[5m]))irate(counter[5m])瞬时速率——只用最后两个数据点计算。能捕获 `rate()` 会平均掉的极短尖峰。
⚠ 常见坑: 一次抓取延迟就会在图上制造假尖峰。不要用在仪表板里,只用于排查正在发生的尖峰。
irate(http_requests_total[1m])
increase(counter[1h])计数器在范围窗口内的总增量。等价于 `rate(c[window]) * 窗口秒数`。会正确处理计数器重置。
increase(http_requests_total[1h])
increase(errors_total{job="api"}[24h])resets(counter[1h])范围窗口内计数器重置的次数。重置意味着计数器从高值跌回零(通常是进程重启)。
resets(http_requests_total[1h])
# alert if more than 3 restarts in an hour: resets(process_start_time_seconds[1h]) > 3
delta(gauge[1h])范围窗口内首末样本的差值。作用于 Gauge,不适用于 Counter。
⚠ 常见坑: 不要对 Counter 用 `delta()`——Counter 会重置,`delta()` 不处理重置。Counter 用 `increase()`。
delta(node_memory_MemFree_bytes[1h])
delta(cpu_temp_celsius[10m])
predict_linear(gauge[1h], 3600)用范围窗口的线性回归预测 `3600` 秒后的值。"磁盘还有 X 小时满" 的告警必备。
# alert: disk full in 4 hours predict_linear(node_filesystem_free_bytes[1h], 4 * 3600) < 0
predict_linear(node_memory_MemAvailable_bytes[30m], 3600)
changes(gauge[1h])范围窗口内值发生变化的次数。检测服务状态抖动或配置变更很有用。
changes(up[1h]) > 5 # service is flapping
changes(kube_deployment_spec_replicas[1h])
histogram_quantile(0.95, sum(rate(h_bucket[5m])) by (le))从 Histogram 指标计算 φ 分位数(0.95 = P95)。`le` 标签标记桶边界,聚合时必须保留。
⚠ 常见坑: `by (le)` 是必须的——省略会丢掉桶标签,函数返回 NaN。
histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))
histogram_quantile(0.99, sum by (le, job) (rate(grpc_server_handling_seconds_bucket[5m])))
absent(metric)表达式有样本时返回空向量;没有样本时返回单元素向量(值为 1)。用于指标消失时告警。
⚠ 常见坑: `absent()` 不会继承消失序列的标签。重要标签要硬写进告警的 `labels:` 块。
absent(up{job="api"} == 1)absent(http_requests_total{env="prod"})absent_over_time(metric[5m])类似 `absent()`,但要求指标连续缺失整个范围窗口才返回 1。避免因单次抓取缺失就告警。
absent_over_time(up{job="api"}[5m])label_replace(m, "dst", "$1", "src", "(.*)")对标签做正则替换后写入新标签。`$1` 引用正则的第一个捕获组。
# extract "host" from "host:port" in instance label: label_replace(up, "host", "$1", "instance", "([^:]+):.*")
label_replace(metric, "short_name", "$1", "handler", "/api/v[0-9]+/(.*)")
label_join(m, "new", ",", "l1", "l2")用分隔符连接多个已有标签值,写入新标签。
label_join(up, "node_region", "/", "instance", "region")
abs() / ceil() / floor() / round(m, 0.5)绝对值、向上取整、向下取整、四舍五入到最近倍数。逐元素作用于每个序列值。
abs(node_filesystem_avail_bytes - node_filesystem_size_bytes / 2)
round(rate(http_requests_total[5m]) * 100, 0.01)
clamp(m, 0, 100) / clamp_min / clamp_max把所有值夹到 [min, max] 范围内。`clamp_min(m, 0)` 强制值 ≥ 0;`clamp_max(m, 100)` 强制值 ≤ 100。
clamp(some_ratio, 0, 1)
clamp_min(node_load1 - 1, 0) # never negative
sort(m) / sort_desc(m)对结果向量按值排序(升序或降序)。仪表板里把最差的始终排到最前面很有用。
sort_desc(rate(http_requests_total[5m]))
sort(node_filesystem_avail_bytes)
time() / timestamp(m)`time()` 返回当前求值时间戳(标量)。`timestamp(v)` 返回向量里每个样本的时间戳。
# age of the most recent sample in seconds:
time() - timestamp(up{job="api"})# alert: sample is stale (older than 5 min): time() - timestamp(up) > 300
hour() / minute() / day_of_week() / month()基于时间的函数。`hour()` 返回 UTC 0-23;`day_of_week()` 返回 0 (周日) 到 6;`month()` 返回 1-12。业务时间抑制条件必备。
# only alert on business hours UTC+8: hour() >= 1 and hour() < 10 # 9am-6pm CST
day_of_week() != 0 and day_of_week() != 6 # not weekends
sum_over_time(m[1h]) / avg_over_time / max_over_time在范围窗口内对 Gauge 做时间维度聚合。`sum_over_time` 求和;`avg_over_time` 取均值;`max_over_time` 取峰值。
avg_over_time(node_load1[1h])
max_over_time(go_goroutines[30m])
quantile_over_time(0.95, http_response_time_seconds[1h])
m1 + m2 / m1 - m2 / m1 * scalar算术算子:`+` `-` `*` `/` `%` `^`。两个即时向量运算时,标签集必须完全匹配(除 `__name__`)。
⚠ 常见坑: 两个向量运算要求标签完全匹配。用 `on()` 或 `ignoring()` 控制匹配方式。
# error ratio: rate(errors_total[5m]) / rate(requests_total[5m])
# bytes to megabytes: node_memory_MemAvailable_bytes / 1024 / 1024
# percentage used: 1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)
m1 > bool m2比较算子:`==` `!=` `>` `<` `>=` `<=`。不加 `bool` 时过滤序列(不匹配的序列被丢弃);加 `bool` 时转换为 0/1。
# filter: only series where value > 0.9: rate(errors_total[5m]) / rate(requests_total[5m]) > 0.9
# convert to 0/1 for arithmetic: (up == bool 1) * 100
m1 and m2集合交集。返回 m1 中在 m2 里有匹配标签集的序列。不合并值——只用 m1 的值。
# only show CPU metrics for up instances: node_cpu_seconds_total and on(instance) up == 1
m1 or m2集合并集。返回 m1 的所有序列,加上 m2 中在 m1 里没有匹配标签集的序列。
# combine metrics from two jobs when one may be absent:
metric{job="a"} or metric{job="b"}m1 unless m2集合差集。返回 m1 中在 m2 里没有匹配标签集的序列。
# exclude maintenance windows: rate(errors_total[5m]) unless on(instance) maintenance_mode == 1
m1 * on(instance) m2`on()` 把向量匹配限制到指定的标签集。配对样本时忽略其他所有标签。
# join error rate with instance metadata: rate(errors_total[5m]) * on(instance) group_left(version) app_info
m1 * ignoring(env) m2`ignoring()` 从匹配键中排除列出的标签。当序列只在一个不应影响配对的标签上不同时使用。
requests_total * ignoring(status) error_total
m1 * on(instance) group_left(version) m2`group_left()` 允许多对一匹配:左侧多个序列可以匹配右侧一个序列。括号内的标签从右侧复制过来。
⚠ 常见坑: 不加 `group_left` 或 `group_right` 时,多对一匹配会报错:"multiple matches for labels"。
# enrich metrics with build version from info metric: rate(http_requests_total[5m]) * on(instance) group_left(version) app_build_info
scalar(m) / vector(s)`scalar(v)` 把单元素向量转成标量值。`vector(s)` 把标量转成无标签的单元素向量。
# normalize by cluster total: rate(requests_total[5m]) / scalar(sum(rate(requests_total[5m])))
vector(1) # always returns 1 with no labels
Counter单调递增的值。始终用 `rate()` 或 `increase()`——原始值本身没有意义。后缀约定:`_total`。
⚠ 常见坑: 永远不要对 Counter 用 `delta()` 或 Gauge 类函数——它们不能正确处理计数器重置。
# good: rate(http_requests_total[5m])
# bad (raw counter value): http_requests_total # only useful at a fixed moment in time
Gauge可以升降的值:内存用量、温度、队列长度、goroutine 数。直接使用或配合 `delta()`、`avg_over_time()`、`predict_linear()`。
node_memory_MemAvailable_bytes # current free memory
avg_over_time(go_goroutines[5m]) # average over window
predict_linear(node_filesystem_free_bytes[1h], 4 * 3600) # forecast
Histogram按配置好的桶对观测值计数。每个基础名称暴露三类序列:`_bucket{le="..."}`、`_count`、`_sum`。用 `histogram_quantile()` 计算百分位。
⚠ 常见坑: 桶边界要在埋点时配置好。如果 P99 总是打到最高桶,说明需要配更大的桶上限。
histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))
# request rate via histogram count: rate(http_request_duration_seconds_count[5m])
Summary在客户端预先计算分位数。暴露 `_count`、`_sum` 和 `{quantile="0.99"}` 标签对。不能跨实例聚合。
⚠ 常见坑: 永远不要跨实例 `sum()` Summary 的分位数序列——对预计算分位数求和在数学上是错误的。需要聚合时用 Histogram。
# correct: per-instance summary:
go_gc_duration_seconds{quantile="0.99"}# wrong:
sum by (job) (go_gc_duration_seconds{quantile="0.99"}) # DO NOT DO THISNaming conventions指标名用 snake_case。后缀约定:`_total`(计数器)、`_seconds`(时长)、`_bytes`(大小)、`_ratio`(0-1 比例)、`_info`(元数据 Gauge,值恒为 1)。
http_requests_total # counter
http_request_duration_seconds # histogram or summary
process_resident_memory_bytes # gauge
app_build_info{version="1.2"} # metadata info gaugeAlert rule YAML structure写在规则文件 `groups` 块下的完整 Prometheus 告警规则。`expr` 字段在每个 `evaluation_interval` 时被求值。
groups:
- name: example
rules:
- alert: HighErrorRate
expr: |
sum(rate(http_requests_total{status=~"5.."}[5m]))
/ sum(rate(http_requests_total[5m])) > 0.05
for: 5m
labels:
severity: critical
annotations:
summary: "High error rate on {{ $labels.job }}"
description: "Error rate is {{ $value | humanizePercentage }}"for: 5m (pending state)`for` 子句让告警在条件持续满足指定时长后才从 PENDING 转为 FIRING。避免因短暂尖峰触发告警。
⚠ 常见坑: 不写 `for` 时,条件一满足就立刻触发告警。除非是最紧急的"即时"告警,否则始终加 `for`。
for: 5m # must be true for 5 minutes
for: 0m # fire immediately (no pending)
for: 1h # sustained disk pressure
labels: { severity: critical }该规则的每条告警都会加上的静态标签。Alertmanager 路由用这些标签决定发给谁。标签值可以用 Go 模板语法。
labels: severity: critical team: platform runbook_url: "https://wiki.example.com/runbooks/high-error-rate"
{{ $labels.instance }} / {{ $value | humanize }}告警 annotations 中的 Go 模板语法。`$labels` 访问告警的标签集;`$value` 是当前表达式的值。Prometheus 内置模板函数:`humanize`、`humanizePercentage`、`humanizeDuration`、`title`、`toUpper`。
annotations:
summary: "Instance {{ $labels.instance }} is down"
description: >
Error rate is {{ $value | humanizePercentage }}
(threshold: 5%). Job: {{ $labels.job }}.Multi-window alert (burn rate)Google SRE 消耗率模式:结合短窗口(快、灵敏)和长窗口(慢、持续),在快速发现真实故障的同时减少误报。
- alert: HighErrorBurnRate
expr: |
(
rate(http_requests_total{status=~"5.."}[1h])
/ rate(http_requests_total[1h]) > 0.02
) and (
rate(http_requests_total{status=~"5.."}[5m])
/ rate(http_requests_total[5m]) > 0.02
)
for: 2mALERTS{alertname="X", alertstate="firing"}Prometheus 会为每条活跃告警合成 `ALERTS` 指标。用它查告警状态、构建告警叠加规则、或与其他指标 join。
ALERTS{job="api", alertstate="firing"}# how many alerts are currently firing:
count(ALERTS{alertstate="firing"})Inhibit rule (Alertmanager)Alertmanager 的 inhibit 规则在另一条告警激活时抑制某些告警。例如:节点整体宕机时抑制该节点上所有服务告警。
inhibit_rules:
- source_match:
alertname: NodeDown
target_match_re:
alertname: ".*"
equal:
- instanceRecording rule YAML structure录制规则预先计算昂贵的表达式并存为新指标。和告警规则写在同一个 `rules:` 块下,在 `groups` 键下面。
groups:
- name: request_rates
interval: 1m # optional: override global evaluation_interval
rules:
- record: job:http_requests:rate5m
expr: sum by (job) (rate(http_requests_total[5m]))level:metric:operations (naming convention)`level` = 聚合维度(job、instance、cluster);`metric` = 去掉 `_total`/`_seconds` 后的基础指标名;`operations` = 从左到右冒号分隔的 PromQL 操作。
job:http_requests:rate5m # per-job rate over 5m
cluster:http_requests:rate5m_sum # cluster-level sum
instance:node_cpu:rate5m # per-instance CPU rate
job:http_request_duration_seconds:p95_5m # P95 latency
When to create recording rules以下情况创建录制规则:(1) 求值超过 1 秒的查询;(2) 对大量序列做 `rate + sum`(代价高);(3) 仪表板和告警都用的表达式;(4) 反复求值的子查询。
# before (in every dashboard panel and alert): histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, job)) # after (one recording rule, referenced everywhere): job:http_request_duration_seconds:p95_5m
Rule file reload不重启 Prometheus 即可重载规则文件:发送 SIGHUP、调用 `POST /-/reload`,或先用 `promtool check rules file.yml` 验证。
kill -HUP <prometheus_pid>
curl -X POST http://localhost:9090/-/reload
promtool check rules /etc/prometheus/rules/*.yml
GET /api/v1/query即时查询。在单个时间点对 PromQL 表达式求值。参数:`query`(必填)、`time`(Unix 或 RFC3339,默认当前时间)、`timeout`。
curl "http://localhost:9090/api/v1/query?query=up&time=2024-01-01T00:00:00Z"
curl -G --data-urlencode 'query=rate(http_requests_total[5m])' http://localhost:9090/api/v1/query
GET /api/v1/query_range范围查询。在时间范围内对表达式求值,返回矩阵。参数:`query`、`start`、`end`(Unix 或 RFC3339)、`step`(时长或秒数)。
curl "http://localhost:9090/api/v1/query_range?query=up&start=2024-01-01T00:00:00Z&end=2024-01-01T01:00:00Z&step=60"
GET /api/v1/series返回匹配一个或多个选择器的所有序列。参数:`match[]`(一个或多个选择器表达式)、`start`、`end`。
curl "http://localhost:9090/api/v1/series?match[]=http_requests_total&match[]=up"
GET /api/v1/label/<name>/values列出给定标签名在所有时间序列中的所有已知值。构建动态仪表板和自动补全时很有用。
curl http://localhost:9090/api/v1/label/job/values
curl http://localhost:9090/api/v1/label/instance/values
GET /api/v1/targets返回所有当前抓取目标的信息:健康状态、标签、最后抓取时间和最后一次错误。用 `state=active|dropped|any` 过滤。
curl "http://localhost:9090/api/v1/targets?state=active"
GET /api/v1/rules返回所有已加载的告警规则和录制规则。用 `type=alert|record` 过滤。包含规则状态、最后求值时间和最后一次错误。
curl "http://localhost:9090/api/v1/rules?type=alert"
GET /api/v1/alerts返回当前所有活跃(pending 或 firing)告警。每条包含告警名、标签、状态、激活时间戳和当前值。
curl http://localhost:9090/api/v1/alerts
POST /api/v1/admin/tsdb/delete_series删除匹配选择器的所有序列数据。需要 `--web.enable-admin-api` 启动参数。下次压缩前不会释放磁盘空间。
⚠ 常见坑: 此 API 具有破坏性且不可逆。先用 `GET /api/v1/series` 确认要删的内容。
curl -X POST "http://localhost:9090/api/v1/admin/tsdb/delete_series?match[]=up{job=\"test\"}"GET /api/v1/metadata返回抓取目标注册的指标元数据(类型、帮助文本)。参数:`metric` 按名称过滤,`limit` 限制结果数量。
curl "http://localhost:9090/api/v1/metadata?metric=http_requests_total"
replace (default action)对 `source_labels` 拼接后的字符串(用 `separator` 连接)匹配 `regex`。匹配则把扩展后的 `replacement` 写入 `target_label`。
# extract hostname from "host:port" in __address__: - source_labels: [__address__] regex: "([^:]+)(:\d+)?" target_label: instance replacement: "$1"
keep只保留 `source_labels` 拼接后匹配 `regex` 的目标/序列。其他全部丢弃。
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape] action: keep regex: "true"
drop丢弃 `source_labels` 拼接后匹配 `regex` 的目标/序列。与 `keep` 相反。
- source_labels: [__meta_kubernetes_namespace] action: drop regex: "kube-system|monitoring"
labelmap把所有名称匹配 `regex` 的标签复制为新标签,用 `replacement` 替换标签名。推广 Kubernetes annotations/labels 时很好用。
# promote k8s labels to Prometheus labels: - action: labelmap regex: "__meta_kubernetes_pod_label_(.+)" replacement: "$1"
labeldrop / labelkeep`labeldrop` 删除名称匹配 `regex` 的所有标签。`labelkeep` 删除名称不匹配 `regex` 的所有标签。在 relabeling 之后应用。
⚠ 常见坑: 删太多标签可能导致指标碰撞——原本不同的两个序列失去区分标签后可能变成同一个。
# drop all labels starting with "tmp_": - action: labeldrop regex: "tmp_.*"
# keep only essential labels: - action: labelkeep regex: "job|instance|env"
hashmod对 `source_labels` 取哈希再取模,把结果写入 `target_label`。用于把抓取目标分片分配给多个 Prometheus 实例。
- source_labels: [__address__] modulus: 4 # 4 Prometheus shards target_label: __tmp_hash action: hashmod - source_labels: [__tmp_hash] regex: "0" # this shard handles only hash==0 targets action: keep
lowercase / uppercase`lowercase` 把 `source_labels` 转成小写写入 `target_label`。`uppercase` 反之。Prometheus ≥ 2.36 可用。
- source_labels: [__meta_kubernetes_pod_name] action: lowercase target_label: pod_name
Common pattern: port from __address__用 `replace` + 正则捕获组从 `__address__` 标签里提取主机或端口。在 Kubernetes 服务发现里非常常见。
# set the scrape port from an annotation: - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port] action: replace regex: "([^:]+)(?::\d+)?;(\d+)" replacement: "$1:$2" target_label: __address__
可搜索的 Prometheus 速查表,90+ 条目按九个分类整理。选择器: 即时向量 `metric{label="val"}`、范围向量 `metric[5m]`、标签匹配器 `=` `!=` `=~` `!~`、offset 修饰符、`@` 锚点、子查询语法。 聚合算子:`sum` `avg` `max` `min` `count` `topk` `bottomk` 配 `by`/`without`。 函数:`rate` `irate` `increase` 处理计数器;`delta` `predict_linear` 处理仪表盘;`histogram_quantile` 计算分位数;`label_replace` `label_join`; `absent` `absent_over_time`;`time()` `hour()` `day_of_week()`。 二元算子:算术 `+ - * / % ^`;比较含 `bool` 修饰符;集合算子 `and or unless`; 向量匹配 `on()` `ignoring()` `group_left()` `group_right()`。 指标类型:Counter、Gauge、Histogram、Summary 各自适用场景、 `_total` `_bucket` `_count` `_sum` 后缀约定、Summary 聚合踩坑。 告警规则:完整 YAML 结构、`for` 子句、Go 模板 `{{ $value | humanize }}`、多窗口消耗率模式、inhibit 规则。 录制规则:命名约定 `level:metric:operations`、何时预计算、规则重载。 HTTP API:`/api/v1/query`、`/api/v1/query_range`、序列/标签/target 端点。 Relabeling:`replace` `keep` `drop` `labelmap` `labeldrop` `hashmod`。 每条都有双语说明、可直接复制的例子和常见坑提醒。全浏览器运行。
把内容粘贴或拖入工具面板。
点击按钮,在浏览器内本地处理,文件不上传。
一键复制结果或下载到本地。
适合穿插在写代码、查问题、做 Review、上线前的小任务里。
这些入口会把当前任务接到更完整的工具链里。
凌晨三点告警打来,你打开速查表,拿到 `rate(http_requests_total{status=~"5.."}[5m])`,加上 `by (handler)` 找出最吵的接口,再用 `topk(5, …)` 列出前五名。 全靠记忆?不,靠复制粘贴,不到两分钟。
你想要一个对短暂中断敏感但不会因一次抓取抖动就打电话的告警。 你查到多窗口模式,复制带 `for: 5m` 的 `short_window` 和 `long_window` 表达式块填上指标名。annotations 那节直接告诉你 `{{ $labels.job }}` 和 `{{ $value | humanizePercentage }}` 怎么写, 不用猜语法。
仪表板上的 P95 延迟面板每次刷新要跑八秒,因为要对四百个序列 每次都算 `histogram_quantile(0.95, sum(rate(…)) by (le))`。 你查到录制规则命名约定,建出 `job:request_duration_seconds:p95_5m`, 把它同时用到仪表板和告警里。加载时间降到 200ms 以内。
在仪表板里用 `irate()`,它显示的瞬时尖峰看起来吓人,但大多数是抓取时间抖动,不是真信号。趋势图用 `rate()`。
`sum(rate(hist_bucket[5m]))` 传给 `histogram_quantile()` 之前没加 `by (le)`,`le` 标签必须在聚合后保留。
用 Summary 指标然后想跨实例聚合分位数,预先计算的分位数不可相加,只有 Histogram 的桶计数是可加的。
计数器名字忘写 `_total` 后缀,Prometheus 约定是 `http_requests_total`,不是 `http_requests`。
全部在你的浏览器里跑。速查表是内存里的静态数组,搜索框、分类胶囊 和复制按钮都不发任何网络请求。你打的字不会被记录,也不会写进 URL。 离网、公司代理后面、离网跳板机上都能用。
做你这行的人, 还会一起用这些。