<!-- review: finished -->

<a id="custom-metrics-config"></a>

# 自定义指标配置

Angie 可以在共享内存中收集自定义数值指标，并通过实时 [统计 API](https://cn.angie.software//angie/docs/configuration/modules/http/http_api.md#metrics) 在 `/status/http/metric_zones/` 公开它们。这由 [Metric](https://cn.angie.software//angie/docs/configuration/modules/http/http_metric.md#http-metric) 模块提供。

<a id="configuration-steps-1"></a>

## 配置步骤

1. 在 `http` 块中定义指标区域：
   - [metric_zone](https://cn.angie.software//angie/docs/configuration/modules/http/http_metric.md#metric-zone) 创建具有单个指标模式的区域。
   - [metric_complex_zone](https://cn.angie.software//angie/docs/configuration/modules/http/http_metric.md#metric-complex-zone) 创建具有多个命名指标的区域。
2. 使用 [metric](https://cn.angie.software//angie/docs/configuration/modules/http/http_metric.md#id5) 指令在请求处理中更新指标。
   使用 `key=value` 对（两者都是 [复杂值](https://cn.angie.software//angie/docs/configuration/configfile.md#syntax)），并使用 `on=` 选择更新阶段（`request`、`response` 或 `end`）。
3. 使用 `location` 公开 API：
   ```nginx
   location /status/ {
       api /status/http/metric_zones/;
   }
   ```

<a id="example"></a>

## 示例

统计每个主机的请求数并在 API 中公开指标：

```nginx
http {
    metric_zone requests:128k count;

    server {
        listen 80;

        location / {
            metric requests $host=1;
        }

        location /status/ {
            api /status/http/metric_zones/;
        }
    }
}
```

<a id="notes"></a>

## 注意事项

- 如果在区域上设置了 `expire=on` 且共享内存已满，则最近最少使用的条目将过期。如果设置了 `expire=off`，新的更新将被丢弃，`discarded` 计数器会增长。
- 如果设置了 `discard_key`，过期条目的指标将在 API 输出中聚合到该键下。
- 键和值限制为 255 字节；较长的键在 API 中会被截断。
- 空值被视为 `0`，没有前导数字的非空值被视为 `1`。
