@btravstack/observability

中文文档
0.58.0发布于 2026/11/08MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 8367

Observability for @btravstack/core: a strict Logger port correlated with the kernel's units, a dependency-free JSON sink, and the lifecycle events as log lines

原始使用文档
文档目录5 节
  1. A worked example
  2. What makes the interface strict
  3. Swapping the implementation
  4. Traces and metrics
  5. License

@btravstack/observability

Observability for @btravstack/core, starting with logging: a strict Logger port — no any, no printf, no mutable context, no static instance — a default implementation that stamps every line with the ambient unit's trace id, a dependency-free JSON sink, pino behind a subpath, and the kernel's ten lifecycle events as log lines in the same stream.

📖 Documentation · How-to · API Reference

pnpm add @btravstack/observability @btravstack/core @btravstack/config @btravstack/di unthrown

Those four are peers. pino is an optional peer, needed only if you import @btravstack/observability/pino. Node >=22.

A worked example

import { runMain, Logger } from "@btravstack/core";
import {
  createLogger,
  jsonSink,
  kernelEvents,
  observability,
} from "@btravstack/observability";
import { Module, Provider } from "@btravstack/di";

// The application depends on the port, like any other service.
const placeOrder = Provider(PlaceOrder)({
  inject: { orders: OrderRepository, logger: Logger },
  sync: ({ orders, logger }) => ({
    execute: (id, quantity) =>
      orders
        .save({ id, quantity })
        .tap(() => logger.info("order placed", { id, quantity })),
  }),
});

// The starter provides it. `LOG_LEVEL` is read inside the graph and validated
// once — `verbose` is a startup failure naming the variable, not a silent
// fallback to `info`.
const OrderApi = HttpModule("OrderApi")({
  router: orderRouter,
  imports: [
    OrdersSlice,
    CustomersSlice,
    cache({ adapter: redisCache() }),
    observability(),
    otel(),
  ],
});

// The kernel's own events, in the same stream and the same shape. The logger
// here is built by hand because `building` is emitted while the graph still
// is: the sink cannot come from the context it is watching.
await runMain(OrderApi, { onEvent: kernelEvents(createLogger(jsonSink())) });

Every line written inside a unit carries that unit's traceId, unitId and tenantId — the logger reads currentUnit() per call, so one application-scope logger is correct for every request without a single argument threaded through the call stack.

{
  "orderId": "0199a1e0-0000-7000-8000-000000000001",
  "time": "2026-08-16T09:41:02.113Z",
  "level": "info",
  "message": "order placed",
  "unitId": "u-7",
  "traceId": "3f9c…"
}

What makes the interface strict

DecisionWhy
A port, never a class or a staticA test provides its own; there is no global to reach past DI with
with(attributes) returns a loggerNothing mutates: two scopes cannot interleave each other's context
Attributes is a flat record of scalarsThe shape a log backend indexes; no any, no printf, no stringifying whatever it is handed
A failure goes in causeAn Error's message and stack are non-enumerable — JSON.stringify alone drops exactly the part worth keeping
It cannot throwA broken sink is swallowed: an observability fault must not become an outage
Six levels, fixedLOG_LEVEL is validated at startup, and isEnabled is a comparison

Swapping the implementation

observability({ sink }) replaces the destination; providing Logger yourself replaces everything. For a deployment that wants pino's throughput:

import pino from "pino";
import { pinoSink } from "@btravstack/observability/pino";

observability({ sink: pinoSink(pino()) });

The child logger uses a trace floor and leaves the supplied logger unchanged. The level filter stays this package's — LOG_LEVEL, validated once — so there is one filter in the process rather than two that can disagree.

Both JSON and Pino sinks retain safe error diagnostics and omit arbitrary error payloads. Pino's error serializer is installed on a child logger at trace, leaving the supplied logger's configuration intact.

A configured production policy also projects ambient unit, trace and tenant correlation before custom sinks and starter-owned spans see it. UUIDs and nonzero W3C trace IDs survive; free text does not. Unconfigured legacy rendering and explicitly sensitive debugging keep their existing disclosure behavior.

For production data minimization, pass a shared diagnosticPolicy() through observability({ diagnostics }), otel({ diagnostics }) and Temporal's installTemporalDiagnostics. Without this explicit policy, error messages, stacks and bounded cause chains remain visible. See the disclosure policy reference for allowlists and the separate sensitive-debug access and retention contract.

Traces and metrics

The other half of the package's name, behind an optional-peer subpath the way pino is:

pnpm add @opentelemetry/api @opentelemetry/sdk-node
import { observability } from "@btravstack/observability";
import { UnitSpanModule, otel } from "@btravstack/observability/otel";

// Beside observability() in the root's imports; the SDK is a resource of the
// graph — started with the scope, flushed by release on every exit path.
// Configuration is the OTEL_* environment conventions, read by the SDK itself.
const AppImports = [observability(), otel()];

// A span per unit, correlated with the same ids the logger stamps — bound on
// the starter's own `unit` option and forked by the runtime around each
// request, delivery or activity attempt, e.g.
// http({ unit: { anonymous: UnitSpanModule } })

Inbound W3C traceparent feeds the unit's trace id in @btravstack/http-server and @btravstack/amqp-worker. Auto-instrumentation must be preloaded (node --import @opentelemetry/auto-instrumentations-node/register) — it cannot be a provider, and the package does not pretend otherwise. Full semantics on the reference page.

License

MIT © Benoit TRAVERS

版本与发布记录

@btravstack/observability 共发布 62 个版本,首次发布于 2026/08/26;过去 12 个月发布了 62 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.58.0latest2026/11/08今天
0.57.02026/11/071 天前
0.56.12026/11/062 天前
0.56.02026/11/062 天前
0.55.12026/11/035 天前
0.55.02026/11/035 天前

关于 @btravstack/observability 的常见问题

@btravstack/observability 是什么?

Observability for @btravstack/core: a strict Logger port correlated with the kernel's units, a dependency-free JSON sink, and the lifecycle events as log lines

如何安装 @btravstack/observability?

在项目目录运行 npm install @btravstack/observability,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:unthrown(^5.0.0)、@btravstack/di(^0.58.0)、@btravstack/core(^0.58.0)、@btravstack/config(^0.58.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@btravstack/observability 支持 TypeScript 吗?

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

@btravstack/observability 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@btravstack/observability 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@btravstack/observability 可以商用吗?

@btravstack/observability 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@btravstack/observability 的下载量有多少?

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

@btravstack/observability 还在维护吗?

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