我不能将原始请求数据推送到 Prometheus 吗?

Can't I push raw request data to Prometheus?

我需要计算 API 个按特定 headers 分组的呼叫。例如,我想知道有多少 API 个呼叫有 headerX=valueY

为此,我想发布一个这样的指标(请忽略命名约定),以便我以后查询。

http_request{HeaderX=valueR, HeaderY=valueM, etc...}

如果普罗米修斯可以做到这一点,请帮助我。

正如@tkausl 所观察到的,这是可能的,但不推荐。您没有说明您使用的是哪个特定客户端(即 Java、Go、Python 等),所以这是一个 Java 示例":

static final Counter httpRequests = Counter.build()
    .name("http_requests_total")
    .help("Total number of requests by path and header values.")
    .labelNames("path", "content_type", "user_agent")
    .register();

然后在你的请求中handler/interceptor:

httpRequests.labels(requestPath, contentType, userAgent).inc();

不推荐这样做的原因是如果你的 header 可以有无限数量的值(它们可以,因为你可以用任何随机 header values you please) 然后你可以得到无限数量的时间序列。例如

http_requests_total{path="/",content_type="text/plain",user_agent="curl 1.0"} 5
http_requests_total{path="/",content_type="text/plain",user_agent="curl 1.0-whatever"} 1
http_requests_total{path="/",content_type="text/plain",user_agent="curl 1.0-the"} 1
http_requests_total{path="/",content_type="text/plain",user_agent="curl 1.0-client"} 1
http_requests_total{path="/",content_type="text/plain",user_agent="curl 1.0-wants"} 1

现在乘以每个标签(假设您有 10 个 API 端点、10 种不同的内容类型和 100 个不同的用户代理,您有 10k 个指标。

因此,如果您真的对几个可能的 header 和一些可能的值感兴趣(比如 JSON、XML 和文本;以及 Chrome、Firefox 和 IE),然后记录这些特定值(例如 "application/json")或使用正则表达式匹配 ".*Chrome.*",然后记录 "Chrome" 作为标签值。对于任何不匹配的 header 值,您可以使用 "other" 或您想要的任何特定值。这样你的客户就不会炸毁你的普罗米修斯。 (客户端库管理多个值的时间可能比 Prometheus 长得多,Prometheus 需要为每个值保留一个时间序列,即使它永远停留在 1。)