@amplication/opentelemetry-nestjs

中文文档
7.0.0发布于 2026/10/03MITTypeScriptCommonJS零依赖近 30 天下载 1.4万

OpenTelemetry module for Nestjs with auto instrumentation and resource detection. Initially forked from https://github.com/overbit/opentelemetry-nestjs.git

原始使用文档
文档目录25 节
  1. Description
  2. Installation
  3. Setup
  4. Usage
  5. @Span
  6. @Traceable
  7. Tracer
  8. TraceService
  9. Auto Trace Instrumentation
  10. Instrumented components
  11. Manual Tracing for Non-Injectable Classes
  12. Metrics
  13. Starting the OpenTelemetry SDK
  14. startNestJsOpenTelemetrySDK(configuration)
  15. nodeAutoInstrumentationReduceNoise()
  16. nodeAutoInstrumentationHttpReduceIncoming(options?)
  17. nestjsContextManager()
  18. nestjsTextMapPropagator()
  19. nestjsResourceDetectors()
  20. mergeInstrumentationConfigMap(target, source)
  21. Examples
  22. AWS X-Ray/CloudWatch
  23. Migrating from v6.x to v7.x
  24. Migrating from v5.x to v6.x
  25. Quick Summary of Changes

NestJS OpenTelemetry

This library, originally forked from @overbit/opentelemetry-nestjs, provides seamless OpenTelemetry integration for NestJS applications, including automatic tracing and metrics.

Description

Designed for NestJS, a protocol-agnostic framework, this library works across HTTP, GRPC, RabbitMQ, and other protocols. It enables deep observability of NestJS-specific layers, including Controllers, Guards, Interceptors, Pipes, and Providers.

Additionally, it provides automatic trace and metric instrumentation for widely-used NestJS libraries, helping you monitor and analyze your application with minimal configuration.

Installation

npm install @amplication/opentelemetry-nestjs --save

Supports NestJS 10, 11 and 12 on Node.js >= 20.19. @nestjs/graphql, @nestjs/microservices, @nestjs/schedule and @nestjs/platform-express are optional peers - install them only if your app uses them.

Setup

Getting started with @amplication/opentelemetry-nestjs is simple. To enable automatic instrumentation for most NestJS components, just import the OpenTelemetryModule in your root module:

import { OpenTelemetryModule } from '@amplication/opentelemetry-nestjs';

@Module({
  imports: [OpenTelemetryModule.forRoot()],
})
export class AppModule {}

This will automatically instrument controllers, providers, guards, interceptors, and other core NestJS layers, giving you observability out-of-the-box.

[!TIP] This library only instruments NestJS code. Make sure the OpenTelemetry Node SDK is installed and properly initialized to collect traces and metrics. This package also provides helpers for it.

Usage

While this library automatically instruments core NestJS layers, you can use @Traceable and @Span decorators to create custom spans for specific methods, such as provider functions. This allows you to give meaningful names to spans and capture fine-grained traces for important operations.

@Span

import { Injectable } from '@nestjs/common';
import { Span } from '@amplication/opentelemetry-nestjs';

@Injectable()
export class AppService {
  @Span()
  getHello(): string {
    return 'Hello World!';
  }

  @Span('SpecialCase')
  getSpecial(): string {
    return 'Never miss a SpecialCase with its fancy name!';
  }
}

@Traceable

@Traceable works like @Span but with the difference that it can be used at a class level to auto instrument every method of the class:

import { Injectable } from '@nestjs/common';
import { Traceable } from '@amplication/opentelemetry-nestjs';

@Traceable()
@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
}

Tracer

In an advanced use cases, you need to access the native OpenTelemetry trace provider to access them from NestJS application context. In that case you can inject the Tracer provider:

import { Injectable } from '@nestjs/common';
import { Tracer } from '@amplication/opentelemetry-nestjs';

@Injectable()
export class AppService {
  constructor(private readonly tracer: Tracer) {}

  getHello(): string {
    const span = this.tracer.startSpan('important_section_start');
    // do something important
    span.setAttributes({ userId: 1150 });
    span.end();
    return 'Hello World!';
  }
}

TraceService

The TraceService provides direct access to the current span context and allows you to start custom spans:

import { Injectable } from '@nestjs/common';
import { TraceService } from '@amplication/opentelemetry-nestjs';

@Injectable()
export class AppService {
  constructor(private readonly traceService: TraceService) {}

  getHello(): string {
    const span = this.traceService.startSpan('hello');
    // do something
    span.end();
    return 'Hello World!';
  }
}

Auto Trace Instrumentation

The library comes with comprehensive NestJS instrumentation out-of-the-box. Once you import the module, controllers, guards, providers, pipes, and other core components are automatically traced.

If you want to customize which instrumentations are enabled, you can use the instrumentation option:

import { Module } from '@nestjs/common';
import {
  OpenTelemetryModule,
  ControllerInstrumentation,
  EventEmitterInstrumentation,
  GuardInstrumentation,
  LoggerInstrumentation,
  PipeInstrumentation,
  ScheduleInstrumentation,
} from '@amplication/opentelemetry-nestjs';

@Module({
  imports: [
    OpenTelemetryModule.forRoot({
      instrumentation: [
        ControllerInstrumentation,
        GuardInstrumentation,
        EventEmitterInstrumentation,
        ScheduleInstrumentation,
        PipeInstrumentation,
        LoggerInstrumentation,
      ],
    }),
  ],
})
export class AppModule {}

Instrumented components

InstanceDescription
ControllerInstrumentationAuto trace all of module controllers
GuardInstrumentationAuto trace all of module guards including global guards
PipeInstrumentationAuto trace all of module pipes including global pipes
InterceptorInstrumentationAuto trace all of module interceptors including global pipes
EventEmitterInstrumentationAuto trace for @nestjs/event-emitter library, supports all features
ScheduleInstrumentationAuto trace for @nestjs/schedule library, supports all features
ConsoleLoggerInstrumentationConsoleLogger and Logger class tracer, logs with traceId

Logging with Trace ID

By enabling ConsoleLoggerInstrumentation (or using the default configuration), all logs will automatically include the current trace ID, making it easier to correlate logs with traces:

Example trace output

Manual Tracing for Non-Injectable Classes

If you need to trace instances of classes that aren’t managed by the NestJS DI container, you can wrap the instance with TraceWrapper.trace(). This automatically creates a new span for each method:

import { TraceWrapper } from '@amplication/opentelemetry-nestjs';

class MyClass {
  hello() {
    console.log('Hi');
  }

  async bye() {
    await new Promise(() => console.log('bye bye'));
  }
}

// ....

const instance = new MyClass();
const tracedInstance = TraceWrapper.trace(instance);

// ....

Metrics

You can set up metrics collection using the Prometheus exporter. First, install the Prometheus exporter package:

npm install @opentelemetry/exporter-prometheus

Then, configure it in your OpenTelemetry Node SDK:

new NodeSDK({
  serviceName: 'nestjs-opentelemetry-example',
  // ...
  metricReader: new PrometheusExporter({
    endpoint: 'metrics',
    port: 9464,
  }),
});

You can now access the automatically collected metrics via the Prometheus exporter at http://localhost:9464/metrics.

For other exporter options, see the OpenTelemetry JavaScript exporters documentation.

Starting the OpenTelemetry SDK

In a typical OpenTelemetry setup for Node.js, it’s conventional to create a tracing.ts (or similarly named) file where you initialize and configure the SDK. This file should be imported at the very top of main.ts, before any other imports, so that all modules and libraries loaded afterward are properly instrumented. Doing this ensures that spans are correctly created for your application’s operations, and that context propagation and auto-instrumentations are active from the start of the process.

This package provides a set of helper functions to simplify starting and configuring the OpenTelemetry Node SDK for NestJS applications. It covers context management, propagators, resource detection, auto-instrumentations, and span processing — and can significantly reduce noise in traces.

startNestJsOpenTelemetrySDK(configuration)

Starts the Node OpenTelemetry SDK with default NestJS-friendly helpers, including auto-instrumentations, context manager, propagators, and resource detectors. Accepts any NodeSDKConfiguration overrides:

Example:

import { startNestJsOpenTelemetrySDK } from '@amplication/opentelemetry-nestjs';
import { PrometheusExporter } from '@opentelemetry/exporter-prometheus';

const sdk = startNestJsOpenTelemetrySDK({
  serviceName: 'nestjs-example',
  metricReader: new PrometheusExporter({ endpoint: 'metrics', port: 9464 }),
});

startNestJsOpenTelemetrySDK is equivalent to the following:

import { NodeSDK } from '@opentelemetry/sdk-node';
import {
  nodeAutoInstrumentationReduceNoise,
  nodeAutoInstrumentationHttpReduceIncoming,
  nestjsContextManager,
  nestjsTextMapPropagator,
  nestjsResourceDetectors,
} from '@amplication/opentelemetry-nestjs';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';

const sdk = new NodeSDK({
  instrumentations: getNodeAutoInstrumentations(
    mergeInstrumentationConfigMap(
      nodeAutoInstrumentationReduceNoise(),
      nodeAutoInstrumentationHttpReduceIncoming(),
    ),
  ),
  contextManager: nestjsContextManager(),
  textMapPropagator: nestjsTextMapPropagator(),
  resourceDetectors: nestjsResourceDetectors(),
});

sdk.start();

nodeAutoInstrumentationReduceNoise()

Returns a preconfigured set of Node auto-instrumentations with noise reduction:

  • fs instrumentation ignores files in node_modules and tags spans with file paths.
  • http instrumentation updates incoming request spans to "HTTP_METHOD PATH".
  • graphql instrumentation is configured for NestJS (mergeItems: true, ignoreResolveSpans: true, ignoreTrivialResolveSpans: true).
  • net, dns, express, and nestjs-core instrumentations are disabled to reduce noise.

Example:

import { nodeAutoInstrumentationReduceNoise } from '@amplication/opentelemetry-nestjs';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';

const instrumentations = getNodeAutoInstrumentations(
  nodeAutoInstrumentationReduceNoise(),
);

nodeAutoInstrumentationHttpReduceIncoming(options?)

Filters out specific incoming HTTP requests from tracing, such as health checks or OPTIONS requests.

Options:

  • healthChecks: array of URL paths to ignore (['/health', '/_health', '/healthz', 'healthcheck'] by default)
  • methods: array of HTTP methods to ignore (['OPTIONS'] by default)

Example:

import { nodeAutoInstrumentationHttpReduceIncoming } from '@amplication/opentelemetry-nestjs';

const httpInstrumentations = nodeAutoInstrumentationHttpReduceIncoming({
  healthChecks: ['/health', '/status'],
  methods: ['OPTIONS'],
});

nestjsContextManager()

Returns an AsyncLocalStorageContextManager for proper context propagation in async NestJS code.

Example:

import { nestjsContextManager } from '@amplication/opentelemetry-nestjs';

const contextManager = nestjsContextManager();

nestjsTextMapPropagator()

Returns a composite propagator supporting:

  • Jaeger
  • W3C Trace Context
  • B3 single-header and multi-header

Example:

import { nestjsTextMapPropagator } from '@amplication/opentelemetry-nestjs';

const propagator = nestjsTextMapPropagator();

nestjsResourceDetectors()

Returns an array of resource detectors to enrich spans with environment information (currently includes containerDetector).

Example:

import { nestjsResourceDetectors } from '@amplication/opentelemetry-nestjs';

const detectors = nestjsResourceDetectors();

mergeInstrumentationConfigMap(target, source)

Recursively merges two instrumentation configuration objects. Useful to combine custom auto-instrumentation options with the defaults.

Example:

import {
  mergeInstrumentationConfigMap,
  nodeAutoInstrumentationReduceNoise,
} from '@amplication/opentelemetry-nestjs';

const customConfig = {
  '@opentelemetry/instrumentation-http': {
    ignoreIncomingRequestHook: (req) => req.url === '/metrics',
  },
};

const merged = mergeInstrumentationConfigMap(
  nodeAutoInstrumentationReduceNoise(),
  customConfig,
);

Examples

/* tracing.ts */
import { startNestJsOpenTelemetrySDK } from '@amplication/opentelemetry-nestjs';
import { PrometheusExporter } from '@opentelemetry/exporter-prometheus';
import { PrometheusExporter } from '@opentelemetry/exporter-prometheus';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node';
import { CompositePropagator } from '@opentelemetry/core';
import { JaegerPropagator } from '@opentelemetry/propagator-jaeger';
import { B3InjectEncoding, B3Propagator } from '@opentelemetry/propagator-b3';

startNestJsOpenTelemetrySDK({
  serviceName: 'myservice-opentelemetry-example',
  metricReader: new PrometheusExporter({
    endpoint: 'metrics',
    port: 9464,
  }),
  spanProcessors: [
    new BatchSpanProcessor(
      new OTLPTraceExporter({
        url: 'your-jaeger-url',
      }),
    ),
  ],
  textMapPropagator: new CompositePropagator({
    propagators: [
      new JaegerPropagator(),
      new B3Propagator(),
      new B3Propagator({
        injectEncoding: B3InjectEncoding.MULTI_HEADER,
      }),
    ],
  }),
});

import { NestFactory } from '@nestjs/core';
// ....
/* at the very top of main.ts */
import 'tracing.ts';
// ...
/* app.module.ts */
import { Module } from '@nestjs/common';
import { OpenTelemetryModule } from '@amplication/opentelemetry-nestjs';

@Module({
  imports: [OpenTelemetryModule.forRoot()],
})
export class AppModule {}

AWS X-Ray/CloudWatch

For the integration with AWS X-Ray and CloudWatch, follow the official instructions:

/* tracing.ts */
import {
  startNestJsOpenTelemetrySDK,
  defaultInstrumentation,
} from '@amplication/opentelemetry-nestjs';
import { PrometheusExporter } from '@opentelemetry/exporter-prometheus';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node';
import { CompositePropagator } from '@opentelemetry/core';
import { AWSXRayPropagator } from '@opentelemetry/propagator-aws-xray';
import { AWSXRayIdGenerator } from '@opentelemetry/id-generator-aws-xray';
import { AwsInstrumentation } from '@opentelemetry/instrumentation-aws-sdk';

startNestJsOpenTelemetrySDK({
  serviceName: 'myservice-opentelemetry-example',
  metricReader: new PrometheusExporter({
    endpoint: 'metrics',
    port: 9464,
  }),
  instrumentations: [
    ...defaultInstrumentation,
    new AwsInstrumentation({
      suppressInternalInstrumentation: true,
      sqsExtractContextPropagationFromPayload: true,
    }),
  ],
  idGenerator: new AWSXRayIdGenerator(),
  spanProcessors: [new BatchSpanProcessor(new OTLPTraceExporter({}))],
  textMapPropagator: new AWSXRayPropagator(),
});

Migrating from v6.x to v7.x

Version 7.0 has no API changes. It drops support for NestJS 8 and 9 and adds support for NestJS 12 and @nestjs/graphql 13.4+ / 14:

  • Supported versions: NestJS 10, 11 and 12 (@nestjs/graphql 12-14, @nestjs/event-emitter 2, 3 and 12, @nestjs/schedule 3-6 and 12). Node.js >= 20.19 is required, which lets this CommonJS package load the ESM-only NestJS 12 packages.
  • Optional peers: @nestjs/graphql, @nestjs/microservices, @nestjs/schedule and @nestjs/platform-express are no longer installed automatically. Add them to your app's dependencies if you use them.
  • No more internal imports: the package no longer deep-imports @nestjs/graphql/dist/... or @nestjs/microservices/constants, which broke with the package exports maps introduced in @nestjs/graphql 13.4.

Migrating from v5.x to v6.x

Version 6.0 introduces significant breaking changes to improve type safety, align with OpenTelemetry standards, and enhance code organization.

📖 Complete Migration Guide →

Quick Summary of Changes

  1. SDK Initialization: Tracing.init() → startNestJsOpenTelemetrySDK()
  2. Module Config: Array format → Object format with instrumentation property
  3. Naming: All *Injector classes → *Instrumentation
  4. Imports: File paths updated to kebab-case
  5. Trace Naming: Updated to align with OpenTelemetry Semantic Conventions

Before (v5.x):

Tracing.init({ serviceName: 'my-app' });
OpenTelemetryModule.forRoot([ControllerInjector]);

After (v6.x):

startNestJsOpenTelemetrySDK({ serviceName: 'my-app' });
OpenTelemetryModule.forRoot({ instrumentation: [ControllerInstrumentation] });

For detailed migration instructions, code examples, and a complete checklist, see the Migration Guide.

版本与发布记录

@amplication/opentelemetry-nestjs 共发布 37 个版本,首次发布于 2023/06/28;过去 12 个月发布了 7 个版本。

版本发布日期距今
7.0.0latest2026/10/031 个月前
6.0.02026/01/079 个月前
6.0.0-beta.5beta2026/01/0310 个月前
6.0.0-beta.42026/01/0310 个月前
6.0.0-beta.32026/01/0310 个月前
6.0.0-beta.22026/01/0310 个月前

关于 @amplication/opentelemetry-nestjs 的常见问题

@amplication/opentelemetry-nestjs 是什么?

OpenTelemetry module for Nestjs with auto instrumentation and resource detection. Initially forked from https://github.com/overbit/opentelemetry-nestjs.git

如何安装 @amplication/opentelemetry-nestjs?

在项目目录运行 npm install @amplication/opentelemetry-nestjs,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@nestjs/core(^10.0.0 || ^11.0.0 || ^12.0.0)、@nestjs/common(^10.0.0 || ^11.0.0 || ^12.0.0)、@nestjs/event-emitter(^2.0.0 || ^3.0.0 || ^12.0.0)、@opentelemetry/sdk-node(>=0.203.0 <1.0.0)、@opentelemetry/propagator-b3(^2.0.0)、@opentelemetry/sdk-trace-base(^2.0.0)、@opentelemetry/propagator-jaeger(^2.0.0)、@opentelemetry/context-async-hooks(^2.0.0)、@opentelemetry/exporter-trace-otlp-grpc(>=0.203.0 <1.0.0)、@opentelemetry/exporter-trace-otlp-http(>=0.203.0 <1.0.0)、@opentelemetry/exporter-trace-otlp-proto(>=0.203.0 <1.0.0)、@opentelemetry/auto-instrumentations-node(>=0.62.1 <1.0.0)、@opentelemetry/exporter-metrics-otlp-grpc(>=0.203.0 <1.0.0)、@opentelemetry/exporter-metrics-otlp-proto(>=0.203.0 <1.0.0)、@opentelemetry/resource-detector-container(>=0.7.0 <1.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@amplication/opentelemetry-nestjs 支持 TypeScript 吗?

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

@amplication/opentelemetry-nestjs 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@amplication/opentelemetry-nestjs 需要什么版本的 Node.js?

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

@amplication/opentelemetry-nestjs 可以商用吗?

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

@amplication/opentelemetry-nestjs 的下载量有多少?

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

@amplication/opentelemetry-nestjs 还在维护吗?

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