custom-metrics
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseVercel 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 → invoke the deployed function → discover and query the metric with or Observability.
metric()vc metrics使用 Custom Metrics 记录由 Vercel Function 中运行的服务端代码发出的数值型应用和业务测量数据。工作流是:使用 发出数值样本 → 调用已部署的函数 → 使用 或 Observability 发现并查询指标。
metric()vc metricsEmit a metric
发出指标
Install or upgrade , then import from its root entry point:
@vercel/functionsmetricbash
pnpm add @vercel/functionsts
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- identifies one stable measurement, such as
nameororders.created.orders.duration_ms - is the numeric sample. Emit
valuefor an increment that will be summed; emit the observed value for a duration, size, or score.1 - are optional string attributes. After ingestion, discovered tag keys appear as dimensions for filtering and grouping.
tags - is synchronous and returns
metric(); do notvoidit.await - 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/functionsmetricbash
pnpm add @vercel/functionsts
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 prefix for application-defined names.
vercel. - Keep variable data in tags instead of metric names. Use with
checkout.completed, not{ plan: 'pro' }.checkout.completed.pro - Keep tag cardinality bounded. Good tags are ,
outcome,plan, or a normalized route. Do not attach user IDs, request IDs, email addresses, raw URLs, or other unique or sensitive values.provider - 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:
| Measurement | Emit | Query |
|---|---|---|
| Occurrence or increment | | |
| Duration or size | | |
| Sampled level | | |
- 优先使用稳定且以点分隔的名称,并在有帮助时添加单位后缀,例如 、
checkout.completed、checkout.duration_ms。queue.batch_size - 不要将保留的 前缀用于应用定义的名称。
vercel. - 将可变数据保存在标签中,而不是指标名称中。使用 和
checkout.completed,不要使用{ plan: 'pro' }。checkout.completed.pro - 控制标签基数。合适的标签包括 、
outcome、plan或规范化的路由。不要附加用户 ID、请求 ID、电子邮箱地址、原始 URL 或其他唯一或敏感的值。provider - 在结果确定的位置发出一个样本。对于可重试或至少执行一次的工作,应确定要衡量的是尝试次数还是成功的逻辑操作,并相应地命名指标。
根据发出的数据选择查询聚合方式:
| 测量类型 | 发出方式 | 查询方式 |
|---|---|---|
| 出现次数或增量 | | |
| 时长或大小 | | |
| 采样水平 | | |
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=jsonvcvercelvc metrics schema <name>-S <team>-p <project>--allCustom Metrics querying requires Observability Plus and availability for the selected team. If a metric is missing:
- Confirm the function was deployed to Vercel and the instrumented path actually ran.
- Confirm exports
@vercel/functions; upgrade it if necessary.metric - Check , the selected team, and the linked project.
vc whoami - Allow for ingestion delay, then rerun .
vc metrics schema - 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=jsonvcvercelvc metrics schema <name>-S <team>-p <project>--all查询 Custom Metrics 需要 Observability Plus,并且所选团队必须具备该功能。如果缺少某个指标:
- 确认函数已部署到 Vercel,并且埋点路径确实执行过。
- 确认 导出了
@vercel/functions;必要时进行升级。metric - 检查 、所选团队和已关联的项目。
vc whoami - 考虑数据摄取延迟,然后重新运行 。
vc metrics schema - 确认团队已启用 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 配对使用。