Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

Nestjs-OpenTelemetry

> 后端框架
Open source

Deeply Integrated and Auto Instrumented OpenTelemetry module for NestJS

389 stars0 likes1 views
WebsiteGitHub

About

Deeply Integrated and Auto Instrumented OpenTelemetry module for NestJS

NestJS OpenTelemetry

This library provides deeply integrated protocol-agnostic Nestjs OpenTelemetry instrumentations, metrics and SDK.

Description

Nestjs is a protocol-agnostic framework. That's why this library can able to work with different protocols like RabbitMQ, GRPC and HTTP. Also you can observe and trace Nestjs specific layers like Pipe, Guard, Controller and Provider.

It also includes auto trace and metric instrumentations for some popular Nestjs libraries.

  • Distributed Tracing

    • Setup
    • Decorators
    • Trace Providers
    • Auto Trace Instrumentations
    • Distributed Logging with Trace ID
  • Metrics

    • Setup
    • Decorators
    • Metric Providers
    • Auto Metric Observers

OpenTelemetry Metrics currently experimental. So, this library doesn't support metric decorators and Auto Observers until it's stable. but if you want to use it, you can use OpenTelemetry API directly.

Competability table for Nestjs versions.

Nestjs Nestjs-OpenTelemetry
9.x 3.x.x
8.x 2.x.x

Installation

bash
npm install @metinseylan/nestjs-opentelemetry --save

Configuration

This is a basic configuration without any trace and metric exporter, but includes default metrics and injectors

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

@Module({
  imports: [
    OpenTelemetryModule.forRoot({
      serviceName: 'nestjs-opentelemetry-example',
    })
  ]
})
export class AppModule {}

Async configuration example

typescript
import { OpenTelemetryModule } from '@metinseylan/nestjs-opentelemetry';
import {ConfigModule, ConfigService} from '@nestjs/config';

@Module({
  imports: [
    OpenTelemetryModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        serviceName: configService.get('SERVICE_NAME'),
      }),
      inject: [ConfigService]
    })
  ]
})
export class AppModule {}

Default Parameters

key value description
traceAutoInjectors ControllerInjector, GuardInjector, EventEmitterInjector, ScheduleInjector, PipeInjector, LoggerInjector default auto trace instrumentations
metricAutoObservers ResourceMetric, ProcessStartTimeMetric, ProcessOpenFdsMetric, ProcessMaxFdsMetric, ActiveHandlesMetric, ActiveHandlesTotalMetric, HttpRequestDurationSeconds, GrpcRequestDurationSeconds, RabbitMqRequestDurationSeconds default auto metric collectors
contextManager AsyncLocalStorageContextManager default trace context manager inherited from NodeSDKConfiguration
instrumentations AutoInstrumentations default instrumentations inherited from NodeSDKConfiguration
spanProcessor NoopSpanProcessor default spanProcessor inherited from NodeSDKConfiguration
textMapPropagator JaegerPropagator, B3Propagator default textMapPropagator inherited from NodeSDKConfiguration

OpenTelemetryModule.forRoot() takes OpenTelemetryModuleConfig as a parameter, this type is inherited by NodeSDKConfiguration so you can use same OpenTelemetry SDK parameter.


Distributed Tracing

Simple setup with Zipkin exporter, including with default trace instrumentations.

typescript
import { OpenTelemetryModule } from '@metinseylan/nestjs-opentelemetry';
import { ZipkinExporter } from '@opentelemetry/exporter-zipkin';
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';

@Module({
  imports: [
    OpenTelemetryModule.forRoot({
      spanProcessor: new SimpleSpanProcessor(
        new ZipkinExporter({
          url: 'your-zipkin-url',
        })
      ),
    }),
  ],
})
export class AppModule {}

After setup, your application will be instrumented, so that you can see almost every layer of application in ZipkinUI, including Guards, Pipes, Controllers even global layers like this

List of supported official exporters here.


Trace Decorators

This library supports auto instrumentations for Nestjs layers, but sometimes you need to define custom span for specific method blocks like providers methods. In this case @Span decorator will help you.

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

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

Also @Span decorator takes name field as a parameter

typescript
@Span('hello')

Trace Providers

In an advanced usage case, you need to access the native OpenTelemetry Trace provider to access them from Nestjs application context.

typescript
import { Injectable } from '@nestjs/common';
import { Tracer } from '@opentelemetry/sdk-trace-base';

@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 can access directly current span context and start new span.

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

@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 Instrumentations

The most helpful part of this library is that you already get all of the instrumentations by default if you set up a module without any extra configuration. If you need to avoid some of them, you can use the traceAutoInjectors parameter.

…

List of Trace Injectors

Instance Description
ControllerInjector Auto trace all of module controllers
GuardInjector Auto trace all of module guards including global guards
PipeInjector Auto trace all of module pipes including global pipes
EventEmitterInjector Auto trace for @nestjs/event-emitter library, supports all features
ScheduleInjector Auto trace for @nestjs/schedule library, supports all features
LoggerInjector ConsoleLogger and Logger class tracer, logs with traceId

Distributed Logging with Trace ID

When you set up your environment with the LoggerInjector class or default configuration, you can see trace id with every log.


Metrics

Simple setup with Prometheus exporter, you need install @opentelemetry/exporter-prometheus

typescript
import { OpenTelemetryModule } from '@metinseylan/nestjs-opentelemetry';
import { PrometheusExporter } from '@opentelemetry/exporter-prometheus';

@Module({
  imports: [OpenTelemetryModule.forRoot({
    serviceName: 'nestjs-opentelemetry-example',
    metricReader: new PrometheusExporter({
      endpoint: 'metrics',
      port: 9464,
    })
  })]
})
export class AppModule {}

Now you can access Prometheus exporter with auto collected metrics http://localhost:9464/metrics. Also, you can find different exporters here


Metric Decorators (Deprecated)

If you need to observe simple block of function, you can use some basic decorators like @Counter and @Observer

Counter

typescript
import { Injectable } from '@nestjs/common';
import { Counter } from '@metinseylan/nestjs-opentelemetry';

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

@Counter decorator is uses OpenTelemetry Counter metric, If you check prometheus exporter you will see metric appservice_gethello_total

typescript
@Counter('call_me_mr_fahrenheit', {
  description: 'important function call counting here.'
})

And of course, you can configure your decorator metric, the first parameter is "name" and the second one is [MetricOptions](https://github.com/open-telemetry/opentelemetry-js/blob/357ec92

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptdistributed-tracingjeagermetricsnest

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架