@aws-blocks/bb-logger

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

Structured logging with consistent JSON format, log levels, and contextual metadata.

原始使用文档
文档目录14 节
  1. When to Use
  2. When NOT to Use
  3. Quick Start
  4. API
  5. Constructor
  6. Methods
  7. Log Entry Format
  8. Child Loggers
  9. Log Level Precedence
  10. Error Object Handling
  11. Serialization Safety
  12. Retention (Production)
  13. Local Development
  14. Errors

@aws-blocks/bb-logger

Structured logging with consistent JSON format, log levels, and contextual metadata.

Design & mock parity details: DESIGN.md

When to Use

  • You need structured, queryable application logs
  • You want consistent log format across your backend
  • You need request-scoped loggers with correlation IDs
  • You want log level filtering without code changes

When NOT to Use

  • For numeric measurements over time → use Metrics
  • For distributed request tracing → use Tracing

Quick Start

import { Scope } from '@aws-blocks/core';
import { Logger } from '@aws-blocks/bb-logger';

const scope = new Scope('my-app');
const log = new Logger(scope, 'app');

log.info('Server started', { port: 3000 });
log.warn('Slow query', { durationMs: 1500 });
log.error('Request failed', { err: new Error('timeout') });

API

Constructor

new Logger(scope: ScopeParent, id: string, options?: LoggingOptions)

Options:

  • level — Minimum log level ('debug' | 'info' | 'warn' | 'error'). Default: 'info'.
  • defaultContext — Fields included in every log entry.

Log retention is not a Logger option — it is a compute-level setting (see Retention below).

Methods

log.debug(message: string, context?: Record<string, unknown>): void
log.info(message: string, context?: Record<string, unknown>): void
log.warn(message: string, context?: Record<string, unknown>): void
log.error(message: string, context?: Record<string, unknown>): void
log.child(context: Record<string, unknown>): ChildLogger

All log methods are synchronous (no await needed).

Log Entry Format

Every log entry is a JSON object written to stdout (or stderr for errors):

{
  "level": "info",
  "message": "User logged in",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "logger": "app",
  "userId": "user-123"
}

Child Loggers

Create request-scoped loggers that inherit context:

const requestLog = log.child({ requestId: 'req-abc', userId: 'u-123' });
requestLog.info('Processing request');
// Output includes requestId and userId automatically

Children can be nested:

const dbLog = requestLog.child({ component: 'database' });
dbLog.warn('Slow query', { table: 'users', durationMs: 500 });

Log Level Precedence

  1. Constructor level option
  2. Default: 'info'

Set the level per Logger via the level option. There is no LOG_LEVEL env var — log level is a runtime construction-time choice.

Error Object Handling

Error instances passed in context are automatically extracted:

try {
  await doSomething();
} catch (err) {
  log.error('Operation failed', { err });
  // err is serialized as { name, message, stack }
}

Serialization Safety

The logger handles edge cases gracefully:

  • Circular references → replaced with "[Circular]"
  • BigInt values → converted to string
  • Functions/Symbols → replaced with "[unserializable]"
  • Errors in context → extracted to { name, message, stack }

Retention (Production)

Logging is always on, and retention is a compute-level setting — not a Logger option. Every compute captures its handler's stdout to its own CloudWatch log group, which carries the stack-wide default retention (defaults.logRetention — one week in sandbox, one year in production).

To change retention, set logRetention on the stack-wide defaults (it applies to every compute's handler log group):

import { BlocksPresets } from '@aws-blocks/core/cdk';
import { RetentionDays } from 'aws-cdk-lib/aws-logs';

// In your aws-blocks backend, override the preset's logRetention:
defaults: { ...BlocksPresets.production, logRetention: RetentionDays.ONE_MONTH };

A Logger no longer reconfigures retention — the compute owns the single, framework-owned handler log group. Per-compute retention (a logRetention prop on the compute) arrives with the public compute-configuration surface; until then, defaults.logRetention is the retention knob.

Local Development

In local dev (npm run dev), the Logger BB:

  • Writes structured JSON to stdout/stderr (same as production)
  • Does NOT persist logs to disk
  • Does NOT create any files in .bb-data/
  • Retention has no local effect (it is a cloud-only, compute-level setting)
  • Log level comes from the Logger's level option (default 'info')

Errors

import { LoggingErrors } from '@aws-blocks/bb-logger';

LoggingErrors.SerializationFailed // 'SerializationFailedException'

This error is used as a marker in degraded log entries when context serialization fails (not thrown to consumers).

版本与发布记录

@aws-blocks/bb-logger 共发布 14 个版本,首次发布于 2026/06/16;过去 12 个月发布了 14 个版本。最新版本附带 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-logger 的常见问题

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

Structured logging with consistent JSON format, log levels, and contextual metadata.

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

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

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

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

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

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

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

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

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

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

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