@aws-blocks/bb-metrics

中文文档
0.2.0发布于 2026/11/02Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 6.3万

Custom application metrics backed by Amazon CloudWatch (via Embedded Metric Format).

原始使用文档
文档目录17 节
  1. API
  2. Options
  3. EmitOptions
  4. MetricUnit
  5. Error Handling
  6. Examples
  7. Basic Usage
  8. Emit with Dimensions
  9. Batch Emit
  10. Child Emitters (Scoped Dimensions)
  11. Wrapping an Existing Namespace
  12. High-Resolution Metrics
  13. CDK Configuration
  14. Synchronous API Rationale
  15. Best Practices
  16. Scaling & Cost (AWS)
  17. Local Development

Metrics

Custom application metrics backed by Amazon CloudWatch (via Embedded Metric Format).

When to use: You need to track numeric measurements over time — request counts, error rates, latency, queue depths, business KPIs. Good for dashboards, alarms, and operational visibility.

When NOT to use: If you need structured log output, use Logging. If you need distributed request tracing, use Tracing. If you need to store time-series data for querying, use Database or DistributedTable.

Design & mock parity details: DESIGN.md

API

const metrics = new Metrics(scope, id, options?)
MethodReturnsDescription
emit(name, value, options?)voidRecord a single metric data point via EMF.
emitBatch(metrics)voidRecord multiple metric data points in one EMF document (max 100).
flush()voidNo-op (EMF writes are immediate). Provided for interface compatibility.
child(dimensions)MetricsEmitterCreate a child emitter with inherited namespace and merged dimensions.
Metrics.fromExisting(namespace)ExternalMetricsRefWrap a pre-existing CloudWatch namespace.

Options

OptionTypeDescription
namespacestringCloudWatch namespace. Defaults to scope.fullId.
defaultDimensionsRecord<string, string>Dimensions applied to every emit. Per-emit dimensions merge on top (per-emit wins on conflict).
metricsExternalMetricsRefWrap an existing CloudWatch namespace instead of creating one. When set, namespace is ignored.
loggerChildLoggerOptional logger for internal operations. When omitted, a default Logger at error level is created.

EmitOptions

OptionTypeDescription
unitMetricUnitUnit of the metric value. Defaults to 'None'.
dimensionsRecord<string, string>Dimensions for this data point (max 30 total including defaults).
timestampDateTimestamp for the data point. Defaults to now.
resolutionMetricResolution'standard' (60s, default) or 'high' (1s, higher cost).

MetricUnit

type MetricUnit =
  | 'Count' | 'Seconds' | 'Milliseconds' | 'Microseconds'
  | 'Bytes' | 'Kilobytes' | 'Megabytes' | 'Gigabytes'
  | 'Percent' | 'Bits/Second' | 'None';

Error Handling

import { isBlocksError } from '@aws-blocks/core';
import { MetricsErrors } from '@aws-blocks/bb-metrics';

try {
  metrics.emit('', 1);
} catch (e: unknown) {
  if (isBlocksError(e, MetricsErrors.InvalidMetricName)) {
    // metric name is empty or exceeds 1024 characters
  }
}
ErrorCondition
MetricsErrors.InvalidMetricNameMetric name is empty or exceeds 1024 characters.
MetricsErrors.InvalidDimensionsDimensions exceed 30 entries, or contain empty keys/values, or key/value exceeds 1024 chars.
MetricsErrors.BatchTooLargeBatch contains more than 100 metrics.
MetricsErrors.InvalidNamespaceNamespace is empty, too long, contains invalid characters, or uses reserved AWS/ prefix.

Examples

Basic Usage

import { Scope, ApiNamespace } from '@aws-blocks/blocks';
import { Metrics } from '@aws-blocks/bb-metrics';

const scope = new Scope('my-app');
const metrics = new Metrics(scope, 'appMetrics', {
  namespace: 'MyApp/Orders',
  defaultDimensions: { service: 'orders' },
});

export const api = new ApiNamespace(scope, 'api', (context) => ({
  async handleRequest() {
    metrics.emit('RequestCount', 1, { unit: 'Count' });
    metrics.emit('Latency', 42, { unit: 'Milliseconds' });
    return { ok: true };
  },
}));

Emit with Dimensions

metrics.emit('RequestCount', 1, {
  unit: 'Count',
  dimensions: { endpoint: '/api/users', method: 'GET' },
});

Batch Emit

metrics.emitBatch([
  { name: 'RequestCount', value: 1, unit: 'Count' },
  { name: 'Latency', value: 42, unit: 'Milliseconds' },
  { name: 'ErrorCount', value: 0, unit: 'Count' },
]);

Child Emitters (Scoped Dimensions)

const requestMetrics = metrics.child({ endpoint: '/api/users', method: 'GET' });
requestMetrics.emit('RequestCount', 1);
requestMetrics.emit('Latency', 35, { unit: 'Milliseconds' });

Children inherit the parent's namespace and default dimensions, merging their own on top. Children can be nested arbitrarily.

Wrapping an Existing Namespace

const legacy = new Metrics(scope, 'legacy', {
  metrics: Metrics.fromExisting('MyOrg/SharedMetrics'),
});
legacy.emit('MigrationCount', 1);

High-Resolution Metrics

metrics.emit('CPUSpike', 95.2, {
  unit: 'Percent',
  resolution: 'high', // 1-second aggregation
});

CDK Configuration

The CDK construct creates no AWS resources. It only resolves and exposes the namespace and defaultDimensions as readonly properties for CDK-time consumers.

EMF uses CloudWatch Logs (which Lambda already has permissions for), so no environment variable or cloudwatch:PutMetricData IAM grant is needed. CloudWatch namespaces are created implicitly on first metric data point arrival.

Synchronous API Rationale

All metric methods return void, not Promise<void>. This is intentional:

  • EMF writes to stdout — process.stdout.write() is a synchronous, non-blocking call on Linux. The kernel buffers the write and Lambda's logging agent captures it asynchronously.
  • No network I/O — Unlike PutMetricData (which makes an HTTP call to CloudWatch), EMF piggybacks on CloudWatch Logs, which Lambda already streams. There is nothing to await.
  • Zero overhead — Returning a Promise would add microtask scheduling overhead for zero benefit. Metrics should be as cheap as a console.log.
  • Fire-and-forget semantics — Metrics are observability data, not business-critical writes. If a metric fails to emit (e.g., stdout is closed), it should not crash the request.

This design means you can emit metrics anywhere — in hot loops, synchronous callbacks, or error handlers — without worrying about async context or unhandled promise rejections.

Best Practices

  • Keep dimension cardinality low (avoid user IDs or request IDs as dimensions)
  • Use consistent metric names across your application
  • Use defaultDimensions for shared context (service name, environment)
  • Prefer emitBatch when recording multiple metrics in a single request
  • Use units to enable automatic conversions in CloudWatch dashboards
  • Use child() to avoid repeating dimensions across related metrics

Scaling & Cost (AWS)

  • Ingestion: CloudWatch accepts unlimited metrics via EMF — no API call limits
  • Standard resolution (60s): Retained for 15 days at full resolution, then aggregated
  • High resolution (1s): Retained for 3 hours at full resolution, then aggregated
  • Cost: Scales with unique metric name + dimension combinations (~$0.30/metric/month)
  • Latency: EMF adds zero latency to the request (stdout write is non-blocking)

Local Development

Metrics are written as EMF JSON to stdout — the same format as AWS. In local dev, you can see metric emissions in the terminal output. No disk persistence — metrics are ephemeral locally (unlike KVStore or DistributedTable which persist to .bb-data/).

Delete nothing to reset — there's no local state to clear.

版本与发布记录

@aws-blocks/bb-metrics 共发布 14 个版本,首次发布于 2026/06/16;过去 12 个月发布了 14 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.2.0latest2026/11/025 天前
0.1.92026/10/1622 天前
0.0.0-canary.esql-canary.c93c81b.1791235863canary-esql-canary2026/10/061 个月前
0.1.82026/10/051 个月前
0.0.0-canary.esql-canary.f7f39ac.17909891272026/10/031 个月前
0.0.0-canary.ci-publish-canary-npm.f53dfdc.1790988617canary-ci-publish-canary-npm2026/10/031 个月前

关于 @aws-blocks/bb-metrics 的常见问题

@aws-blocks/bb-metrics 是什么?

Custom application metrics backed by Amazon CloudWatch (via Embedded Metric Format).

如何安装 @aws-blocks/bb-metrics?

在项目目录运行 npm install @aws-blocks/bb-metrics,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:constructs(^10.6.0)、aws-cdk-lib(^2.257.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aws-blocks/bb-metrics 支持 TypeScript 吗?

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

@aws-blocks/bb-metrics 支持 ESM 还是 CommonJS?

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

@aws-blocks/bb-metrics 可以商用吗?

@aws-blocks/bb-metrics 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aws-blocks/bb-metrics 的下载量有多少?

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

@aws-blocks/bb-metrics 还在维护吗?

最新版本 0.2.0 发布于 2026/11/02(5 天前);至今共发布 14 个版本,其中过去 12 个月发布了 14 个;首次发布于 2026/06/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。