312 lines
25 KiB
HTML
312 lines
25 KiB
HTML
|
|
<!DOCTYPE html>
|
|||
|
|
<html lang="zh-CN" data-theme="light">
|
|||
|
|
<head>
|
|||
|
|
<meta charset="utf-8">
|
|||
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|||
|
|
<title>埋点实战:给应用加上 RED 指标 · 指标与 Prometheus · SRE 从零到成熟</title>
|
|||
|
|
<meta name="description" content="指标与 Prometheus 第 8 章:埋点实战:给应用加上 RED 指标。本章 4 个小节。">
|
|||
|
|
<link rel="stylesheet" href="../../assets/doc.css">
|
|||
|
|
</head>
|
|||
|
|
<body>
|
|||
|
|
|
|||
|
|
<header class="topbar">
|
|||
|
|
<div class="tb-in">
|
|||
|
|
<a class="brand" href="../../index.html"><span class="logo">SRE</span><div>从零到成熟<small>模块详解</small></div></a>
|
|||
|
|
<div class="crumbs">
|
|||
|
|
<a href="../../index.html">学习路径</a><span class="sep">/</span>
|
|||
|
|
<a href="../../index.html#s2">阶段 2 · 看得见</a><span class="sep">/</span>
|
|||
|
|
<a href="index.html">指标与 Prometheus</a><span class="sep">/</span><b>第 8 章</b>
|
|||
|
|
</div>
|
|||
|
|
<div class="spacer"></div>
|
|||
|
|
<button class="btn" id="tocToggle">☰ 导航</button>
|
|||
|
|
<button class="btn" id="themeBtn" title="切换到深色主题">深色</button>
|
|||
|
|
</div>
|
|||
|
|
</header>
|
|||
|
|
|
|||
|
|
<div class="layout" id="layout">
|
|||
|
|
<aside class="sidebar">
|
|||
|
|
<h2>章节目录</h2>
|
|||
|
|
<nav id="chapters"><a class="toc-a" href="01-why.html"><i class="cn">1</i>为什么指标是可观测性的第一支柱</a><div class="subnav"><a class="toc-a lv3" href="01-why.html#sec-1-1">指标能回答而日志回答不了的问题</a><a class="toc-a lv3" href="01-why.html#sec-1-2">三支柱的分工:别让一种数据干三种活</a><a class="toc-a lv3" href="01-why.html#sec-1-3">成本模型:为什么指标可以全量长期保留</a></div><a class="toc-a" href="02-method.html"><i class="cn">2</i>方法论:四大黄金信号、USE 与 RED</a><div class="subnav"><a class="toc-a lv3" href="02-method.html#sec-2-1">四大黄金信号:先分清面向谁</a><a class="toc-a lv3" href="02-method.html#sec-2-2">RED:一个服务的最小可观测集合</a><a class="toc-a lv3" href="02-method.html#sec-2-3">USE:每个资源都要问三个问题</a><a class="toc-a lv3" href="02-method.html#sec-2-4">三个框架怎么一起用</a></div><a class="toc-a" href="03-model.html"><i class="cn">3</i>数据模型:时间序列、标签与基数陷阱</a><div class="subnav"><a class="toc-a lv3" href="03-model.html#sec-3-1">一条时间序列的完整身份</a><a class="toc-a lv3" href="03-model.html#sec-3-2">基数(cardinality)是怎么被撑爆的</a><a class="toc-a lv3" href="03-model.html#sec-3-3">标签设计规则:先写指标字典,再写代码</a></div><a class="toc-a" href="04-types.html"><i class="cn">4</i>指标类型:counter / gauge / histogram / summary</a><div class="subnav"><a class="toc-a lv3" href="04-types.html#sec-4-1">counter:只增不减,必须用 rate 读</a><a class="toc-a lv3" href="04-types.html#sec-4-2">gauge:可增可减,直接读</a><a class="toc-a lv3" href="04-types.html#sec-4-3">histogram:服务端分桶,能聚合的分位数</a><a class="toc-a lv3" href="04-types.html#sec-4-4">summary:客户端算分位数,聚合即失真</a></div><a class="toc-a" href="05-promql.html"><i class="cn">5</i>PromQL 核心:rate、聚合与 by / without</a><div class="subnav"><a class="toc-a lv3" href="05-promql.html#sec-5-1">instant vector 与 range vector:rate 只能吃区间</a><a class="toc-a lv3" href="05-promql.html#sec-5-2">rate 与 increase:为什么至少需要两个样本</a><a class="toc-a lv3" href="05-promql.html#sec-5-3">聚合:by 与 without 的语义差异</a><a class="toc-a lv3" href="05-promql.html#sec-5-4">offset、@ 与子查询</a></div><a class="toc-a" href="06-quantile.html"><i class="cn">6</i>分位数:histogram_quantile 与 P99 的正确算法</a><div class="subnav"><a class="toc-a lv3" href="06-quantile.html#sec-6-1">为什么不能对 P99 求平均</a><a class="toc-a lv3" href="06-quantile.html#sec-6-2">分桶是怎么变成分位数的</a><a class="toc-a lv3" href="06-quantile.html#sec-6-3">低桶数为什么失真:误差最大可以到一整个桶宽</a><a class="toc-a lv3" href="06-quantile.html#sec-6-4">生产可用的分位数查询</a></div><a class="toc-a" href="07-collect.html"><i class="cn">7</i>采集体系:exporter、pull 模型、服务发现与 relabel</a><div class="subnav"><a class="toc-a lv3" href="07-collect.html#sec-7-1">pull 模型与 exporter 生态</a><a class="toc-a lv3" href="07-collect.html#sec-7-2">一份真实的 scrape_configs</a><a class="toc-a lv3" href="07-collect.html#sec-7-3">服务发现与 relabel:从发现到抓取之间发生了什么</a><a class="toc-a lv3" href="07-collect.html#sec-7-4">抓取间隔、超时与保留策略的取舍</a></div><span class="toc-a active" aria-current="page"><i class="cn">8</i>埋点实战:给应用加上 RED 指标</span><div class="subnav current"><a class="toc-a lv3" href="#sec-8-1">先写指标字典,再写代码</a><a class="toc-a lv3" href="#sec-8-2">中间件:一次搞定 QPS、错误率和耗时</a><a class="toc-a lv3" href="#sec-8-3">业务与依赖指标:资源全绿时唯一能救命的信号</a><a class="toc-a lv3" href="#sec-8-4">高基数防御:三道卡口</a></div><a class="toc-a" href="09-alert.html"><i class="cn">9</i>告警设计:for、分级、路<EFBFBD>
|
|||
|
|
<div class="side-foot">
|
|||
|
|
<a class="btn" href="index.html">← 模块目录</a>
|
|||
|
|
<a class="btn" href="../../index.html">学习路径</a>
|
|||
|
|
</div>
|
|||
|
|
</aside>
|
|||
|
|
<div class="mask" id="mask"></div>
|
|||
|
|
|
|||
|
|
<main class="main-col">
|
|||
|
|
<article>
|
|||
|
|
<p class="chapnav">
|
|||
|
|
<a href="index.html">指标与 Prometheus</a>
|
|||
|
|
<span>·</span>
|
|||
|
|
<span>第 <b class="pos">8</b> / 14 章</span>
|
|||
|
|
</p>
|
|||
|
|
|
|||
|
|
<h2 id="instrument"><span class="n">8</span>埋点实战:给应用加上 RED 指标</h2>
|
|||
|
|
|
|||
|
|
<p>这一章把前面所有概念落成代码。目标很具体:给一个 HTTP 服务加上
|
|||
|
|
<b>QPS、错误率、P95/P99、队列深度、依赖耗时</b>五组指标,
|
|||
|
|
并且保证这些指标的标签基数有上限。埋点写错的地方通常不在语法,
|
|||
|
|
而在<b>标签的取值集合没有边界</b>。</p>
|
|||
|
|
|
|||
|
|
<h3 id="sec-8-1">8.1 先写指标字典,再写代码</h3>
|
|||
|
|
<p>下面这张表就是「指标字典」:每一行在代码里对应一个指标对象,
|
|||
|
|
在评审时对应一个问题「它的标签最多几个取值」。</p>
|
|||
|
|
<div class="tablewrap">
|
|||
|
|
<table>
|
|||
|
|
<thead><tr><th>指标名</th><th>类型</th><th>标签(取值上限)</th><th>用途 / 对应告警</th></tr></thead>
|
|||
|
|
<tbody>
|
|||
|
|
<tr><td><code>http_requests_total</code></td><td>counter</td><td>route(20) method(5) status(15)</td><td>QPS 与错误率;无流量告警</td></tr>
|
|||
|
|
<tr><td><code>http_request_duration_seconds</code></td><td>histogram</td><td>route(20) method(5) status(15)</td><td>P95 / P99;延迟告警</td></tr>
|
|||
|
|
<tr><td><code>http_inflight_requests</code></td><td>gauge</td><td>route(20)</td><td>并发度,配合饱和度判断</td></tr>
|
|||
|
|
<tr><td><code>dependency_request_duration_seconds</code></td><td>histogram</td><td>dep(6) op(10) result(3)</td><td>依赖耗时;依赖慢告警</td></tr>
|
|||
|
|
<tr><td><code>worker_queue_depth</code></td><td>gauge</td><td>queue(3)</td><td>队列深度;饱和度告警</td></tr>
|
|||
|
|
<tr><td><code>worker_queue_oldest_seconds</code></td><td>gauge</td><td>queue(3)</td><td>最老任务的等待时长(真饱和度信号)</td></tr>
|
|||
|
|
<tr><td><code>order_created_total</code></td><td>counter</td><td>channel(4) result(3)</td><td>业务指标:下单成功数</td></tr>
|
|||
|
|
<tr><td><code>build_info</code></td><td>gauge(恒为 1)</td><td>version(∞ 但每次发布只变一个值)</td><td>关联发布与指标变化</td></tr>
|
|||
|
|
</tbody>
|
|||
|
|
</table>
|
|||
|
|
</div>
|
|||
|
|
<p>命名规则:<code><命名空间>_<子系统>_<名称>_<单位></code>,
|
|||
|
|
单位一律用基本单位(<code>seconds</code> 而不是 <code>ms</code>,<code>bytes</code> 而不是 <code>KB</code>),
|
|||
|
|
counter 以 <code>_total</code> 结尾。直方图不要自己加 <code>_seconds_bucket</code> 后缀,
|
|||
|
|
客户端库会自动展开。</p>
|
|||
|
|
|
|||
|
|
<h3 id="sec-8-2">8.2 中间件:一次搞定 QPS、错误率和耗时</h3>
|
|||
|
|
<p>Go 版本(<code>github.com/prometheus/client_golang</code>),关键点是
|
|||
|
|
<b>route 取自路由模板而不是原始 URL</b>,以及 <code>status</code> 在响应写出后才能拿到:</p>
|
|||
|
|
<pre data-lang="go" data-name="metrics.go:指标定义与中间件">package middleware
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"net/http"
|
|||
|
|
"strconv"
|
|||
|
|
"time"
|
|||
|
|
|
|||
|
|
"github.com/prometheus/client_golang/prometheus"
|
|||
|
|
"github.com/prometheus/client_golang/prometheus/promauto"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
var (
|
|||
|
|
httpRequests = promauto.NewCounterVec(prometheus.CounterOpts{
|
|||
|
|
Name: "http_requests_total",
|
|||
|
|
Help: "HTTP 请求总数",
|
|||
|
|
}, []string{"route", "method", "status"})
|
|||
|
|
|
|||
|
|
httpDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
|
|||
|
|
Name: "http_request_duration_seconds",
|
|||
|
|
Help: "HTTP 请求耗时",
|
|||
|
|
Buckets: []float64{0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 10},
|
|||
|
|
}, []string{"route", "method", "status"})
|
|||
|
|
|
|||
|
|
inflight = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
|||
|
|
Name: "http_inflight_requests",
|
|||
|
|
Help: "正在处理的请求数",
|
|||
|
|
}, []string{"route"})
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// statusRecorder 用来在 WriteHeader 时捕获状态码
|
|||
|
|
type statusRecorder struct {
|
|||
|
|
http.ResponseWriter
|
|||
|
|
status int
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func (r *statusRecorder) WriteHeader(code int) {
|
|||
|
|
r.status = code
|
|||
|
|
r.ResponseWriter.WriteHeader(code)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// routeOf 从请求里取出路由模板。
|
|||
|
|
// 用 gin / chi / echo 时都有现成方法(c.FullPath() / chi.RouteContext(r.Context()).RoutePattern())。
|
|||
|
|
// 取不到时必须落到固定值,绝不能用 r.URL.Path。
|
|||
|
|
func routeOf(r *http.Request) string {
|
|||
|
|
if p := r.Context().Value(routeKey{}); p != nil {
|
|||
|
|
return p.(string)
|
|||
|
|
}
|
|||
|
|
return "unmatched"
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func Metrics(next http.Handler) http.Handler {
|
|||
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|||
|
|
route := routeOf(r)
|
|||
|
|
inflight.WithLabelValues(route).Inc()
|
|||
|
|
defer inflight.WithLabelValues(route).Dec()
|
|||
|
|
|
|||
|
|
rec := &statusRecorder{ResponseWriter: w, status: 200}
|
|||
|
|
start := time.Now()
|
|||
|
|
next.ServeHTTP(rec, r)
|
|||
|
|
elapsed := time.Since(start).Seconds()
|
|||
|
|
|
|||
|
|
status := strconv.Itoa(rec.status)
|
|||
|
|
httpRequests.WithLabelValues(route, r.Method, status).Inc()
|
|||
|
|
httpDuration.WithLabelValues(route, r.Method, status).Observe(elapsed)
|
|||
|
|
})
|
|||
|
|
}</pre>
|
|||
|
|
<p>几个容易写错的地方:</p>
|
|||
|
|
<ul>
|
|||
|
|
<li><b>没有 <code>statusRecorder</code> 就永远只能记 200。</b>Go 的
|
|||
|
|
<code>http.ResponseWriter</code> 不暴露已写出的状态码,必须自己包一层;
|
|||
|
|
忘写 <code>WriteHeader</code> 的转发会导致 <code>status</code> 恒为 200,错误率永远显示 0%。</li>
|
|||
|
|
<li><b><code>inflight</code> 要用 <code>defer</code> 减</b>,否则发生 panic 时这个 gauge 会一直涨,
|
|||
|
|
而且重启前不会回落——它看起来就像一次永不结束的流量高峰。</li>
|
|||
|
|
<li><b>热路径上优先用 <code>With(labelValues...)</code> 缓存</b>而不是每次
|
|||
|
|
<code>WithLabelValues</code>。后者每次都要做一次 map 查找与哈希,
|
|||
|
|
在 5000 QPS 下是可见的开销。写法是把它放进一个 map 或直接用
|
|||
|
|
<code>prometheus.CounterVec</code> 的 <code>MustCurryWith</code>。</li>
|
|||
|
|
<li><code>/metrics</code> <b>要单独一个端口</b>(比如 9464),不要和业务端口共用,
|
|||
|
|
也不要经过鉴权、限流、日志中间件——否则监控抓取会污染业务日志,还可能被公网扫到。</li>
|
|||
|
|
</ul>
|
|||
|
|
|
|||
|
|
<h3 id="sec-8-3">8.3 业务与依赖指标:资源全绿时唯一能救命的信号</h3>
|
|||
|
|
<p>依赖耗时的埋法要点是<b>标签用枚举</b>:<code>dep="mysql"</code>、<code>dep="redis"</code>、
|
|||
|
|
<code>dep="payment-gateway"</code>,而不是把 URL 打进去。
|
|||
|
|
调用点建议放在统一的 HTTP / DB 客户端封装里,而不是散落在业务代码。</p>
|
|||
|
|
<pre data-lang="go" data-name="dependency.go:依赖耗时与结果">var depDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
|
|||
|
|
Name: "dependency_request_duration_seconds",
|
|||
|
|
Help: "对外依赖调用耗时",
|
|||
|
|
Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 3},
|
|||
|
|
}, []string{"dep", "op", "result"})
|
|||
|
|
|
|||
|
|
func ObserveDep(dep, op string, start time.Time, err error) {
|
|||
|
|
result := "ok"
|
|||
|
|
switch {
|
|||
|
|
case err == nil:
|
|||
|
|
case errors.Is(err, context.DeadlineExceeded):
|
|||
|
|
result = "timeout"
|
|||
|
|
case errors.Is(err, context.Canceled):
|
|||
|
|
result = "canceled"
|
|||
|
|
default:
|
|||
|
|
result = "error"
|
|||
|
|
}
|
|||
|
|
depDuration.WithLabelValues(dep, op, result).Observe(time.Since(start).Seconds())
|
|||
|
|
}</pre>
|
|||
|
|
<p><b>队列深度要打两个指标</b>,这一点经常被忽略:</p>
|
|||
|
|
<ul>
|
|||
|
|
<li><code>worker_queue_depth</code>:当前等待中的任务数。<b>它会被限流掩盖</b>——
|
|||
|
|
如果上游限流了,队列深度可能一直很健康。</li>
|
|||
|
|
<li><code>worker_queue_oldest_seconds</code>:最老的那个任务已经等了多久。
|
|||
|
|
这才是真正的饱和度信号:深度 50 但最老任务等了 0.2 秒,说明消费很快;
|
|||
|
|
深度 50 而最老任务等了 40 秒,说明消费已经停了。<b>告警应该建在第二个指标上。</b></li>
|
|||
|
|
</ul>
|
|||
|
|
<p>业务指标至少要有三个:入口请求量、核心业务动作的成功数(<code>order_created_total</code>)、
|
|||
|
|
以及一致性校验(比如「已支付但未发货」的订单数,用 gauge 暴露)。
|
|||
|
|
资源指标全绿而业务指标归零,是最难查的一类故障,见<a href="11-antipattern.html">第 11 章</a>。</p>
|
|||
|
|
|
|||
|
|
<h3 id="sec-8-4">8.4 高基数防御:三道卡口</h3>
|
|||
|
|
<ol class="steps">
|
|||
|
|
<li><b>代码卡口</b>:任何 <code>WithLabelValues(变量)</code> 在评审时都要能回答
|
|||
|
|
「这个变量的取值集合有多大、上限是多少」。答不上来就说明它该进日志而不是指标。</li>
|
|||
|
|
<li><b>路由归一化</b>:优先用框架的路由模板;取不到就落到固定值
|
|||
|
|
<code>unmatched</code>,绝不用 <code>r.URL.Path</code>。注意 404 请求的路由模板通常是空的,
|
|||
|
|
所以 <code>unmatched</code> 这一档本身也要在字典里登记(它的基数永远是 1)。</li>
|
|||
|
|
<li><b>采集侧兜底</b>:用 <code>metric_relabel_configs</code> 把已经失控的指标整体丢掉,
|
|||
|
|
并给每个 job 配 <code>sample_limit</code>。这是在代码来不及改时的止血手段。</li>
|
|||
|
|
</ol>
|
|||
|
|
<pre data-lang="yaml" data-name="采集侧兜底:丢掉高基数指标与标签">metric_relabel_configs:
|
|||
|
|
# 整体丢弃某个高基数指标(比改代码快得多,但会永久丢失这个指标)
|
|||
|
|
- source_labels: [__name__]
|
|||
|
|
regex: http_request_uri_total|trace_detail_seconds.*
|
|||
|
|
action: drop
|
|||
|
|
# 只丢掉某个罪魁标签,保留指标本身
|
|||
|
|
- regex: user_id|request_id|session_id
|
|||
|
|
action: labeldrop</pre>
|
|||
|
|
|
|||
|
|
<div class="box case">
|
|||
|
|
<span class="bt">真实场景 · 用 <code>r.URL.Path</code> 当 route,3 小时涨到 120 万条序列</span>
|
|||
|
|
<p>一个订单查询接口的埋点写成了 <code>WithLabelValues(r.URL.Path, ...)</code>。
|
|||
|
|
上线后第一个小时一切正常,因为压测流量集中在少数几个订单 ID 上。</p>
|
|||
|
|
<ul>
|
|||
|
|
<li>09:10 上线,<code>prometheus_tsdb_head_series</code> = 31 万。</li>
|
|||
|
|
<li>10:00 真实流量上来,路径里全是真实订单号
|
|||
|
|
(<code>/api/v1/orders/9f2b8c1d-...</code>),序列数涨到 58 万。</li>
|
|||
|
|
<li>11:30 涨到 86 万,<code>scrape_series_added{job="orders"}</code> 稳定在每分钟新增 4000 条以上。</li>
|
|||
|
|
<li>12:20 涨到 120 万,Prometheus 抓取耗时从 0.09s 涨到 3.4s,多个看板查询超时。</li>
|
|||
|
|
</ul>
|
|||
|
|
<p><b>发现方式</b>:<code>count(count by (route) (http_requests_total))</code> 返回 47 万,
|
|||
|
|
正常应该在 20 上下。修复:改用路由模板 <code>/api/v1/orders/{id}</code>,
|
|||
|
|
再加一条采集侧的 <code>labeldrop</code> 做兜底。
|
|||
|
|
<b>关键是这个事故不会触发任何错误告警</b>——错误率、延迟、QPS 全都正常,
|
|||
|
|
唯一的信号是序列数曲线的斜率。所以基数斜率必须单独配一条告警。</p>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<div class="box lab">
|
|||
|
|
<span class="bt">动手 · 30 秒起一个带完整 RED 埋点的服务(Python 版)</span>
|
|||
|
|
<pre data-lang="bash" data-name="安装客户端并启动">python3 -m pip install prometheus_client</pre>
|
|||
|
|
<pre data-lang="python" data-name="demo_metrics.py">import random, threading, time
|
|||
|
|
from prometheus_client import Counter, Gauge, Histogram, start_http_server
|
|||
|
|
|
|||
|
|
REQ = Counter("http_requests_total", "HTTP 请求总数", ["route", "method", "status"])
|
|||
|
|
LAT = Histogram(
|
|||
|
|
"http_request_duration_seconds", "HTTP 请求耗时", ["route"],
|
|||
|
|
buckets=[0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 10],
|
|||
|
|
)
|
|||
|
|
DEP = Histogram(
|
|||
|
|
"dependency_request_duration_seconds", "依赖调用耗时", ["dep", "result"],
|
|||
|
|
buckets=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 3],
|
|||
|
|
)
|
|||
|
|
QUEUE = Gauge("worker_queue_depth", "等待中的任务数", ["queue"])
|
|||
|
|
HTTP_BUCKETS = LAT # 仅用于对齐命名
|
|||
|
|
|
|||
|
|
depth = 0
|
|||
|
|
|
|||
|
|
def simulate_requests():
|
|||
|
|
while True:
|
|||
|
|
route = random.choice(["/api/v1/orders", "/api/v1/orders/{id}", "/api/v1/pay"])
|
|||
|
|
slow = random.random() < 0.01 # 1% 的慢请求
|
|||
|
|
dep = random.choice(["mysql", "redis", "payment"])
|
|||
|
|
DEP.labels(dep, "error" if slow else "ok").observe(random.expovariate(1 / (1.5 if slow else 0.03)))
|
|||
|
|
time.sleep(random.expovariate(1 / 0.03))
|
|||
|
|
status = "500" if random.random() < 0.01 else "200"
|
|||
|
|
LAT.labels(route).observe(random.expovariate(1 / (0.8 if slow else 0.05)))
|
|||
|
|
REQ.labels(route, "GET", status).inc()
|
|||
|
|
|
|||
|
|
def simulate_queue():
|
|||
|
|
global depth
|
|||
|
|
while True:
|
|||
|
|
depth = max(0, depth + random.randint(-6, 7))
|
|||
|
|
QUEUE.labels("order-worker").set(depth)
|
|||
|
|
time.sleep(1)
|
|||
|
|
|
|||
|
|
start_http_server(9464)
|
|||
|
|
threading.Thread(target=simulate_queue, daemon=True).start()
|
|||
|
|
threading.Thread(target=simulate_requests, daemon=True).start()
|
|||
|
|
while True:
|
|||
|
|
time.sleep(3600)</pre>
|
|||
|
|
<pre data-lang="bash" data-name="运行并确认指标格式">python3 demo_metrics.py &
|
|||
|
|
sleep 5
|
|||
|
|
curl -s localhost:9464/metrics | grep -E '^http_requests_total|^http_request_duration_seconds_count' | head
|
|||
|
|
curl -s localhost:9464/metrics | grep '^http_request_duration_seconds_bucket' | head -4</pre>
|
|||
|
|
<p>预期输出:能看到 <code>http_requests_total{method="GET",route="/api/v1/orders",status="200"} 47.0</code>
|
|||
|
|
这样的行,以及从 <code>le="0.01"</code> 开始的桶序列。
|
|||
|
|
<b>如果桶里没有 <code>le="+Inf"</code>,说明你手写的文本格式有问题</b>——
|
|||
|
|
用客户端库时它一定会有。接着把第 7 章的 <code>prometheus.yml</code> 里加一个 job
|
|||
|
|
指向 <code>host.docker.internal:9464</code>,就能在 Prometheus 里跑出完整的 RED 查询。</p>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<div class="box warn">
|
|||
|
|
<span class="bt">不要在高频路径上做「指标续期」</span>
|
|||
|
|
<p>有一种常见反模式:为了让 gauge 不「过期」,在每次请求里都给它 <code>Set()</code> 一次当前值。
|
|||
|
|
这会让 gauge 的含义退化成「最近一次请求时的值」,并且在高 QPS 下产生大量无意义的写入。
|
|||
|
|
<b>gauge 应该由专门的后台协程按固定周期(1–15 秒)采集,而不是被业务请求驱动。</b>
|
|||
|
|
监控数据的时间语义要和业务事件解耦,否则「刚刚有没有请求」会污染「队列有多长」这个事实。</p>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
|
|||
|
|
</article>
|
|||
|
|
|
|||
|
|
<nav class="pager">
|
|||
|
|
<a class="prev" href="07-collect.html"><span class="k">← 上一章</span><span class="v">第 7 章 · 采集体系:exporter、pull 模型、服务发现与 relabel</span></a>
|
|||
|
|
<a class="next" href="09-alert.html"><span class="k">下一章 →</span><span class="v">第 9 章 · 告警设计:for、分级、路由与抑制</span></a>
|
|||
|
|
</nav>
|
|||
|
|
|
|||
|
|
<p class="foot">
|
|||
|
|
指标与 Prometheus · 第 8 章 埋点实战:给应用加上 RED 指标<br>
|
|||
|
|
<a href="index.html">模块目录</a> · <a href="../../index.html">返回学习路径</a>
|
|||
|
|
</p>
|
|||
|
|
</main>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<button id="toTop" title="回到顶部">↑</button>
|
|||
|
|
<script src="../../assets/doc.js"></script>
|
|||
|
|
</body>
|
|||
|
|
</html>
|