# @balena/node-metrics-gatherer 中文文档

规范地址：https://npmcn.com/package/%40balena/node-metrics-gatherer/

版本：8\.0\.4
npm 元数据更新时间：2026-11-02T23:21:06.019Z
中文译文更新时间：2026-11-07T15:43:41.146Z
软件包许可：ISC

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40balena/node-metrics-gatherer
原文对照：https://npmcn.com/package/%40balena/node-metrics-gatherer/?lang=original
项目主页：https://github.com/balena-io-modules/node-metrics-gatherer#readme
源码仓库：https://github.com/balena-io-modules/node-metrics-gatherer

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：97.9 kB，39 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：^24 \|\| \>=26
- 运行依赖：5 个
- peer 依赖：@types/express ^4\.17\.21 \|\| ^5\.0\.0
- 首次发布：2019-01-22T00:02:23.607Z
- 最新版本发布：2026-11-02T23:21:05.665Z
- 近 30 天下载量：13485（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：182（近 12 个月 37 个）

## 中文简介

很容易在节点中收集/导出 propetheus 度量衡

## 安装

```sh
npm install @balena/node-metrics-gatherer
```

也可以使用：`pnpm add @balena/node-metrics-gatherer`、`yarn add @balena/node-metrics-gatherer`、`bun add @balena/node-metrics-gatherer`

## README

# 节点测量-采集器

以简单的语法来收集并曝光 propetheus 度量衡

## 图表

[![diagram of module](https://docs.google.com/drawings/d/e/2PACX-1vQV0WH1tpJJR_nm1FkIEUMwX2-0QNUZY-j9ArDtJ3MUyrDGnzvWm-e8J6CNmpD72V5uzttocdNUcRBD/pub?w=984&h=407)](https://docs.google.com/drawings/d/1BvUjCTtYJNlS9GIFXnfMcNjkt2m1Le_j80btPTLiarE/edit?usp=sharing)

## 基本用途:

### 写入指标

基本用法包括增加一进一行.

```
import { metrics } from '@balena/node-metrics-gatherer';

...

// inside some loop which checks sensors...
metrics.gauge('temperature', 28);
```

### 导出指标(简单)

然后,你需要确保 当一个请求到达时, 测量标准可以被满足. 这个库不依赖于运行时的快件 - 而是提供一个 请求您在您的快速应用程序上挂载的处理器( 或您的专用应用程序) 仅为度量衡创建 :

```
// create a request handler to respond to prometheus pulls, and mount it on
// your express app
app.use('/metrics', metrics.requestHandler());

// OR, create a dedicated app just for metrics (using port 9337, arbitrarily)
import express from 'express';
express().use('/metrics', metrics.requestHandler()).listen(9337);
```

可以选择,您可以提供一种功能,以验证请求是否应当 通过返回布林(一种"AuthFunc"):

```
const authFunc = (req) => req.get('Authorization') === 'Basic 123456';
app.use('/metrics', metrics.requestHandler(authFunc));
```

## 出口指标(组)

如果一个申请叉了几个童工 他们各自听 `:80/metrics`,每个工人都会有随机的被打的机会,每次只输出自己的指标,造成不稳定和混乱. 谢天谢地, [`@prometheus-io/client`](https://github.com/prometheus/client_js) 提供了处理的方法,您在叉后创建一个注册。 在内部,它处理工人与主要过程之间的信息传递,其中的衡量标准是汇总的。 这个 `example/` 文件夹在 repo 中有一个实例。 这需要单独创建一个快捷的应用程序,在不参与工人集群集合的端口上监听.

每个工人必须选择通过呼叫进行汇总 `metrics.aggregateRequestWorker()`否则,初级将无法收集其衡量标准,而总请求将暂停。 在初级进程本身中记录的任何衡量标准也包含在总产出中.

见下文实例:

(任意选择的港口9337)

```
if (cluster.isPrimary) {
    for (let i = 0; i < 4; i++) {
        cluster.fork();
    }
    express()
        .use('/cluster_metrics', metrics.aggregateRequestHandler())
        .listen(9337);
} else {
    metrics.aggregateRequestWorker();
}
```

### 一个警告 `metrics.describe` 和节点 `cluster` 模块

当你打给 `metrics.describe.counter()` (或 `metrics.describe.histogram()`页:1 ,则全球登记对象将随该指标的描述而更新。 如果你打电话 `metrics.describe.counter()` {\\fn黑体\\fs20\\shad2\\2ah82\\3ah20\\4ah33\\fscx95\\3ch592001\\be1}在主的面前,我们开始 工人内部的登记册将没有标准定义,因为你可以写 不首先描述它,这意味着它将 简单的所有默认,而不是 您的自定义描述,标签,桶,百分位等...

为了避免这种情况,应说明衡量标准 _在工人将遵循的密码路径内_, (中文(简体) ), 以便全球登记对象在工人中将有一个指标性说明.

## 计量类型

见 [波斯文文档](https://prometheus.io/docs/concepts/metric_types/)

作为方法调用(如:, `metrics.summary`)对应 至普罗米修斯度量衡类型(如普罗米修斯"概要")

### 高盖

用来记录一个可以随时间而变化的值,比如温度.

```
metrics.gauge('greenhouse_temperature', temp [, labelObject ]);
```

#### 计数器

用来记录单调计数器的增量,就像所送达的请求一样.

```
metrics.counter('requests_served_total', 1 [, labelObject ]);
```

#### 内容提要

用于计算(预定义)数据流上的等分数.

```
metrics.summary('db_query_duration_milliseconds', queryTime, [, labelObject ]);
```

#### 直方图

用于计算一串数据流上的直方图.

```
metrics.histogram('db_query_duration_milliseconds', queryTime, [, labelObject ]);
```

#### 直方图摘要

有一种观察直方图和摘要的方便方法,它将 后缀 `_hist` 财务报告和审定财务报表 `_summary` 对度量衡.

```
metrics.histogramSummary('db_query_duration_milliseconds', queryTime, [, labelObject ]);
```

## 标签

标签可用于在计量中添加一些更细颗粒性:

```
metrics.counter('application_deployments_total', 1, { app: userRequest.appId, method: 'git-push' });
metrics.counter('application_deployments_total', 1, { app: userRequest.appId, method: 'balena-cli-push' });
```

您必须使用您打算在每次通话中附加的全套标签; 例如,你不能有一行添加标签 `{ method: 'git-push' }` 和另一个 线条添加标签 `{ result: 'success' }`。标签应用于那些 应用到每次引用的度量( 如“ 未知” 等值的精确使用) 或者“默认”可以处理你可能认为不该添加标签的案件.

### 标签和时间序列

节制使用标签 - 每对标签名称将创建一个时间序列 / 您创建的值 。 创建一个跟踪源IP的标签是不好的,例如, 除非你真的确定 tsdb 能处理它.

比如说 我们有两个标签, `A` 财务报告和审定财务报表 `B`,他们可以有价值 `[x, y]`,以及 `[q, r, s]`分别是: 然后会出现以下时间序列:

```
A=x, B=q
A=x, B=r
A=x, B=s
A=y, B=q
A=y, B=r
A=y, B=s
```

## 说明

描述可以用来向 propetheus / 客户端库告知度量:

### 帮助文本

量子描述调用至少指定了计量的种类,名称,以及描述:

```
metrics.describe.histogram(
    'api_request_duration_milliseconds',
    'histogram of total time taken to service requests to the api including queue wait (all queues and all userAgents together)',
);
```

### 定义标签集

此处还将指定标签:

```
metrics.describe.histogram(
    'api_request_duration_milliseconds',
    'histogram of total time taken to service requests to the api including queue wait (all queues and all userAgents together)',
    {
        labelNames: ['requestType']
    },
);
```

### 直方图桶和简略百分比

也可以声明直方图型计量的桶或汇总型计量的百分位数,如果您希望它们与默认不同:

**直方图桶**

```
metrics.describe.histogram(
    'api_request_duration_milliseconds',
    'histogram of total time taken to service requests to the api including queue wait',
    {
        buckets: [4, 10, 100, 500, 1000, 5000, 15000, 30000],
        labelNames: ['queue', 'userAgent'],
    },
);
```

**百分位数**

```
metrics.describe.summary(
    'api_request_duration_milliseconds',
    'summary of total time taken to service requests to the api including queue wait',
    {
        percentiles: [0.9, 0.99, 0.999, 0.9999, 0.99999],
        labelNames: ['queue', 'userAgent'],
    },
);
```

### 分组汇总战略

有几个汇总战略: `@prometheus-io/client`是因为 `ClusterRegistry` 可以用来合并下列记录的度量衡: `cluster` 工人们。 它们是:

-   总和
-   第一个
-   分钟
-   最大数
-   平均数
-   删除

(你可以看到他们是如何工作 在源 [`@prometheus-io/client/lib/metricAggregators.js`](https://github.com/prometheus/client_js/blob/master/lib/metricAggregators.js)(中文(简体) )

为了控制聚合策略( 如果未指定则默认为 “ sum” ) 对于给定的度量,你可以提供 `aggregator` 属性改为 `describe()` 哪个 将确定集合登记册在多个集群时使用的方法 工人给这个指标写信.

这么说吧,我们造了4个工人,每个工人都观察到 一定数量的连接 在一次活动中, 写入一个 Gauge 类型的度量 :

```
on('connect', () => {
    nConnections++;
    metrics.gauge('active_connections', nConnections);
});
on('disconnect', () => {
    nConnections--;
    metrics.gauge('active_connections', nConnections);
});
```

我们可能会满足于默认汇总行为(即: (a) 与每个工人的个人结果之和) 活动连接.

但是,如果我们想知道有多少人与 最忙的工人正在处理, 以衡量最忙的工人有多远 偏离平均值(即 `total / nWorkers`我们也可以 记录一个测量仪,该测量仪已被描述与 `max` 汇总战略:

```
metrics.describe.gauge(
    'active_connections_max',
    'the number of connections being handled by the busiest worker',
    {
        aggregator: 'max'
    }
);

...

on('connect', () => {
    nConnections++;
    metrics.gauge('active_connections', nConnections);
    metrics.gauge('active_connections_max', nConnections);
});
on('disconnect', () => {
    nConnections--;
    metrics.gauge('active_connections', nConnections);
    metrics.gauge('active_connections_max', nConnections);
});
```

### 内部错误

调用此库时发生错误, 如果 `DEBUG` env var 被定义,MetricsGatherer对象的公有财产将被递增: `internalErrorCount`。 。 。 .

## 常见问题

### @balena/node-metrics-gatherer 是什么？

很容易在节点中收集/导出 propetheus 度量衡

### 如何安装 @balena/node-metrics-gatherer？

在项目目录运行 npm install @balena/node-metrics-gatherer，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@types/express（^4\.17\.21 \|\| ^5\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @balena/node-metrics-gatherer 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @balena/node-metrics-gatherer 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @balena/node-metrics-gatherer 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js ^24 \|\| \>=26。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @balena/node-metrics-gatherer 可以商用吗？

@balena/node-metrics-gatherer 使用 ISC 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @balena/node-metrics-gatherer 的下载量有多少？

根据 npm 官方下载统计，@balena/node-metrics-gatherer 在 2026/10/08 – 2026/11/06 这 30 天内被下载 13,485 次，日均约 450 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @balena/node-metrics-gatherer 还在维护吗？

最新版本 8\.0\.4 发布于 2026/11/03（4 天前）；至今共发布 182 个版本，其中过去 12 个月发布了 37 个；首次发布于 2019/01/22。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

