@crossdelta/telemetry

中文文档
0.13.2发布于 2026/05/24MITTypeScriptESM + CJS近 30 天下载 4033

OpenTelemetry instrumentation for CrossDelta services

原始使用文档
文档目录15 节
  1. Getting Started
  2. 1. Install
  3. 2. Import (first line!)
  4. 3. Set environment variables
  5. Usage
  6. Hono services (Bun)
  7. Logging
  8. Qwik apps
  9. Custom initialization
  10. Runtime Support
  11. Supported Backends
  12. API Reference
  13. Essential
  14. Advanced
  15. License

@crossdelta/telemetry

npm version License: MIT TypeScript OpenTelemetry

OpenTelemetry instrumentation for TypeScript services on Bun and Node.js.

Getting Started

1. Install

bun add @crossdelta/telemetry

2. Import (first line!)

import '@crossdelta/telemetry'

import { Hono } from 'hono'

The import must come before everything else to properly patch modules.

3. Set environment variables

OTEL_SERVICE_NAME=my-service
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://otlp-gateway.grafana.net/otlp/v1/traces
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://otlp-gateway.grafana.net/otlp/v1/logs
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://otlp-gateway.grafana.net/otlp/v1/metrics
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic base64(instanceId:apiKey)

If no endpoint is configured, telemetry stays disabled with zero overhead.

Usage

Hono services (Bun)

Wire instrumentMiddleware() to get per-request spans, HTTP metrics, and log context. Every console.* call within a request automatically includes requestId, traceId, path, and method in Grafana.

import '@crossdelta/telemetry'
import { instrumentMiddleware } from '@crossdelta/telemetry/middleware'
import { Hono } from 'hono'

const app = new Hono()
app.use('*', instrumentMiddleware())

Per request this creates:

  • An OTEL server span (http.method, http.target, http.status_code)
  • An http.server.request.duration histogram entry
  • ALS context with requestId, traceId, spanId, path, method for log correlation

The W3C traceparent header is propagated automatically, so all downstream services share the same traceId. NATS CloudEvents carry trace context via @crossdelta/cloudevents.

On Node.js (NestJS/Express), HttpInstrumentation handles spans and metrics automatically. instrumentMiddleware() only sets up the ALS context there.

Logging

For most cases, plain console.* works. The OTEL patch captures everything and attaches trace context automatically.

console.info('[ORDER:CREATED]', orderId)
console.error('[PAYMENT:FAILED]', reason)

For queryable key-value attributes in Grafana:

import { logInfo, logError } from '@crossdelta/telemetry/logger'

await logInfo('Order created', { orderId, total, tenantId })
await logError('Payment failed', { orderId, reason, provider })

Qwik apps

import { initRequestContext } from '@crossdelta/telemetry/logger'

export const onRequest: RequestHandler = async (ev) => {
  const requestId = initRequestContext(ev)
  ev.headers.set('X-Request-Id', requestId)
}

Custom initialization

For non-default settings, use initTelemetry() instead of the side-effect import:

import { initTelemetry } from '@crossdelta/telemetry'

initTelemetry({
  metricsIntervalMs: 30_000,
  onShutdown: async () => {
    await database.close()
  },
})

Runtime Support

All signals (logs, metrics, traces) work on both runtimes. The difference is how HTTP spans and metrics are created:

FeatureNode.jsBun
HTTP spansauto (HttpInstrumentation)instrumentMiddleware()
HTTP metrics (http.server.request.duration)auto (HttpInstrumentation)instrumentMiddleware()
Express/NestJS tracingYesNo

Supported Backends

Grafana Cloud, Better Stack, Jaeger — any OTLP endpoint works.

API Reference

Essential

ExportFromDescription
import '@crossdelta/telemetry'.Auto-initialize SDK (side-effect import)
instrumentMiddleware()./middlewareHono middleware: server span, HTTP metrics, ALS context, X-Request-Id header
logInfo(msg, data?)./loggerStructured info log with ALS context
logWarn(msg, data?)./loggerStructured warning log with ALS context
logError(msg, data?)./loggerStructured error log with ALS context
logDebug(msg, data?)./loggerStructured debug log with ALS context
initRequestContext(event)./loggerSet up per-request ALS context. Returns requestId.
logger./loggerUniversal logger object (server: Pino+ALS, client: console)

Advanced

ExportFromDescription
initTelemetry(config?).Manual SDK initialization with custom options
shutdownTelemetry().Flush pending data and shut down the SDK
getSDK().Get the current NodeSDK instance (or null)
extractTraceparent(request)./traceparentParse W3C traceparent header from a Request
parseTraceparent(header)./traceparentParse a W3C traceparent string
buildTraceparent(context)./traceparentBuild a W3C traceparent header from trace context
getCurrentTraceparent()./traceparentGet current traceparent from ALS or OTEL active span
runWithTraceparent(header, fn)./traceparentRun a function inside a trace context derived from a traceparent header
runWithLogContext(context, fn)./loggerRun a function inside a custom ALS context
buildRequestLogContext(req, url)./loggerBuild a LogContext Map from a Request
getLogContext()./loggerRead current ALS context as a plain object
withLogging(name, fn, opts?)./loggerWrap async function with auto error + slow-call logging
serializeError(error)./loggerSerialize Error to { err, errName, stack, cause }

In production, set OTEL_* vars via your secrets manager or CI/CD.

License

MIT

版本与发布记录

@crossdelta/telemetry 共发布 23 个版本,首次发布于 2025/12/04;过去 12 个月发布了 23 个版本。

版本发布日期距今
0.13.2latest2026/05/245 个月前
0.13.12026/04/256 个月前
0.13.02026/04/256 个月前
0.11.12026/04/256 个月前
0.11.02026/04/196 个月前
0.9.12026/04/116 个月前

关于 @crossdelta/telemetry 的常见问题

@crossdelta/telemetry 是什么?

OpenTelemetry instrumentation for CrossDelta services

如何安装 @crossdelta/telemetry?

在项目目录运行 npm install @crossdelta/telemetry,或使用 pnpm add / yarn add / bun add。

@crossdelta/telemetry 支持 TypeScript 吗?

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

@crossdelta/telemetry 支持 ESM 还是 CommonJS?

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

@crossdelta/telemetry 可以商用吗?

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

@crossdelta/telemetry 的下载量有多少?

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

@crossdelta/telemetry 还在维护吗?

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