custom-metrics

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vercel Custom Metrics

Vercel Custom Metrics

Use Custom Metrics for numeric application and business measurements emitted by server-side code running in a Vercel Function. The workflow is emit a numeric sample with
metric()
→ invoke the deployed function → discover and query the metric with
vc metrics
or Observability
.
使用 Custom Metrics 记录由 Vercel Function 中运行的服务端代码发出的数值型应用和业务测量数据。工作流是:使用
metric()
发出数值样本 → 调用已部署的函数 → 使用
vc metrics
或 Observability 发现并查询指标
。

Emit a metric

发出指标

Install or upgrade
@vercel/functions
, then import
metric
from its root entry point:
bash
pnpm add @vercel/functions
ts
import { metric } from '@vercel/functions';

export async function POST() {
  const startedAt = performance.now();

  try {
    await createOrder();
    metric('orders.created', 1, { outcome: 'success' });
    return Response.json({ ok: true });
  } catch (error) {
    metric('orders.created', 1, { outcome: 'error' });
    throw error;
  } finally {
    metric('orders.duration_ms', performance.now() - startedAt);
  }
}
The signature is:
ts
metric(name: string, value: number, tags?: Record<string, string>): void
  • name
    identifies one stable measurement, such as
    orders.created
    or
    orders.duration_ms
    .
  • value
    is the numeric sample. Emit
    1
    for an increment that will be summed; emit the observed value for a duration, size, or score.
  • tags
    are optional string attributes. After ingestion, discovered tag keys appear as dimensions for filtering and grouping.
  • metric()
    is synchronous and returns
    void
    ; do not
    await
    it.
  • The helper is a no-op when the runtime does not expose Custom Metrics support. Verify instrumentation through a deployed Vercel Function invocation, not local execution alone.
安装或升级
@vercel/functions
,然后从其根入口导入
metric
:
bash
pnpm add @vercel/functions
ts
import { metric } from '@vercel/functions';

export async function POST() {
  const startedAt = performance.now();

  try {
    await createOrder();
    metric('orders.created', 1, { outcome: 'success' });
    return Response.json({ ok: true });
  } catch (error) {
    metric('orders.created', 1, { outcome: 'error' });
    throw error;
  } finally {
    metric('orders.duration_ms', performance.now() - startedAt);
  }
}
函数签名如下:
ts
metric(name: string, value: number, tags?: Record<string, string>): void
  • name
    标识一个稳定的测量项,例如
    orders.created
    或
    orders.duration_ms
    。
  • value
    是数值样本。对于将被求和的增量,发出
    1
    ;对于时长、大小或分数,则发出观测到的值。
  • tags
    是可选的字符串属性。摄取数据后,发现的标签键会显示为可用于筛选和分组的维度。
  • metric()
    是同步函数,返回
    void
    ;不要
    await
    它。
  • 当运行时未提供 Custom Metrics 支持时,该辅助函数不会执行任何操作。应通过调用已部署的 Vercel Function 来验证埋点,而不能只依赖本地执行。

Model metrics for useful queries

为便于查询而设计指标

  • Prefer stable, dotted names with a unit suffix where useful:
    checkout.completed
    ,
    checkout.duration_ms
    ,
    queue.batch_size
    .
  • Do not use the reserved
    vercel.
    prefix for application-defined names.
  • Keep variable data in tags instead of metric names. Use
    checkout.completed
    with
    { plan: 'pro' }
    , not
    checkout.completed.pro
    .
  • Keep tag cardinality bounded. Good tags are
    outcome
    ,
    plan
    ,
    provider
    , or a normalized route. Do not attach user IDs, request IDs, email addresses, raw URLs, or other unique or sensitive values.
  • Emit one sample at the point where the outcome is known. For retryable or at-least-once work, decide whether attempts or successful logical operations are the intended measurement and name the metric accordingly.
Choose the query aggregation to match what was emitted:
MeasurementEmitQuery
Occurrence or increment
metric('checkout.completed', 1)
sum
or
persecond
Duration or size
metric('checkout.duration_ms', duration)
avg
,
p75
,
p95
,
max
Sampled level
metric('queue.batch_size', size)
avg
,
min
,
max
, percentiles
  • 优先使用稳定且以点分隔的名称,并在有帮助时添加单位后缀,例如
    checkout.completed
    、
    checkout.duration_ms
    、
    queue.batch_size
    。
  • 不要将保留的
    vercel.
    前缀用于应用定义的名称。
  • 将可变数据保存在标签中,而不是指标名称中。使用
    checkout.completed
    和
    { plan: 'pro' }
    ,不要使用
    checkout.completed.pro
    。
  • 控制标签基数。合适的标签包括
    outcome
    、
    plan
    、
    provider
    或规范化的路由。不要附加用户 ID、请求 ID、电子邮箱地址、原始 URL 或其他唯一或敏感的值。
  • 在结果确定的位置发出一个样本。对于可重试或至少执行一次的工作,应确定要衡量的是尝试次数还是成功的逻辑操作,并相应地命名指标。
根据发出的数据选择查询聚合方式:
测量类型发出方式查询方式
出现次数或增量
metric('checkout.completed', 1)
sum
或
persecond
时长或大小
metric('checkout.duration_ms', duration)
avg
、
p75
、
p95
、
max
采样水平
metric('queue.batch_size', size)
avg
、
min
、
max
、百分位数

Discover and query the metric

发现并查询指标

Run the deployed code at least once, then use the linked project and correct team scope:
bash
vc metrics schema
vc metrics schema orders.duration_ms

vc metrics orders.created -a sum --group-by outcome --since 24h
vc metrics orders.duration_ms -a p95 --since 1h
vc metrics orders.duration_ms -a p95 --group-by outcome --since 24h --format=json
vc
and
vercel
are equivalent. Always inspect the exact metric first with
vc metrics schema <name>
because the schema reports the available aggregations and discovered tag dimensions. Use
-S <team>
and
-p <project>
when the current link or scope is ambiguous; use
--all
only for a deliberate team-wide query.
Custom Metrics querying requires Observability Plus and availability for the selected team. If a metric is missing:
  1. Confirm the function was deployed to Vercel and the instrumented path actually ran.
  2. Confirm
    @vercel/functions
    exports
    metric
    ; upgrade it if necessary.
  3. Check
    vc whoami
    , the selected team, and the linked project.
  4. Allow for ingestion delay, then rerun
    vc metrics schema
    .
  5. Confirm Observability Plus and Custom Metrics are enabled for the team.
至少运行一次已部署的代码,然后使用已关联的项目和正确的团队范围:
bash
vc metrics schema
vc metrics schema orders.duration_ms

vc metrics orders.created -a sum --group-by outcome --since 24h
vc metrics orders.duration_ms -a p95 --since 1h
vc metrics orders.duration_ms -a p95 --group-by outcome --since 24h --format=json
vc
和
vercel
是等效的。始终先使用
vc metrics schema <name>
检查确切的指标,因为 schema 会报告可用的聚合方式和发现的标签维度。当当前关联或范围不明确时,使用
-S <team>
和
-p <project>
;仅在有意进行团队级查询时使用
--all
。
查询 Custom Metrics 需要 Observability Plus,并且所选团队必须具备该功能。如果缺少某个指标:
  1. 确认函数已部署到 Vercel,并且埋点路径确实执行过。
  2. 确认
    @vercel/functions
    导出了
    metric
    ;必要时进行升级。
  3. 检查
    vc whoami
    、所选团队和已关联的项目。
  4. 考虑数据摄取延迟,然后重新运行
    vc metrics schema
    。
  5. 确认团队已启用 Observability Plus 和 Custom Metrics。

Use the right signal

选择合适的信号类型

  • Use Custom Metrics for numeric values you want to aggregate, trend, and filter.
  • Use Web Analytics custom events for user interaction and conversion events in Web Analytics.
  • Use OpenTelemetry spans for traces, operation timing, and request causality.
  • Use logs for detailed diagnostic context and individual records.
Do not encode detailed event payloads into metric tags. Pair a low-cardinality metric with structured logs or traces when investigation needs per-request detail.
  • 使用 Custom Metrics 记录需要聚合、趋势分析和筛选的数值。
  • 使用 Web Analytics 自定义事件 记录 Web Analytics 中的用户交互和转化事件。
  • 使用 OpenTelemetry span 记录 trace、操作计时和请求因果关系。
  • 使用 日志 记录详细的诊断上下文和单条记录。
不要将详细的事件载荷编码到指标标签中。当调查需要每个请求的详细信息时,将低基数指标与结构化日志或 trace 配对使用。