@aws-blocks/bb-tracer

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

Distributed tracing backed by AWS X-Ray.

原始使用文档
文档目录10 节
  1. Installation
  2. Quick Usage
  3. API
  4. Segment Methods
  5. Options
  6. Best Practices
  7. Local Development
  8. Sampling
  9. Pricing
  10. See Also

Tracer

Distributed tracing backed by AWS X-Ray.

Fleet-wide + cost: tracing is presence-gated — constructing any Tracer in the app enables X-Ray Active mode on every compute (X-Ray is billed per trace recorded/retrieved). enabled: false on a Tracer only removes that Tracer's opt-in; if any other Tracer exists, X-Ray still turns on fleet-wide.

When to use: You need to trace request flow across services, debug latency issues, or visualize service dependencies. Good for identifying bottlenecks, understanding call chains, and correlating failures across Building Blocks.

When NOT to use: If you need structured log output, use Logging. If you need numeric measurements over time, use Metrics.

Design & mock parity details: DESIGN.md

Installation

npm install @aws-blocks/bb-tracer

Quick Usage

import { Tracer } from '@aws-blocks/bb-tracer';

const tracer = new Tracer(scope, 'my-tracer');

// Wrap an operation in a traced segment
const user = await tracer.startSegment('fetchUser', async (segment) => {
  segment.addAnnotation('userId', 'user-123');
  const result = await db.get('user-123');
  segment.setHttpStatus(200);
  return result;
});

// Add root-level annotations (attached to the Lambda facade segment)
tracer.addAnnotation('endpoint', '/api/users');

// Get the current trace ID for log correlation
const traceId = tracer.getTraceId();

API

const tracer = new Tracer(scope, id, options?)
MethodReturnsDescription
startSegment(name, fn)Promise<T>Wrap an async function in a traced subsegment. The segment is automatically closed when fn completes or throws.
addAnnotation(key, value)voidAdd a searchable annotation to the root segment.
addMetadata(key, value)voidAdd non-searchable metadata to the root segment.
getTraceId()string | nullGet the current trace ID for log correlation. Returns null when disabled.

Segment Methods

The segment object passed to startSegment's callback:

MethodDescription
addAnnotation(key, value)Add a searchable annotation (string, number, or boolean).
addMetadata(key, value)Add non-searchable metadata (any JSON-serializable value).
addError(error)Record an error without re-throwing.
setHttpStatus(statusCode)Record HTTP response status code.

Options

OptionTypeDefaultDescription
enabledbooleantrueEnable or disable tracing. When false, startSegment still executes the wrapped function.
samplingRatenumber1.0Sampling rate between 0 and 1. Only affects local mock behavior.
loggerChildLogger—Optional logger for internal operations. When omitted, a default Logger at error level is created.

Best Practices

  • Use startSegment to wrap discrete units of work (DB calls, HTTP requests, business logic)
  • Keep segment names short and descriptive (e.g., 'fetchUser', 'processPayment')
  • Use annotations for values you want to filter/search by in the X-Ray console
  • Use metadata for large or complex debugging data you don't need to search
  • Keep annotation cardinality low (avoid user-specific values as annotation keys)
  • Use AsyncJob for long-running work rather than tracing huge spans

Local Development

Mock data persists to disk at .bb-data/{fullId}/traces.json across dev server restarts. Nested segments are stored as a tree (children array). Wipe with rm -rf .bb-data.

The mock records all traces locally with full timing, annotations, metadata, and error data — matching the shape of what X-Ray would capture in production.

Sampling

  • Local (mock): Controlled by the samplingRate option. A value of 0.1 means roughly 10% of local traces are recorded. Default is 1.0 (record everything).
  • Production (AWS): Sampling is controlled by X-Ray sampling rules configured in the AWS console or via CDK. The samplingRate option is ignored in production — X-Ray's native sampling infrastructure takes precedence.

Pricing

  • Free tier: 100,000 traces recorded per month, 1,000,000 traces scanned/retrieved per month
  • Beyond free tier: $5.00 per million traces recorded, $0.50 per million traces retrieved or scanned
  • Lambda daemon: No additional charge — the X-Ray daemon is built into the Lambda runtime
  • Cost drivers: Number of traced invocations × sampling rate
  • Cost optimization: Configure X-Ray sampling rules to keep recorded-trace volume (and cost) low for high-throughput functions (the samplingRate option only affects the local mock, not production)
  • Disabled (enabled: false): Zero X-Ray cost — no traces are recorded or sent

See Also

  • Types — Shared type definitions (Segment, TracerOptions, AnnotationValue)

版本与发布记录

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

版本发布日期距今
0.3.0latest2026/11/025 天前
0.2.22026/10/1622 天前
0.0.0-canary.esql-canary.c93c81b.1791235863canary-esql-canary2026/10/061 个月前
0.2.12026/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-tracer 的常见问题

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

Distributed tracing backed by AWS X-Ray.

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

在项目目录运行 npm install @aws-blocks/bb-tracer,或使用 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-tracer 支持 TypeScript 吗?

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

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

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

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

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

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

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

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

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