@aient/otel

中文文档
2.2.2发布于 2026/10/27MITTypeScriptES Module零依赖近 30 天下载 1.9万

Aient wrapper around OpenTelemetry APIs

原始使用文档
文档目录12 节
  1. Quick Start (3 lines)
  2. Local Development
  3. Custom Endpoint (programmatic)
  4. Full Example (all options)
  5. Environment Variables
  6. OTLP JSON protocol contract
  7. Build Metadata (required for source mapping)
  8. Manual Spans & Logs
  9. Recording external-service failures on the active span
  10. Defaults
  11. Request telemetry
  12. License

@aient/otel

OpenTelemetry for Node.js/Next.js/Edge. Works out of the box, highly configurable.

Quick Start (3 lines)

npm install @aient/otel @opentelemetry/api @opentelemetry/api-logs
// instrumentation.ts (Next.js 13.4+)
import { registerOTel } from '@aient/otel'

export function register() {
  registerOTel({ serviceName: 'my-app' })
}

Browser-propagated app.installation.id, enduser.id, and enduser.pseudo.id are untrusted correlation hints. @aient/otel projects only those safe browser identity fields, then applies attributesFromHeaders, so a gateway/session-derived trusted enduser.id wins. Never map a freely client-set header as trusted identity, and never authorize from baggage.

Done. Traces go to https://ingest.aient.ai/v1/traces by default, logs to /v1/logs.

Local Development

For local development with a collector on localhost, set the env var:

OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318

Custom Endpoint (programmatic)

To set the endpoint in code instead of env vars, use exporterUrl:

registerOTel({
  serviceName: 'my-app',
  exporterUrl: 'https://my-collector.example.com', // SDK appends /v1/traces and /v1/logs
  exporterHeaders: { 'x-api-key': 'your-key' },    // optional custom headers
})

Full Example (all options)

import { registerOTel, OTLPHttpJsonTraceExporter, OTLPHttpJsonLogsExporter } from '@aient/otel'
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'
import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'

export function register() {
  registerOTel({
    // Identity
    serviceName: 'my-app',
    attributes: {
      'app.version': process.env.npm_package_version,
    },

    // Release metadata (CRITICAL for source mapping)
    // Config takes precedence over env vars (COMMIT_SHA, COMMIT_REF, etc.)
    release: {
      commit: process.env.COMMIT_SHA,
      branch: process.env.COMMIT_REF,
      version: '1.0.0',
      environment: 'production',
    },

    // Aient auth (or set AIENT_PUBLISHABLE_KEY env var)
    publishableKey: process.env.AIENT_PUBLISHABLE_KEY,

    // Extract request context
    attributesFromHeaders: {
      'enduser.id': 'x-user-id',
      'tenant.id': 'x-tenant-id',
      'client.ip': 'x-forwarded-for',
    },

    // Sampling (10% in production)
    traceSampler: 'parentbased_traceidratio',

    // Error handling
    captureUnhandledErrors: true,
    exitOnUnhandledException: true,
    flushTimeoutMs: 2000,

    // Custom endpoint (alternative to OTEL_EXPORTER_OTLP_ENDPOINT env var)
    exporterUrl: 'https://collector.example.com',
    exporterHeaders: { 'x-api-key': 'your-key' },

    // Debug logging (alternative to OTEL_LOG_LEVEL env var)
    logLevel: 'DEBUG',  // 'ALL' | 'VERBOSE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'NONE'

    // Multi-backend fan-out (advanced - overrides exporterUrl)
    // spanProcessors: [
    //   new BatchSpanProcessor(new OTLPHttpJsonTraceExporter({
    //     url: 'https://collector-a.example.com/v1/traces',
    //   })),
    //   new BatchSpanProcessor(new OTLPHttpJsonTraceExporter({
    //     url: 'https://collector-b.example.com/v1/traces',
    //   })),
    // ],
  })
}
# Set sampling ratio
OTEL_TRACES_SAMPLER_ARG=0.1

Environment Variables

Configure via env instead of code:

# Endpoints
OTEL_EXPORTER_OTLP_ENDPOINT=https://collector.example.com  # Base URL
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://traces.example.com/v1/traces
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://logs.example.com/v1/logs

# Protocol
OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/json
OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=http/json
# Legacy http/protobuf values are accepted for compatibility but fall back to JSON.

# Headers
OTEL_EXPORTER_OTLP_HEADERS=x-api-key=secret,env=prod

# Sampling
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1

# Service
OTEL_SERVICE_NAME=my-service
OTEL_SDK_DISABLED=true  # Kill switch

# Aient auth
AIENT_PUBLISHABLE_KEY=pk_xxx

OTLP JSON protocol contract

The SDK exports traces and logs as OTLP/HTTP JSON protobuf payloads with Content-Type: application/json.

The serializer follows the OTLP JSON mapping used by the OpenTelemetry protocol:

  • request envelopes are ExportTraceServiceRequest and ExportLogsServiceRequest JSON objects (resourceSpans and resourceLogs);
  • JSON field names are lowerCamelCase, for example startTimeUnixNano and droppedAttributesCount;
  • trace IDs and span IDs are hex strings, not base64;
  • 64-bit timestamps and integer attribute values are decimal strings;
  • enum fields such as span kind, span status, and log severity are encoded as numbers;
  • arbitrary byte attributes are base64 strings;
  • spans and logs are grouped by resource and instrumentation scope, including schema URLs when present.

@aient/otel does not bundle protobufjs, @opentelemetry/otlp-transformer, @opentelemetry/otlp-exporter-base, or @opentelemetry/exporter-trace-otlp-http. Protocol-sensitive serializer behavior is covered by test/otlp-json-serializer.test.ts, and dependency regressions are covered by test/package-contract.test.ts.


Build Metadata (required for source mapping)

Set commit info for Aient to map errors to code. Use either the release config option or environment variables:

Via config (recommended):

registerOTel({
  serviceName: 'my-app',
  release: {
    commit: process.env.COMMIT_SHA,
    branch: process.env.COMMIT_REF,
    version: '1.0.0',
    environment: 'production',
  }
})

Via environment variables:

COMMIT_SHA=$(git rev-parse HEAD)
COMMIT_REF=$(git rev-parse --abbrev-ref HEAD)
BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

Also reads VERCEL_GIT_COMMIT_SHA, NEXT_PUBLIC_COMMIT_SHA, etc.


Manual Spans & Logs

import { trace } from '@opentelemetry/api'
import { logs, SeverityNumber } from '@opentelemetry/api-logs'

// Spans
const tracer = trace.getTracer('my-component')
const span = tracer.startSpan('operation')
span.setAttribute('key', 'value')
span.end()

// Logs
const logger = logs.getLogger('my-component')
logger.emit({
  severityNumber: SeverityNumber.INFO,
  body: 'User signed up',
  attributes: { plan: 'pro' },
})

Recording external-service failures on the active span

When integrating with third-party systems (GitHub, Slack, Stripe, Linear, email providers, etc), prefer attaching the failure reason to the current active span so traces are self-explanatory.

import { recordExternalFailure, recordExternalFailureReason } from '@aient/otel'

// When you have an Error/exception:
try {
  await doExternalCall()
} catch (e) {
  recordExternalFailure({
    system: 'github',
    operation: 'listInstallationRepos',
    error: e,
    attributes: {
      'aient.external.http.status_code': 404,
      'aient.external.installation_id': 123,
    },
  })
  throw e
}

// When you only have a protocol-level error string (no exception thrown):
recordExternalFailureReason({
  system: 'slack',
  operation: 'chat.postMessage',
  reason: 'not_in_channel',
  attributes: { 'aient.external.slack.channel': 'C123...' },
})

Notes:

  • Both helpers set span status to ERROR, attach aient.external.* attributes, and emit an exception event.
  • aient.external.organisation_id is diagnostic customer context. Authenticated source tenant and environment remain collector-owned resource attributes (aient.organisation.id and aient.environment.*).
  • Historical telemetry retains its original attribute keys; raw attribute inspection remains available.
  • recordExternalFailureReason does not synthesize an Error/stacktrace (to avoid misleading stacks).

Defaults

FeatureDefault
Trace exporterhttp/json → https://ingest.aient.ai/v1/traces
Log exporterhttp/json → https://ingest.aient.ai/v1/logs
Sampleralways_on
PropagatorsW3C Trace Context + Baggage
Instrumentationsfetch, Node http/https
Error captureuncaughtException, unhandledRejection → log + flush + exit
Request telemetrystable HTTP attributes, redacted queries, one access log per inbound request

Request telemetry

Every inbound request's outermost server span carries OpenTelemetry's stable HTTP server attributes, also when the framework only emits legacy names (Next.js): http.request.method, url.path, url.query, url.scheme, http.route, http.response.status_code, server.address, server.port, client.address, user_agent.original, http.request.header.referer, network.protocol.version, http.response.body.size and error.type. Request-header attributes come from the platform request context (Vercel) or from the HTTP server instrumentation.

Each request produces one log record (scope @aient/otel/http) with those attributes, http.server.request.duration in seconds, and the span's trace and span IDs. The message is <method> <route or path> <status>. Severity: ERROR for 5xx, WARN for 4xx, otherwise INFO. The http.server.request.duration histogram is recorded when you configure metricReaders. Outbound fetch spans get the stable client attributes but no access log.

Query values of credential keys become REDACTED in url.query, url.full, http.target, http.url, and referrer attributes (http.referer and http.request.header.referer); keys and other values stay. The same referrer policy applies to application log request context. Defaults: OpenTelemetry's signature keys plus access_token, refresh_token, id_token, client_secret, api_key, apikey, password and token.

registerOTel({
  httpRequestTelemetry: {
    sensitiveQueryParameters: ["sig", "token", "session"], // replaces the defaults
    knownMethods: ["GET", "POST", "PURGE"], // or OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS
    accessLogs: true, // default
  },
})

Next.js on Vercel needs nothing more. For other Node servers (self-hosted Next.js, Express, Fastify, NestJS, plain http), register the standard HTTP server instrumentation so client address, user agent, referer and response size exist:

import { HttpInstrumentation } from "@opentelemetry/instrumentation-http";

registerOTel({
  instrumentations: ["auto", new HttpInstrumentation({
    headersToSpanAttributes: { server: { requestHeaders: ["referer"], responseHeaders: ["content-length"] } },
  })],
});

License

MIT

版本与发布记录

@aient/otel 共发布 7 个版本,首次发布于 2026/04/03;过去 12 个月发布了 7 个版本。

版本发布日期距今
2.2.2latest2026/10/2711 天前
2.2.02026/10/2712 天前
2.1.12026/10/1524 天前
2.1.02026/08/013 个月前
2.0.02026/05/076 个月前
1.0.12026/04/146 个月前

关于 @aient/otel 的常见问题

@aient/otel 是什么?

Aient wrapper around OpenTelemetry APIs

如何安装 @aient/otel?

在项目目录运行 npm install @aient/otel,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@opentelemetry/api(>=1.9.0 <3.0.0)、@opentelemetry/api-logs(>=0.200.0 <0.300.0)、@opentelemetry/sdk-logs(>=0.200.0 <0.300.0)、@opentelemetry/resources(>=2.0.0 <3.0.0)、@opentelemetry/sdk-metrics(>=2.0.0 <3.0.0)、@opentelemetry/sdk-trace-base(>=2.0.0 <3.0.0)、@opentelemetry/instrumentation(>=0.200.0 <0.300.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aient/otel 支持 TypeScript 吗?

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

@aient/otel 支持 ESM 还是 CommonJS?

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

@aient/otel 需要什么版本的 Node.js?

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

@aient/otel 可以商用吗?

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

@aient/otel 的下载量有多少?

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

@aient/otel 还在维护吗?

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