# Prometheus

`prometheus` 插件提供了将 APISIX 与 [Prometheus](https://prometheus.io) 集成的能力。

启用插件后，APISIX 将开始收集相关指标，例如 API 请求和延迟，并以[基于文本的展示格式](https://prometheus.io/docs/instrumenting/exposition_formats/#exposition-formats)将它们导出到 Prometheus。然后，你可以在 Prometheus 中创建监控规则和告警，以监控 API 网关和 API 的健康状况。

[]()

## 指标[​](#指标 "指标的直接链接")

Prometheus 中有不同类型的指标。要了解它们的区别，请参阅 [指标类型](https://prometheus.io/docs/concepts/metric_types/)。

默认情况下，`prometheus` 插件会导出以下指标。有关示例，请参阅 [获取 APISIX 指标](#%E8%8E%B7%E5%8F%96-apisix-%E6%8C%87%E6%A0%87)。请注意，如果没有数据，某些指标（如 `apisix_batch_process_entries`）可能不会立即显示。

| 名称                                      | 类型      | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| ----------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| apisix\_bandwidth                         | counter   | 流经 APISIX 的总流量（以字节为单位）。                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| apisix\_etcd\_modify\_indexes             | gauge     | APISIX 键对 etcd 的更改次数。                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| apisix\_batch\_process\_entries           | gauge     | 批量发送数据时批次中的剩余条目数，例如使用 `http logger` 和其他日志插件时。                                                                                                                                                                                                                                                                                                                                                                                                          |
| apisix\_etcd\_reachable                   | gauge     | APISIX 是否可以连接到 etcd。值 `1` 表示可达，`0` 表示不可达。                                                                                                                                                                                                                                                                                                                                                                                                                        |
| apisix\_http\_status                      | counter   | 返回给客户端的 HTTP 状态码。这是经过插件处理和代理后客户端实际收到的状态，可能与上游状态不同。                                                                                                                                                                                                                                                                                                                                                                                       |
| apisix\_http\_requests\_total             | gauge     | 来自客户端的 HTTP 请求数。                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| apisix\_nginx\_http\_current\_connections | gauge     | 当前与客户端的连接数。                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| apisix\_nginx\_metric\_errors\_total      | counter   | `nginx-lua-prometheus` 错误总数。                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| apisix\_http\_latency                     | histogram | HTTP 请求延迟（以毫秒为单位）。                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| apisix\_node\_info                        | gauge     | 有关 APISIX 节点的信息，例如主机名和 APISIX 版本。                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| apisix\_shared\_dict\_capacity\_bytes     | gauge     | [NGINX 共享字典](https://github.com/openresty/lua-nginx-module#ngxshareddict) 的总容量。                                                                                                                                                                                                                                                                                                                                                                                             |
| apisix\_shared\_dict\_free\_space\_bytes  | gauge     | [NGINX 共享字典](https://github.com/openresty/lua-nginx-module#ngxshareddict) 中的剩余空间。                                                                                                                                                                                                                                                                                                                                                                                         |
| apisix\_nginx\_timers                     | gauge     | 每个 NGINX 进程及子系统中正在运行和等待中的 Lua 定时器数量。自 APISIX 3.20.0 起引入。                                                                                                                                                                                                                                                                                                                                                                                                |
| apisix\_nginx\_timers\_max                | gauge     | 配置的正在运行和等待中的 Lua 定时器数量上限。自 APISIX 3.20.0 起引入。                                                                                                                                                                                                                                                                                                                                                                                                               |
| apisix\_nginx\_process\_connections       | gauge     | 每个 NGINX 进程中正在使用的连接槽位数量。自 APISIX 3.20.0 起引入。                                                                                                                                                                                                                                                                                                                                                                                                                   |
| apisix\_nginx\_process\_connections\_max  | gauge     | 每个 NGINX 进程可用的连接槽位数量。自 APISIX 3.20.0 起引入。                                                                                                                                                                                                                                                                                                                                                                                                                         |
| apisix\_nginx\_lua\_memory\_bytes         | gauge     | 每个 NGINX 进程及子系统中 Lua VM 分配的内存。自 APISIX 3.20.0 起引入。                                                                                                                                                                                                                                                                                                                                                                                                               |
| apisix\_upstream\_status                  | gauge     | 上游节点的健康检查状态，如果在上游配置了健康检查则可用。值 `1` 表示健康，`0` 表示不健康。                                                                                                                                                                                                                                                                                                                                                                                            |
| apisix\_stream\_connection\_total         | counter   | 每个流路由处理的连接总数。                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| apisix\_stream\_active\_connections       | gauge     | 每个流监听地址上活动的 TCP 连接与 UDP 会话数。需要 APISIX-Runtime。在 API7 企业版 3.9.x 系列中自 3.9.19 起支持，在 3.10.x 系列中自 3.10.6 起支持，并且在 APISIX 中自 3.18.0 起支持。                                                                                                                                                                                                                                                                                                 |
| apisix\_stream\_status                    | counter   | 按终止状态、监听地址和上游节点统计的已结束流会话数。在 API7 企业版 3.9.x 系列中自 3.9.19 起支持，在 3.10.x 系列中自 3.10.6 起支持，并且在 APISIX 中自 3.18.0 起支持。                                                                                                                                                                                                                                                                                                                |
| apisix\_stream\_bandwidth                 | counter   | 流子系统按监听地址、方向和连接侧代理的字节数。需要 APISIX-Runtime。在 API7 企业版 3.9.x 系列中自 3.9.19 起支持，在 3.10.x 系列中自 3.10.6 起支持，并且在 APISIX 中自 3.18.0 起支持。                                                                                                                                                                                                                                                                                                 |
| apisix\_llm\_prompt\_tokens               | counter   | 提示词 Token 数量。仅对 AI 请求类型导出。自 API7 企业版 3.9.7 和 APISIX 3.17.0 起支持。                                                                                                                                                                                                                                                                                                                                                                                              |
| apisix\_llm\_completion\_tokens           | counter   | 补全 Token 数量。仅对 AI 请求类型导出。自 API7 企业版 3.9.7 和 APISIX 3.17.0 起支持。                                                                                                                                                                                                                                                                                                                                                                                                |
| apisix\_llm\_latency                      | histogram | LLM 请求延迟，单位为毫秒。仅对 AI 请求类型导出。自 API7 企业版 3.9.7 和 APISIX 3.17.0 起支持。`type` 标签用于区分完整响应延迟（`total`）与流式请求的首 Token 时间（`ttft`），自 API7 企业版 3.9.14、3.10.1 和 APISIX 3.18.0 起引入。未指定 `type` 的查询会同时匹配两类观测值；如需保留此前的总延迟语义，请筛选 `type="total"`。成功的流式响应仅在记录到非零首 Token 时间时，才会分别记录一个 `total` 样本和一个 `ttft` 样本。错误响应以及在记录首 Token 前结束的流不会记录任一样本。 |
| apisix\_llm\_active\_connections          | gauge     | 正在处理的 LLM 上游请求数。仅对 AI 请求类型导出。自 API7 企业版 3.9.7 和 APISIX 3.17.0 起支持。                                                                                                                                                                                                                                                                                                                                                                                      |
| apisix\_llm\_prompt\_tokens\_dist         | histogram | 单个请求的提示词 Token 数量分布。仅对 AI 请求类型导出。自 API7 企业版 3.9.14、3.10.1 和 APISIX 3.18.0 起支持。                                                                                                                                                                                                                                                                                                                                                                       |
| apisix\_llm\_completion\_tokens\_dist     | histogram | 单个请求的补全 Token 数量分布。仅对 AI 请求类型导出。自 API7 企业版 3.9.14、3.10.1 和 APISIX 3.18.0 起支持。                                                                                                                                                                                                                                                                                                                                                                         |
| apisix\_ai\_cache\_hits\_total            | counter   | 由 AI Cache 返回的请求数，按精确缓存层或语义缓存层区分。自 API7 企业版 3.9.16、3.10.3 和 APISIX 3.18.0 起支持。                                                                                                                                                                                                                                                                                                                                                                      |
| apisix\_ai\_cache\_misses\_total          | counter   | 未返回缓存响应的 AI Cache 查找次数。自 API7 企业版 3.9.16、3.10.3 和 APISIX 3.18.0 起支持。                                                                                                                                                                                                                                                                                                                                                                                          |
| apisix\_ai\_cache\_bypasses\_total        | counter   | 绕过 AI Cache 查找的请求数。自 API7 企业版 3.9.16、3.10.3 和 APISIX 3.18.0 起支持。                                                                                                                                                                                                                                                                                                                                                                                                  |
| apisix\_ai\_cache\_embedding\_latency     | histogram | 语义缓存层调用嵌入模型服务提供方的延迟，单位为毫秒。自 API7 企业版 3.9.16、3.10.3 和 APISIX 3.18.0 起支持。                                                                                                                                                                                                                                                                                                                                                                          |

备注

仅当请求由 AI 插件（例如 [AI Proxy](https://docs.apiseven.com/hub/ai-proxy.md)）处理时，才会导出 LLM 指标（`apisix_llm_prompt_tokens`、`apisix_llm_completion_tokens`、`apisix_llm_latency`、`apisix_llm_prompt_tokens_dist` 和 `apisix_llm_completion_tokens_dist`）。未启用 AI 插件的路由不会生成这些指标。`apisix_llm_active_connections` 由 AI 插件直接管理，也仅存在于启用了 AI 的路由中。

当一次 LLM 上游尝试开始时，该 gauge 增加；请求进入日志阶段后，该 gauge 减少。对于单次尝试，它表示正在处理的 LLM 上游请求。使用 `ai-proxy-multi` 回退重试时，每次重试都会增加一个新的实例级时序，而请求只会使用最终实例的标签减少一次。因此，失败实例的时序可能会一直高于真实活动请求数，直到指标过期或存储被重置。

要减少 LLM 指标中的高基数标签，请使用[插件元数据](https://docs.apiseven.com/hub/prometheus/configuration.md#plugin-metadata)中的 `disabled_labels`，有选择地禁用 `consumer` 或 `node` 等标签。

提示词和补全 Token 直方图使用可配置的桶。有关默认值和配置方式，请参阅[静态插件属性](https://docs.apiseven.com/hub/prometheus/configuration.md#static-configurations)。

## LLM Token 统计[​](#llm-token-统计 "LLM Token 统计的直接链接")

以下版本的提示词 Token 指标包含服务提供商的缓存用量：

| 服务提供商         | 提示词总量                                                             | 引入版本                                        |
| ------------------ | ---------------------------------------------------------------------- | ----------------------------------------------- |
| Anthropic Messages | `input_tokens + cache_read_input_tokens + cache_creation_input_tokens` | APISIX 3.20.0、API7 Enterprise 3.9.22 和 3.10.9 |
| Bedrock Converse   | `inputTokens + cacheReadInputTokens + cacheWriteInputTokens`           | APISIX 3.20.0 和 API7 Enterprise 3.10.9         |

API7 Enterprise 3.9.23 的 Bedrock 提示词总量仅使用 `inputTokens`。

## 标签[​](#标签 "标签的直接链接")

[标签](https://prometheus.io/docs/practices/naming/#labels) 是指标的属性，用于区分指标。

例如，`apisix_http_status` 指标可以用 `route` 信息进行标记，以识别 HTTP 状态源自哪个路由。

以下是非详尽的 APISIX 指标及其描述的标签列表。

### `apisix_http_status` 的标签[​](#apisix_http_status-的标签 "apisix_http_status-的标签的直接链接")

以下标签用于区分 `apisix_http_status` 指标。

| 名称                | 描述                                                                                                                                                                                                                 |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| code                | 插件处理和代理转发后返回给客户端的 HTTP 响应代码。                                                                                                                                                                   |
| route               | 当 `prefer_name` 为 `false`（默认值）时，为 HTTP 状态源自的路由 ID；当 `prefer_name` 为 `true` 时，为路由名称。如果请求不匹配任何路由，则默认为空字符串。                                                            |
| route\_id           | 仅在 Enterprise 中可用。无论 `prefer_name` 设置如何，HTTP 状态源自的路由 ID。                                                                                                                                        |
| matched\_uri        | 匹配请求的路由 URI。如果请求不匹配任何路由，则默认为空字符串。                                                                                                                                                       |
| matched\_host       | 匹配请求的路由主机。如果请求不匹配任何路由，或者路由上未配置主机，则默认为空字符串。                                                                                                                                 |
| service             | 当 `prefer_name` 为 `false`（默认值）时，为 HTTP 状态源自的服务 ID；当 `prefer_name` 为 `true` 时，为服务名称。如果匹配的路由不属于任何服务，则为空。                                                                |
| service\_id         | 仅在 Enterprise 中可用。无论 `prefer_name` 设置如何，HTTP 状态源自的服务 ID。                                                                                                                                        |
| consumer            | 与请求关联的消费者名称。如果请求没有关联消费者，则默认为空字符串。                                                                                                                                                   |
| node                | 上游节点的 IP 地址。对于 AI 路由，此值为 `ai-proxy` 或 `ai-proxy-multi` 中的 LLM 实例名称。                                                                                                                          |
| gateway\_group\_id  | HTTP 状态源自的网关组 ID。仅 API7 企业版可用。                                                                                                                                                                       |
| instance\_id        | HTTP 状态源自的网关实例 ID。仅 API7 企业版可用。                                                                                                                                                                     |
| portal\_id          | 开发者门户 ID。仅 API7 企业版可用。                                                                                                                                                                                  |
| api\_product\_id    | HTTP 状态源自的产品 ID。仅 API7 企业版可用。                                                                                                                                                                         |
| request\_type       | 与 HTTP 状态关联的请求类型：`traditional_http`、`websocket`、`ai_chat` 或 `ai_stream`。以 `101 Switching Protocols` 应答的请求为 `websocket`，该类型在 API7 企业版 3.9.21、3.10.7 和 APISIX 3.19.0 中引入。          |
| request\_llm\_model | 客户端请求中指定的模型名称。普通 HTTP 流量为空。                                                                                                                                                                     |
| llm\_model          | 网关实际使用的目标模型。如果 AI 实例配置了模型，则使用该值；否则使用客户端请求的模型。普通 HTTP 流量为空。                                                                                                           |
| response\_source    | HTTP 响应的来源：`apisix`（由 APISIX 生成，如插件拒绝或路由未找到）、`nginx`（NGINX 代理错误，如连接被拒绝或上游超时）或 `upstream`（来自上游服务的真实响应）。该标签自 API7 企业版 3.9.10 和 APISIX 3.17.0 起提供。 |
| mcp\_request\_type  | MCP 请求类型，例如 `tools/list` 或 `tools/call`。非 MCP 请求为空。自 API7 企业版 3.9.14 起支持。                                                                                                                     |
| mcp\_tool\_name     | `tools/call` 请求中的 MCP 工具名称，其他请求为空。自 API7 企业版 3.9.14 起支持。                                                                                                                                     |

`response_source` 是 `apisix_http_status` 的必需标签，每个既有状态标签组合最多可能新增三个时序。发布前请更新匹配完整标签集的 PromQL join、记录规则、告警和 Dashboard，并评估新增基数。

### `apisix_bandwidth` 的标签[​](#apisix_bandwidth-的标签 "apisix_bandwidth-的标签的直接链接")

以下标签用于区分 `apisix_bandwidth` 指标。

| 名称                | 描述                                                                                                                                                                                                |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| type                | 流量类型，`egress`（出口）或 `ingress`（入口）。                                                                                                                                                    |
| route               | 当 `prefer_name` 为 `false`（默认值）时，为带宽对应的路由 ID；当 `prefer_name` 为 `true` 时，为路由名称。如果请求不匹配任何路由，则默认为空字符串。                                                 |
| route\_id           | 仅在 Enterprise 中可用。无论 `prefer_name` 设置如何，带宽对应的路由 ID。                                                                                                                            |
| service             | 当 `prefer_name` 为 `false`（默认值）时，为带宽对应的服务 ID；当 `prefer_name` 为 `true` 时，为服务名称。如果匹配的路由不属于任何服务，则为空。                                                     |
| service\_id         | 仅在 Enterprise 中可用。无论 `prefer_name` 设置如何，带宽对应的服务 ID。                                                                                                                            |
| consumer            | 与请求关联的消费者名称。如果请求没有关联消费者，则默认为空字符串。                                                                                                                                  |
| node                | 上游节点的 IP 地址。对于 AI 路由，此值为 `ai-proxy` 或 `ai-proxy-multi` 中的 LLM 实例名称。                                                                                                         |
| gateway\_group\_id  | 仅在 Enterprise 中可用。带宽对应的网关组 ID。                                                                                                                                                       |
| instance\_id        | 仅在 Enterprise 中可用。带宽对应的网关实例 ID。                                                                                                                                                     |
| portal\_id          | 仅在 API7 企业版中可用。开发者门户 ID。                                                                                                                                                             |
| api\_product\_id    | 仅在 Enterprise 中可用。带宽对应的产品 ID。                                                                                                                                                         |
| request\_type       | 带宽对应的请求类型：`traditional_http`、`websocket`、`ai_chat` 或 `ai_stream`。以 `101 Switching Protocols` 应答的请求为 `websocket`，该类型在 API7 企业版 3.9.21、3.10.7 和 APISIX 3.19.0 中引入。 |
| request\_llm\_model | 客户端请求中指定的模型名称。普通 HTTP 流量为空。                                                                                                                                                    |
| llm\_model          | 网关实际使用的目标模型。如果 AI 实例配置了模型，则使用该值；否则使用客户端请求的模型。普通 HTTP 流量为空。                                                                                          |
| mcp\_request\_type  | MCP 请求类型，例如 `tools/list` 或 `tools/call`。非 MCP 请求为空。自 API7 企业版 3.9.14 和 3.10.1 起支持。                                                                                          |
| mcp\_tool\_name     | `tools/call` 请求中的 MCP 工具名称，其他请求为空。自 API7 企业版 3.9.14 和 3.10.1 起支持。                                                                                                          |

### `apisix_http_latency` 的标签[​](#apisix_http_latency-的标签 "apisix_http_latency-的标签的直接链接")

以下标签用于区分 `apisix_http_latency` 指标。

| 名称                | 描述                                                                                                                                                                                                |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| type                | 延迟类型。有关详细信息，请参阅 [延迟类型](#%E5%BB%B6%E8%BF%9F%E7%B1%BB%E5%9E%8B)。                                                                                                                  |
| route               | 当 `prefer_name` 为 `false`（默认值）时，为延迟对应的路由 ID；当 `prefer_name` 为 `true` 时，为路由名称。如果请求不匹配任何路由，则默认为空字符串。                                                 |
| route\_id           | 仅在 Enterprise 中可用。无论 `prefer_name` 设置如何，延迟对应的路由 ID。                                                                                                                            |
| service             | 当 `prefer_name` 为 `false`（默认值）时，为延迟对应的服务 ID；当 `prefer_name` 为 `true` 时，为服务名称。如果匹配的路由不属于任何服务，则为空。                                                     |
| service\_id         | 仅在 Enterprise 中可用。无论 `prefer_name` 设置如何，延迟对应的服务 ID。                                                                                                                            |
| consumer            | 与延迟关联的消费者名称。如果请求没有关联消费者，则默认为空字符串。                                                                                                                                  |
| node                | 与延迟关联的上游节点 IP 地址。对于 AI 路由，此值为 `ai-proxy` 或 `ai-proxy-multi` 中的 LLM 实例名称。                                                                                               |
| gateway\_group\_id  | 仅在 Enterprise 中可用。延迟对应的网关组 ID。                                                                                                                                                       |
| instance\_id        | 仅在 Enterprise 中可用。延迟对应的网关实例 ID。                                                                                                                                                     |
| portal\_id          | 仅在 API7 企业版中可用。开发者门户 ID。                                                                                                                                                             |
| api\_product\_id    | 仅在 Enterprise 中可用。延迟对应的产品 ID。                                                                                                                                                         |
| request\_type       | 延迟对应的请求类型：`traditional_http`、`websocket`、`ai_chat` 或 `ai_stream`。以 `101 Switching Protocols` 应答的请求为 `websocket`，该类型在 API7 企业版 3.9.21、3.10.7 和 APISIX 3.19.0 中引入。 |
| request\_llm\_model | 客户端请求中指定的模型名称。普通 HTTP 流量为空。                                                                                                                                                    |
| llm\_model          | 网关实际使用的目标模型。如果 AI 实例配置了模型，则使用该值；否则使用客户端请求的模型。普通 HTTP 流量为空。                                                                                          |
| mcp\_request\_type  | MCP 请求类型，例如 `tools/list` 或 `tools/call`。非 MCP 请求为空。自 API7 企业版 3.9.14 和 3.10.1 起支持。                                                                                          |
| mcp\_tool\_name     | `tools/call` 请求中的 MCP 工具名称，其他请求为空。自 API7 企业版 3.9.14 和 3.10.1 起支持。                                                                                                          |

#### 延迟类型[​](#延迟类型 "延迟类型的直接链接")

`apisix_http_latency` 可以用以下三种类型之一进行标记：

* `request` 表示从客户端读取第一个字节到向客户端发送最后一个字节后的日志写入之间经过的时间。

* `upstream` 表示等待上游服务响应所经过的时间。

* `apisix` 表示 `request` 延迟与 `upstream` 延迟之间的差值。

对于 WebSocket 会话，`request` 延迟衡量的是升级后连接保持打开的时长，而不只是初始握手。配置了 `enable_websocket` 的路由还会把会话时长记录为 `upstream` 延迟。使用 `ws` 或 `wss` 上游 scheme 的路由不会单独生成 `upstream` 延迟样本，因此其 `apisix` 延迟覆盖整个会话。

`request_type="websocket"` 标签在 API7 企业版 3.9.21、3.10.7 和 APISIX 3.19.0 中引入。可以在延迟查询中使用 `request_type!="websocket"` 将此类会话排除。

换句话说，APISIX 延迟不仅仅归因于 Lua 处理。它应该理解如下：

```
APISIX latency

  = downstream request time - upstream response time

  = downstream traffic latency + NGINX latency
```

### `apisix_upstream_status` 的标签[​](#apisix_upstream_status-的标签 "apisix_upstream_status-的标签的直接链接")

以下标签用于区分 `apisix_upstream_status` 指标。

| 名称 | 描述                                                                                  |
| ---- | ------------------------------------------------------------------------------------- |
| name | 配置了健康检查的上游对应的资源 ID，例如 `/apisix/routes/1` 和 `/apisix/upstreams/1`。 |
| ip   | 上游节点的 IP 地址。                                                                  |
| port | 节点的端口号。                                                                        |

### 流指标的标签[​](#流指标的标签 "流指标的标签的直接链接")

全部四个流指标（`apisix_stream_connection_total`、`apisix_stream_active_connections`、`apisix_stream_status` 和 `apisix_stream_bandwidth`）还带有以下标签。这些标签自 APISIX 3.20.0、API7 Enterprise 3.9.22 和 3.10.9 起引入：

| 名称         | 描述                                                                                                      |
| ------------ | --------------------------------------------------------------------------------------------------------- |
| `service`    | 所匹配流路由的服务。值为服务 ID；`prefer_name` 为 `true` 时为服务名称。会话没有到达带服务的流路由时为空。 |
| `service_id` | 所匹配流路由的服务 ID。会话没有到达带服务的流路由时为空。                                                 |

活动连接数与带宽在会话仍处于打开状态时就会按服务拆分。监听地址上出现的每个服务都会占用流指标共享内存区域中的一个槽位。该区域占满后，新服务的活动连接数与带宽只计入其监听地址的合计，`service` 和 `service_id` 标签为空。

APISIX 从服务的第一个流会话开始计数，包括在下一个 `refresh_interval` 之前结束的会话。

新增的标签会改变现有流指标时序的标识。如需保留忽略新增服务维度的聚合结果，请使用 `sum without (service, service_id) (apisix_stream_connection_total)` 等查询，并按需对其他流指标应用相同的聚合。

`apisix_stream_active_connections` 以流监听地址作为标签：

| 名称          | 描述                                                           |
| ------------- | -------------------------------------------------------------- |
| `listen_addr` | APISIX 接受该 TCP 连接或 UDP 会话的地址，例如 `0.0.0.0:9100`。 |

`apisix_stream_status` 在每个流会话结束时记录一次：

| 名称          | 描述                                                                                                                                                                                                                                   |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `code`        | 会话的结束方式。`200` 表示正常关闭。`400` 表示客户端侧的问题，例如客户端重置连接或发送了无效数据。`403` 表示被访问规则拒绝。`500` 表示内部错误。`502` 表示上游或传输层问题，例如连接失败、重置或空闲超时。`503` 表示被连接数限制拒绝。 |
| `listen_addr` | APISIX 接受该会话的地址。                                                                                                                                                                                                              |
| `node`        | 选中的上游地址，形式为 `IP:port`。会话在 APISIX 选出上游之前结束时为空。                                                                                                                                                               |

对于上游连接建立之后发生的部分失败，NGINX 报告的 Stream `$status` 仍为 200。该指标改用会话终止原因来区分正常关闭与之后的超时或重置。worker 关闭以及未记录到可识别原因时同样使用 `200`。

`apisix_stream_bandwidth` 在会话保持打开期间持续更新：

| 名称          | 描述                                 |
| ------------- | ------------------------------------ |
| `listen_addr` | APISIX 接受该会话的地址。            |
| `type`        | 流量方向：`ingress` 或 `egress`。    |
| `side`        | 连接侧：`downstream` 或 `upstream`。 |

### NGINX 进程指标的标签[​](#nginx-进程指标的标签 "NGINX 进程指标的标签的直接链接")

以下五个指标有助于诊断单个 NGINX 进程的资源压力：`apisix_nginx_timers`、`apisix_nginx_timers_max`、`apisix_nginx_process_connections`、`apisix_nginx_process_connections_max` 和 `apisix_nginx_lua_memory_bytes`。每个进程按配置的 Prometheus `refresh_interval` 发布自己的值。提供指标展示的进程会在返回响应前刷新自己的值。

| 标签        | 描述                                                                                                                                        |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `process`   | 拥有该值的进程：worker 进程为 `worker-<id>`，特权代理进程为 `privileged-agent`。除 `apisix_nginx_timers_max` 外的所有进程指标都使用此标签。 |
| `subsystem` | 拥有定时器或内存的 Lua VM：`http` 或 `stream`。由 `apisix_nginx_timers` 和 `apisix_nginx_lua_memory_bytes` 使用。                           |
| `state`     | 定时器状态：`running` 或 `pending`。由 `apisix_nginx_timers` 和 `apisix_nginx_timers_max` 使用。                                            |

定时器上限来自 `nginx_config.max_running_timers` 和 `nginx_config.max_pending_timers`，未设置这些字段时使用 NGINX 默认值。连接使用量包括监听套接字、客户端连接和从 Lua 打开的出站连接。worker 进程的上限为 `worker_connections`，特权代理进程的上限为其连接槽位限制。

### `apisix_llm_latency` 的标签[​](#apisix_llm_latency-的标签 "apisix_llm_latency-的标签的直接链接")

APISIX 与 API7 企业版使用的标签集不同。API7 企业版还会添加路由和服务显示标签，以及网关与 API 产品资源维度。

| 名称                | 产品                  | 描述                                                                                                                                                                                                                                     |
| ------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type`              | APISIX 和 API7 企业版 | LLM 延迟类型：`total` 表示完整响应延迟，`ttft` 表示流式请求的首 Token 时间。自 API7 企业版 3.9.14、3.10.1 和 APISIX 3.18.0 起引入。此前将每个 `apisix_llm_latency` 样本都视为总延迟的 Dashboard、告警和记录规则必须添加 `type="total"`。 |
| `route`             | API7 企业版           | `prefer_name` 为 `false`（默认值）时为路由 ID，为 `true` 时为路由名称。路由没有名称时回退到路由 ID；请求未匹配路由时为空。                                                                                                               |
| `route_id`          | APISIX 和 API7 企业版 | 在 APISIX 中默认为路由 ID；`prefer_name` 为 `true` 时，有名称则使用路由名称，否则保留 ID。在 API7 企业版中，该标签始终为路由 ID。请求未匹配路由时为空。                                                                                  |
| `service`           | API7 企业版           | `prefer_name` 为 `false`（默认值）时为服务 ID，为 `true` 时为服务名称。服务没有名称时回退到服务 ID；路由不属于服务时为空。                                                                                                               |
| `service_id`        | APISIX 和 API7 企业版 | 在 APISIX 中默认为服务 ID；`prefer_name` 为 `true` 时，有名称则使用服务名称，否则保留 ID。在 API7 企业版中，该标签始终为服务 ID。路由不属于服务时为空。                                                                                  |
| `consumer`          | APISIX 和 API7 企业版 | 消费者名称。请求未关联消费者时为空。                                                                                                                                                                                                     |
| `node`              | APISIX 和 API7 企业版 | `ai-proxy` 或 `ai-proxy-multi` 选中的 LLM 实例名称，而不是上游 IP 地址。                                                                                                                                                                 |
| `gateway_group_id`  | API7 企业版           | 网关组 ID。                                                                                                                                                                                                                              |
| `instance_id`       | API7 企业版           | 网关实例 ID。                                                                                                                                                                                                                            |
| `portal_id`         | API7 企业版           | 开发者门户 ID。                                                                                                                                                                                                                          |
| `api_product_id`    | API7 企业版           | API 产品 ID。                                                                                                                                                                                                                            |
| `request_type`      | APISIX 和 API7 企业版 | AI 请求类型，例如 `ai_chat` 或 `ai_stream`。                                                                                                                                                                                             |
| `request_llm_model` | APISIX 和 API7 企业版 | 客户端请求中发送的模型名称。                                                                                                                                                                                                             |
| `llm_model`         | APISIX 和 API7 企业版 | 网关实际使用的目标模型。如果 AI 实例配置了模型，则使用该值；否则使用客户端请求的模型。                                                                                                                                                   |

### LLM Token 指标的标签[​](#llm-token-指标的标签 "LLM Token 指标的标签的直接链接")

提示词和补全 Token 的计数器与分布直方图在不同产品中使用不同的标签集。

| 名称                | 产品                  | 描述                                                                                                                                                    |
| ------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `route`             | API7 企业版           | `prefer_name` 为 `false`（默认值）时为路由 ID，为 `true` 时为路由名称。路由没有名称时回退到路由 ID；请求未匹配路由时为空。                              |
| `route_id`          | APISIX 和 API7 企业版 | 在 APISIX 中默认为路由 ID；`prefer_name` 为 `true` 时，有名称则使用路由名称，否则保留 ID。在 API7 企业版中，该标签始终为路由 ID。请求未匹配路由时为空。 |
| `matched_uri`       | API7 企业版           | 匹配路由的 URI；请求未匹配路由时为空。                                                                                                                  |
| `matched_host`      | API7 企业版           | 匹配路由的 Host；请求未匹配路由或路由没有配置 Host 时为空。                                                                                             |
| `service`           | API7 企业版           | `prefer_name` 为 `false`（默认值）时为服务 ID，为 `true` 时为服务名称。服务没有名称时回退到服务 ID；路由不属于服务时为空。                              |
| `service_id`        | APISIX 和 API7 企业版 | 在 APISIX 中默认为服务 ID；`prefer_name` 为 `true` 时，有名称则使用服务名称，否则保留 ID。在 API7 企业版中，该标签始终为服务 ID。路由不属于服务时为空。 |
| `consumer`          | APISIX 和 API7 企业版 | 消费者名称；请求未关联消费者时为空。                                                                                                                    |
| `node`              | APISIX 和 API7 企业版 | `ai-proxy` 或 `ai-proxy-multi` 选中的 LLM 实例名称，而不是上游 IP 地址。                                                                                |
| `gateway_group_id`  | API7 企业版           | 网关组 ID。                                                                                                                                             |
| `instance_id`       | API7 企业版           | 网关实例 ID。                                                                                                                                           |
| `portal_id`         | API7 企业版           | 开发者门户 ID。                                                                                                                                         |
| `api_product_id`    | API7 企业版           | API 产品 ID。                                                                                                                                           |
| `request_type`      | APISIX 和 API7 企业版 | AI 请求类型，例如 `ai_chat` 或 `ai_stream`。                                                                                                            |
| `request_llm_model` | APISIX 和 API7 企业版 | 客户端请求中发送的模型名称。自 API7 企业版 3.9.7 和 APISIX 3.17.0 起引入。                                                                              |
| `llm_model`         | APISIX 和 API7 企业版 | 网关实际使用的目标模型。如果 AI 实例配置了模型，则使用该值；否则使用客户端请求的模型。                                                                  |

### `apisix_llm_active_connections` 的标签[​](#apisix_llm_active_connections-的标签 "apisix_llm_active_connections-的标签的直接链接")

活动连接 gauge 会独立于 `prefer_name` 记录路由和服务名称。

| 名称                | 产品                  | 描述                                                                     |
| ------------------- | --------------------- | ------------------------------------------------------------------------ |
| `route`             | APISIX 和 API7 企业版 | 路由名称；请求未匹配具名路由时为空。                                     |
| `route_id`          | APISIX 和 API7 企业版 | 路由 ID；请求未匹配路由时为空。                                          |
| `matched_uri`       | APISIX 和 API7 企业版 | 匹配路由的 URI；请求未匹配路由时为空。                                   |
| `matched_host`      | APISIX 和 API7 企业版 | 匹配路由的 Host；请求未匹配路由或路由没有配置 Host 时为空。              |
| `service`           | APISIX 和 API7 企业版 | 服务名称；路由不属于具名服务时为空。                                     |
| `service_id`        | APISIX 和 API7 企业版 | 服务 ID；路由不属于服务时为空。                                          |
| `consumer`          | APISIX 和 API7 企业版 | 消费者名称；请求未关联消费者时为空。                                     |
| `node`              | APISIX 和 API7 企业版 | `ai-proxy` 或 `ai-proxy-multi` 选中的 LLM 实例名称，而不是上游 IP 地址。 |
| `gateway_group_id`  | API7 企业版           | 网关组 ID。                                                              |
| `instance_id`       | API7 企业版           | 网关实例 ID。                                                            |
| `portal_id`         | API7 企业版           | 开发者门户 ID。                                                          |
| `api_product_id`    | API7 企业版           | API 产品 ID。                                                            |
| `request_type`      | APISIX 和 API7 企业版 | AI 请求类型，例如 `ai_chat` 或 `ai_stream`。                             |
| `request_llm_model` | APISIX 和 API7 企业版 | 客户端请求中发送的模型名称。                                             |
| `llm_model`         | APISIX 和 API7 企业版 | 网关实际使用的目标模型。                                                 |

`request_llm_model` 和 `llm_model` 的值来自客户端和服务提供方数据，最长为 128 字节。自 API7 企业版 3.9.14、3.10.1 和 APISIX 3.18.0 起引入。如果不需要按模型拆分时序，请禁用这些标签。

### AI Cache 指标的标签[​](#ai-cache-指标的标签 "AI Cache 指标的标签的直接链接")

四个 AI Cache 指标共享以下标签。只有 `apisix_ai_cache_hits_total` 包含 `layer`。

| 名称                | 描述                                                                                                                         |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `layer`             | 返回缓存命中的缓存层：`exact` 或 `semantic`。该结构性标签不能禁用。                                                          |
| `route`             | 路由名称；如果路由没有名称，则为空字符串。                                                                                   |
| `route_id`          | 路由 ID。                                                                                                                    |
| `service`           | 服务名称；如果路由未引用服务，则为空字符串。                                                                                 |
| `service_id`        | 服务 ID；如果路由未引用服务，则为空字符串。                                                                                  |
| `consumer`          | Consumer 名称；如果请求未关联 Consumer，则为空字符串。                                                                       |
| `node`              | `ai-proxy` 或 `ai-proxy-multi` 选中的 LLM 实例名称，而不是上游 IP 地址。                                                     |
| `request_type`      | 请求类型，例如 `ai_chat` 或 `ai_stream`。                                                                                    |
| `request_llm_model` | 客户端请求中发送的模型名称。                                                                                                 |
| `llm_model`         | 网关实际使用的目标模型。如果 AI 实例配置了模型，则使用该值；否则使用客户端请求的模型。缓存命中时不会访问 LLM，因此该值为空。 |

API7 企业版还为这些指标导出 `matched_uri`、`matched_host`、`gateway_group_id`、`instance_id`、`portal_id` 和 `api_product_id`。

## 示例[​](#示例 "示例的直接链接")

下面的示例展示了如何在不同场景下使用 `prometheus` 插件。

### 获取 APISIX 指标[​](#获取-apisix-指标 "获取 APISIX 指标的直接链接")

以下示例展示了如何从 APISIX 获取指标。

默认的 Prometheus 指标端点和其他 Prometheus 相关配置可以在[静态配置](https://docs.apiseven.com/hub/prometheus/configuration.md#static-configurations)中找到。如果你想自定义这些配置，请参阅[配置文件](https://docs.apiseven.com/apisix/reference/configuration-files.md#configyaml-and-configyamlexample)。

如果你在容器化环境中部署网关，并希望从外部访问 Prometheus 指标端点，请在网关静态配置中更新 Prometheus 导出地址：

* Host or Docker
* Kubernetes (Helm)

在网关配置文件中新增或更新以下配置：

config.yaml

```
plugin_attr:

  prometheus:

    export_addr:

      ip: 0.0.0.0
```

重新加载网关以使更改生效。

对于 APISIX Helm Chart，在 Chart values 中启用 Prometheus。该配置会将 `plugin_attr.prometheus.export_addr.ip` 渲染为 `0.0.0.0`：

values.yaml

```
apisix:

  prometheus:

    enabled: true
```

对于 API7 网关 Helm Chart，更新 Prometheus 插件属性：

values.yaml

```
pluginAttrs:

  prometheus:

    export_addr:

      ip: 0.0.0.0

      port: 9091
```

然后使用当前网关 release 对应的 Chart 应用 values 文件：

```
helm upgrade <release-name> <chart-name> -n <namespace> -f values.yaml
```

向 APISIX Prometheus 指标端点发送请求：

```
curl "http://127.0.0.1:9091/apisix/prometheus/metrics"
```

你应该看到类似于以下的输出：

```
# HELP apisix_bandwidth Total bandwidth in bytes consumed per service in Apisix

# TYPE apisix_bandwidth counter

apisix_bandwidth{type="egress",route="",service="",consumer="",node=""} 8417

apisix_bandwidth{type="egress",route="1",service="",consumer="",node="127.0.0.1"} 1420

apisix_bandwidth{type="egress",route="2",service="",consumer="",node="127.0.0.1"} 1420

apisix_bandwidth{type="ingress",route="",service="",consumer="",node=""} 189

apisix_bandwidth{type="ingress",route="1",service="",consumer="",node="127.0.0.1"} 332

apisix_bandwidth{type="ingress",route="2",service="",consumer="",node="127.0.0.1"} 332

# HELP apisix_etcd_modify_indexes Etcd modify index for APISIX keys

# TYPE apisix_etcd_modify_indexes gauge

apisix_etcd_modify_indexes{key="consumers"} 0

apisix_etcd_modify_indexes{key="global_rules"} 0

...
```

### 通过禁用标签降低指标基数[​](#reduce-metric-cardinality-by-disabling-labels "通过禁用标签降低指标基数的直接链接")

插件元数据可将选定标签的值折叠为空字符串，在保留指标标签模式的同时减少时序数量。APISIX 和 API7 企业版为 HTTP 状态和延迟指标使用不同的元数据键。

API7 企业版会导出额外维度，因此两种产品接受的标签也有所不同：

| 指标元数据键                                                                                            | APISIX 中可禁用的标签                                                                                                                             | API7 企业版的差异                                                                                                           |
| ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `http_status`                                                                                           | `route`、`matched_uri`、`matched_host`、`service`、`consumer`、`node`、`request_type`、`request_llm_model`、`llm_model`、`response_source`        | 使用键 `status`。额外支持 `route_id`、`service_id`、`mcp_request_type` 和 `mcp_tool_name`，但不允许禁用 `response_source`。 |
| `http_latency`                                                                                          | `route`、`service`、`consumer`、`node`、`request_type`、`request_llm_model`、`llm_model`                                                          | 使用键 `latency`。额外支持 `route_id`、`service_id`、`mcp_request_type` 和 `mcp_tool_name`。                                |
| `bandwidth`                                                                                             | `route`、`service`、`consumer`、`node`、`request_type`、`request_llm_model`、`llm_model`                                                          | 额外支持 `route_id`、`service_id`、`mcp_request_type` 和 `mcp_tool_name`。                                                  |
| `llm_latency`                                                                                           | `route_id`、`service_id`、`consumer`、`node`、`request_type`、`request_llm_model`、`llm_model`                                                    | 还支持 `route` 和 `service`。                                                                                               |
| `llm_prompt_tokens`、`llm_completion_tokens`、`llm_prompt_tokens_dist`、`llm_completion_tokens_dist`    | `route_id`、`service_id`、`consumer`、`node`、`request_type`、`request_llm_model`、`llm_model`                                                    | 还支持 `route`、`matched_uri`、`matched_host` 和 `service`。                                                                |
| `llm_active_connections`                                                                                | `route`、`route_id`、`matched_uri`、`matched_host`、`service`、`service_id`、`consumer`、`node`、`request_type`、`request_llm_model`、`llm_model` | 标签相同。                                                                                                                  |
| `ai_cache_hits_total`、`ai_cache_misses_total`、`ai_cache_bypasses_total`、`ai_cache_embedding_latency` | `route`、`route_id`、`service`、`service_id`、`consumer`、`node`、`request_type`、`request_llm_model`、`llm_model`                                | 还支持 `matched_uri` 和 `matched_host`。                                                                                    |

本表不包含结构性标签，因为这些标签不能禁用。

在 API7 企业版中，`stream_status` 元数据键可以禁用 `apisix_stream_status` 的 `node` 标签。`code` 和 `listen_addr` 是结构性标签。自 API7 企业版 3.9.19 和 3.10.6 起引入。

在 APISIX 中，使用以下配置禁用 HTTP 状态和延迟指标的 `node` 标签：

```
curl "http://127.0.0.1:9180/apisix/admin/plugin_metadata/prometheus" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "disabled_labels": {

      "http_status": ["node"],

      "http_latency": ["node"]

    }

  }'
```

对于 API7 企业版，请改用 `status` 和 `latency`：

```
{

  "disabled_labels": {

    "status": ["node"],

    "latency": ["node"]

  }

}
```

通过启用了该插件的路由发送请求，然后获取指标端点。受影响的时序应保留 `node` 标签，但其值为空：

```
apisix_http_status{code="200",route="1",matched_uri="/get",matched_host="",service="",consumer="",node="",request_type="traditional_http",request_llm_model="",llm_model="",response_source="upstream"} 1
```

模式会拒绝用于区分不同测量值的结构性标签，包括 HTTP 状态的 `code`，HTTP 延迟、带宽和 LLM 延迟的 `type`，以及 AI Cache 命中的 `layer`。APISIX 与 API7 企业版的可选标签集并不相同；请根据所配置的网关查阅[插件元数据参考](https://docs.apiseven.com/hub/prometheus/configuration.md#plugin-metadata)。

### 在公共 API 端点上暴露 APISIX 指标[​](#在公共-api-端点上暴露-apisix-指标 "在公共 API 端点上暴露 APISIX 指标的直接链接")

以下示例展示了如何禁用默认在端口 `9091` 上暴露端点的 Prometheus 导出服务器，并在 APISIX 用于监听其他客户端请求的端口 `9080` 上的新公共 API 端点上暴露 APISIX Prometheus 指标。

警告

如果收集大量指标，插件可能会占用大量 CPU 资源进行指标计算，并对常规请求的处理产生负面影响。

为了解决这个问题，APISIX 使用 [特权代理（privileged agent）](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/process.md#enable_privileged_agent) 并将指标计算卸载到单独的进程。如果你使用配置文件中配置的指标端点（如 [上文](#%E8%8E%B7%E5%8F%96-apisix-%E6%8C%87%E6%A0%87) 所示），此优化将自动应用。如果你使用 `public-api` 插件暴露指标端点，你将无法从该优化中受益。

要通过 `public-api` 暴露指标，请先禁用默认的 Prometheus 导出服务器：

* Host or Docker
* Kubernetes (Helm)

在网关配置文件中新增或更新以下配置：

config.yaml

```
plugin_attr:

  prometheus:

    enable_export_server: false
```

重新加载网关以使更改生效。

对于 Helm 部署，请更新用于渲染 `plugin_attr.prometheus` 的 Chart values，并保留 values 文件中的其他配置。

对于 APISIX Helm Chart，设置以下 values：

values.yaml

```
apisix:

  pluginAttrs:

    prometheus:

      enable_export_server: false
```

对于 API7 网关 Helm Chart，设置以下 values：

values.yaml

```
pluginAttrs:

  prometheus:

    enable_export_server: false
```

然后使用当前网关 release 对应的 Chart 应用 values 文件：

```
helm upgrade <release-name> <chart-name> -n <namespace> -f values.yaml
```

接下来，创建一个带有 [`public-api`](https://docs.apiseven.com/hub/public-api.md) 插件的路由，并为 APISIX 指标暴露一个公共 API 端点：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "prometheus-metrics",

    "uri": "/prometheus_metrics",

    "plugins": {

      "public-api": {

        "uri": "/apisix/prometheus/metrics"

      }

    }

  }'
```

adc.yaml

```
services:

  - name: prometheus-metrics-service

    routes:

      - uris:

          - /prometheus_metrics

        name: prometheus-metrics

        plugins:

          public-api:

            uri: /apisix/prometheus/metrics

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，并确认变更只影响本指南中的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=prometheus
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=prometheus
```

* Gateway API
* APISIX CRD

prometheus-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  name: httpbin-external-domain

  namespace: aic

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      protocol: TCP

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: prometheus-public-api-config

spec:

  plugins:

    - name: public-api

      config:

        uri: /apisix/prometheus/metrics

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: prometheus-metrics-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /prometheus_metrics

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: prometheus-public-api-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

prometheus-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: prometheus-metrics-route

spec:

  ingressClassName: apisix

  http:

    - name: prometheus-metrics-route

      match:

        paths:

          - /prometheus_metrics

      plugins:

      - name: public-api

        enable: true

        config:

          uri: /apisix/prometheus/metrics
```

将配置应用到集群：

```
kubectl apply -f prometheus-ic.yaml
```

对于此指标路由，`public-api` 会在联系后端之前返回响应。ADC 和 Gateway API 标签页仍包含常规后端。请确认响应中包含指标；仅收到后端响应并不能证明指标处理器已运行。

向新的指标端点发送请求以进行验证：

```
curl "http://127.0.0.1:9080/prometheus_metrics"
```

你应该看到类似于以下的输出：

```
# HELP apisix_http_requests_total The total number of client requests since APISIX started

# TYPE apisix_http_requests_total gauge

apisix_http_requests_total 1

# HELP apisix_nginx_http_current_connections Number of HTTP connections

# TYPE apisix_nginx_http_current_connections gauge

apisix_nginx_http_current_connections{state="accepted"} 1

apisix_nginx_http_current_connections{state="active"} 1

apisix_nginx_http_current_connections{state="handled"} 1

apisix_nginx_http_current_connections{state="reading"} 0

apisix_nginx_http_current_connections{state="waiting"} 0

apisix_nginx_http_current_connections{state="writing"} 1

...
```

### 将 APISIX 与 Prometheus 和 Grafana 集成[​](#将-apisix-与-prometheus-和-grafana-集成 "将 APISIX 与 Prometheus 和 Grafana 集成的直接链接")

要了解如何使用 Prometheus 收集 APISIX 指标并在 Grafana 中将其可视化，请参阅 [操作指南](https://docs.apiseven.com/apisix/how-to-guide/observability/monitor-apisix-with-prometheus.md)。

### 监控上游健康状态[​](#监控上游健康状态 "监控上游健康状态的直接链接")

以下示例展示了如何监控上游节点的健康状态。

创建一个带有 `prometheus` 插件的路由并配置上游主动健康检查：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "prometheus-route",

    "uri": "/get",

    "plugins": {

      "prometheus": {}

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1,

        "127.0.0.1:20001": 1

      },

      "checks": {

        "active": {

          "timeout": 5,

          "http_path": "/status/200",

          "healthy": {

            "interval": 2,

            "successes": 1

          },

          "unhealthy": {

            "interval": 1,

            "http_failures": 2

          }

        },

        "passive": {

          "healthy": {

            "http_statuses": [200, 201],

            "successes": 3

          },

          "unhealthy": {

            "http_statuses": [500],

            "http_failures": 3,

            "tcp_failures": 3

          }

        }

      }

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - uris:

          - /get

        name: prometheus-route

        plugins:

          prometheus: {}

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1

        - host: 127.0.0.1

          port: 20001

          weight: 1

      checks:

        active:

          timeout: 5

          http_path: /status/200

          healthy:

            interval: 2

            successes: 1

          unhealthy:

            interval: 1

            http_failures: 2

        passive:

          healthy:

            http_statuses:

              - 200

              - 201

            successes: 3

          unhealthy:

            http_statuses:

              - 500

            http_failures: 3

            tcp_failures: 3
```

预览变更，并确认变更只影响本指南中的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=prometheus
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=prometheus
```

* Gateway API
* APISIX CRD

prometheus-health-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: healthy-httpbin

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: unhealthy-httpbin

spec:

  type: ExternalName

  externalName: example.com

---

apiVersion: apisix.apache.org/v1alpha1

kind: BackendTrafficPolicy

metadata:

  namespace: aic

  name: healthy-httpbin-health

spec:

  targetRefs:

    - group: ""

      kind: Service

      name: healthy-httpbin

  healthCheck:

    active:

      type: http

      httpPath: /status/200

      timeout: 5s

      healthy:

        interval: 2s

        successes: 1

      unhealthy:

        interval: 1s

        httpFailures: 2

    passive:

      type: http

      healthy:

        httpCodes:

          - 200

          - 201

        successes: 3

      unhealthy:

        httpCodes:

          - 500

        httpFailures: 3

        tcpFailures: 3

---

apiVersion: apisix.apache.org/v1alpha1

kind: BackendTrafficPolicy

metadata:

  namespace: aic

  name: unhealthy-httpbin-health

spec:

  targetRefs:

    - group: ""

      kind: Service

      name: unhealthy-httpbin

  healthCheck:

    active:

      type: http

      httpPath: /status/200

      timeout: 5s

      healthy:

        interval: 2s

        successes: 1

      unhealthy:

        interval: 1s

        httpFailures: 2

    passive:

      type: http

      healthy:

        httpCodes:

          - 200

          - 201

        successes: 3

      unhealthy:

        httpCodes:

          - 500

        httpFailures: 3

        tcpFailures: 3

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: prometheus-plugin-config

spec:

  plugins:

    - name: prometheus

      config: {}

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: prometheus-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /status/200

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: prometheus-plugin-config

      backendRefs:

        - name: healthy-httpbin

          port: 80

          weight: 1

        - name: unhealthy-httpbin

          port: 80

          weight: 1
```

prometheus-health-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Service

    name: healthy-httpbin

    port: 80

  - type: Service

    name: unhealthy-httpbin

    port: 80

  healthCheck:

    active:

      type: http

      httpPath: /status/200

      timeout: 5

      healthy:

        interval: 2s

        successes: 1

      unhealthy:

        interval: 1s

        httpFailures: 2

    passive:

      type: http

      healthy:

        httpCodes:

          - 200

          - 201

        successes: 3

      unhealthy:

        httpCodes:

          - 500

        httpFailures: 3

        tcpFailures: 3

---

apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: healthy-httpbin

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: unhealthy-httpbin

spec:

  type: ExternalName

  externalName: example.com

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: prometheus-route

spec:

  ingressClassName: apisix

  http:

    - name: prometheus-route

      match:

        paths:

          - /get

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: prometheus

        enable: true

        config: {}
```

将配置应用到集群：

```
kubectl apply -f prometheus-health-ic.yaml
```

向 APISIX Prometheus 指标端点发送请求：

```
curl "http://127.0.0.1:9091/apisix/prometheus/metrics"
```

你应该看到类似于以下的输出：

```
# HELP apisix_upstream_status upstream status from health check

# TYPE apisix_upstream_status gauge

apisix_upstream_status{name="/upstreams/<id>",ip="<healthy-node-ip>",port="80"} 1

apisix_upstream_status{name="/upstreams/<id>",ip="<unhealthy-node-ip>",port="80"} 0
```

在该示例输出中，一个上游节点处于健康状态，另一个上游节点处于不健康状态。

要了解有关如何配置主动和被动健康检查的更多信息，请参阅 [健康检查](https://docs.apiseven.com/apisix/how-to-guide/traffic-management/health-check.md)。

### 为指标添加额外标签[​](#add-extra-labels-for-metrics "为指标添加额外标签的直接链接")

以下示例展示了如何向指标添加额外标签并在标签值中使用 [内置变量](https://docs.apiseven.com/apisix/reference/built-in-variables.md)。

目前，只有以下指标支持额外标签：

* `apisix_http_status`
* `apisix_http_latency`
* `apisix_bandwidth`
* 上文列出的所有 `apisix_llm_*` 指标
* 全部四个 `apisix_ai_cache_*` 指标

APISIX 和 API7 网关以相同方式应用额外标签。

标签值的每个不同组合都会创建独立的时间序列。请使用服务或环境等取值集合有限的标签。避免使用请求 ID、API Key、包含查询字符串的完整 URL，以及其他每次请求都可能变化的值。新增标签会成倍增加现有序列，包括每个直方图桶，从而增加网关共享内存占用、抓取大小和 Prometheus 存储需求。

添加标签后，请监控共享内存使用情况。如果持续增长，请先移除或聚合标签，再考虑增大内存限制。API7 网关运维人员还应查看[共享内存容量规划](https://docs.apiseven.com/api7-gateway/configure-and-manage/shared-dict-sizing.md#prevent-metric-dictionary-exhaustion)中的容量规划与恢复说明。

请在 Prometheus 静态配置中添加额外标签：

* Host or Docker
* Kubernetes (Helm)

在网关配置文件中新增或更新以下配置：

config.yaml

```
plugin_attr:

  prometheus:                                # prometheus 插件

    metrics:                                 # 使用内置变量创建额外标签。

      http_status:

        extra_labels:                        # 设置 http_status 指标的额外标签。

          - upstream_addr: $upstream_addr    # 添加 upstream_addr 标签，其值为 NGINX 变量 $upstream_addr。

          - route_name: $route_name          # 添加 route_name 标签，其值为 APISIX 变量 $route_name。
```

重新加载网关以使更改生效。

对于 Helm 部署，请更新用于渲染 `plugin_attr.prometheus.metrics` 的 Chart values，并保留 values 文件中的其他配置。

对于 APISIX Helm Chart，设置以下 values：

values.yaml

```
apisix:

  pluginAttrs:

    prometheus:

      metrics:

        http_status:

          extra_labels:

            - upstream_addr: $upstream_addr

            - route_name: $route_name
```

对于 API7 网关 Helm Chart，设置以下 values：

values.yaml

```
pluginAttrs:

  prometheus:

    metrics:

      http_status:

        extra_labels:

          - upstream_addr: $upstream_addr

          - route_name: $route_name
```

然后使用当前网关 release 对应的 Chart 应用 values 文件：

```
helm upgrade <release-name> <chart-name> -n <namespace> -f values.yaml
```

请注意，如果你在标签值中定义了一个变量，但它不对应任何现有的 [内置变量](https://docs.apiseven.com/apisix/reference/built-in-variables.md)，则标签值将默认为空字符串。

创建一个带有 `prometheus` 插件的路由：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "prometheus-route",

    "uri": "/get",

    "name": "extra-label",

    "plugins": {

      "prometheus": {}

    },

    "upstream": {

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - uris:

          - /get

        name: extra-label

        plugins:

          prometheus: {}

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，并确认变更只影响本指南中的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=prometheus
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=prometheus
```

* Gateway API
* APISIX CRD

prometheus-labels-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: prometheus-plugin-config

spec:

  plugins:

    - name: prometheus

      config: {}

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: prometheus-route

spec:

  parentRefs:

    - name: apisix

  hostnames:

    - "prometheus.example.com"

  rules:

    - matches:

        - path:

            type: Exact

            value: /get

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: prometheus-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

prometheus-labels-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: prometheus-route

spec:

  ingressClassName: apisix

  http:

    - name: prometheus-route

      match:

        hosts:

          - "prometheus.example.com"

        paths:

          - /get

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: prometheus

        enable: true

        config: {}
```

将配置应用到集群：

```
kubectl apply -f prometheus-labels-ic.yaml
```

发送请求到该路由以进行验证：

```
curl -i "http://127.0.0.1:9080/get"
```

你应该看到 `HTTP/1.1 200 OK` 响应。

向 APISIX Prometheus 指标端点发送请求：

```
curl "http://127.0.0.1:9091/apisix/prometheus/metrics"
```

你应该看到类似于以下的输出：

```
# HELP apisix_http_status HTTP status codes per service in APISIX

# TYPE apisix_http_status counter

apisix_http_status{code="200",route="1",matched_uri="/get",matched_host="",service="",consumer="",node="54.237.103.220",request_type="traditional_http",request_llm_model="",llm_model="",response_source="upstream",upstream_addr="54.237.103.220:80",route_name="extra-label"} 1
```

### 使用 Prometheus 监控 TCP/UDP 流量[​](#使用-prometheus-监控-tcpudp-流量 "使用 Prometheus 监控 TCP/UDP 流量的直接链接")

以下示例展示了如何在 APISIX 中收集 TCP/UDP 流量指标。

如需收集 TCP/UDP 指标，请启用 stream proxy，并将 `prometheus` 添加到现有 stream 插件列表中。请保留部署使用的其他 stream 插件；以下主机/Docker 示例展示了本教程所需的最小列表。

* Host or Docker
* Kubernetes (Helm)

在网关配置文件中新增或更新以下配置：

config.yaml

```
apisix:

  proxy_mode: http&stream   # 同时启用 L4 和 L7 代理

  stream_proxy:             # 配置 L4 代理

    tcp:

      - 9100                # 设置 TCP 代理监听端口

    udp:

      - 9200                # 设置 UDP 代理监听端口



stream_plugins:

  - prometheus              # 为 stream proxy 启用 prometheus
```

重新加载网关以使更改生效。

对于 APISIX Helm Chart，请配置 stream listener，并包含希望网关加载的完整 stream plugin 列表。以下示例保留默认 stream plugins 并加入 `prometheus`：

values.yaml

```
service:

  stream:

    enabled: true

    tcp:

      - 9100

    udp:

      - 9200

apisix:

  stream_plugins:

    - ip-restriction

    - limit-conn

    - mqtt-proxy

    - prometheus

    - syslog
```

对于 API7 网关 Helm Chart，设置以下 values：

values.yaml

```
gateway:

  stream:

    enabled: true

    tcp:

      - addr: 9100

    udp:

      - addr: 9200
```

然后使用当前网关 release 对应的 Chart 应用 values 文件：

```
helm upgrade <release-name> <chart-name> -n <namespace> -f values.yaml
```

在 API7 企业版中，stream 插件列表由控制面下发。上面的 values 已经足够，无需配置其他部署形态中展示的 `stream_plugins`。

创建一个启用了 `prometheus` 插件的[流路由](https://docs.apiseven.com/apisix/key-concepts/stream-routes.md)：

```
curl "http://127.0.0.1:9180/apisix/admin/stream_routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "prometheus-route",

    "plugins": {

      "prometheus":{}

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

发送请求到该流路由以进行验证：

```
curl -i "http://127.0.0.1:9100"
```

你应该看到 `HTTP/1.1 200 OK` 响应。

向 APISIX Prometheus 指标端点发送请求：

```
curl "http://127.0.0.1:9091/apisix/prometheus/metrics"
```

你应该看到类似于以下的输出：

```
# HELP apisix_stream_connection_total Total number of connections handled per stream route in APISIX

# TYPE apisix_stream_connection_total counter

apisix_stream_connection_total{route="prometheus-route",service="",service_id=""} 1
```

APISIX 还会导出终止状态。如果 APISIX-Runtime 提供 stream-metrics 模块，抓取结果还会包含活动连接和带宽：

```
# HELP apisix_stream_active_connections Number of stream sessions currently being proxied per listening address and service

# TYPE apisix_stream_active_connections gauge

apisix_stream_active_connections{listen_addr="0.0.0.0:9100",service="",service_id=""} 0

# HELP apisix_stream_status Stream sessions per termination status in APISIX

# TYPE apisix_stream_status counter

apisix_stream_status{code="200",listen_addr="0.0.0.0:9100",service="",service_id="",node="54.237.103.220:80"} 1

# HELP apisix_stream_bandwidth Total bandwidth in bytes proxied by the stream subsystem in APISIX

# TYPE apisix_stream_bandwidth counter

apisix_stream_bandwidth{listen_addr="0.0.0.0:9100",service="",service_id="",type="ingress",side="downstream"} 78

apisix_stream_bandwidth{listen_addr="0.0.0.0:9100",service="",service_id="",type="egress",side="downstream"} 219

apisix_stream_bandwidth{listen_addr="0.0.0.0:9100",service="",service_id="",type="egress",side="upstream"} 78

apisix_stream_bandwidth{listen_addr="0.0.0.0:9100",service="",service_id="",type="ingress",side="upstream"} 219
```

此示例中的路由不属于任何服务，因此 `service` 和 `service_id` 为空。具体上游地址和字节数取决于请求。上例中的活动连接 gauge 为 `0`，因为请求在抓取前已完成；请在连接保持打开时进行抓取，以观察正值。

活动连接和带宽指标使用默认大小为 `1m` 的共享内存区域，约可容纳 750 个槽位。每个 stream 监听地址占用一个槽位，该地址上出现的每个服务再占用一个槽位。按服务分配的槽位自 APISIX 3.20.0 以及 API7 Enterprise 3.9.22 和 3.10.9 起引入。

当网关暴露大量 stream 监听地址或承载大量 stream 服务时，请增大该区域：

config.yaml

```
nginx_config:

  stream:

    metrics_zone_size: 2m
```

更改区域大小后，请重新加载 APISIX。在没有 stream-metrics 模块的运行时中，APISIX 会继续导出连接总数和状态指标，但不会发布活动连接或带宽指标。
