npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@easyv/nestjs-opentelemetry

v1.1.5

Published

deeply integrated OpenTelemetry module for Nestjs

Downloads

221

Readme

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.

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.

Only supports NestJS 9.x

Installation

npm install @easyv/nestjs-opentelemetry --save

Configuration

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

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

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

Async configuration example (Not recommended, May cause auto instrumentations to not work)

import { OpenTelemetryModule } from '@easyv/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 | |-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | traceInjectors | DecoratorInjector, ScheduleInjector, ControllerInjector, GuardInjector, PipeInjector, InterceptorInjector, ExceptionFilterInjector, TypeormInjector, LoggerInjector, ProviderInjector, MiddlewareInjector | default auto trace instrumentations | | contextManager | AsyncLocalStorageContextManager | default trace context manager inherited from NodeSDKConfiguration | | instrumentations | AutoInstrumentations | default instrumentations inherited from NodeSDKConfiguration | | textMapPropagator | W3CTraceContextPropagator | 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.

import { OpenTelemetryModule } from '@easyv/nestjs-opentelemetry';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc'
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';

@Module({
  imports: [
    OpenTelemetryModule.forRoot({
      spanProcessor: new SimpleSpanProcessor(
        new OTLPTraceExporter({
          url: 'http://<collector-hostname>:<port>',
        })
      ),
    }),
  ],
})
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

Example trace output

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 @Trace and @TracePlain decorator will help you.

import { Injectable } from '@nestjs/common';
import { Trace } from '@easyv/nestjs-opentelemetry';

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

Also @Trace decorator takes name field as a parameter

@Trace({ name: 'hello' })

Trace Providers

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

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

@Injectable()
export class AppService {
  constructor() {}

  getHello(): string {
    const span = trace.getTracer('default').startSpan('important_section_start');
    // do something important
    span.setAttributes({ userId: 1150 });
    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.

import { Module } from '@nestjs/common';
import {
  OpenTelemetryModule,
  ControllerInjector,
  EventEmitterInjector,
  GuardInjector,
  LoggerInjector,
  PipeInjector,
  ScheduleInjector,
} from '@easyv/nestjs-opentelemetry';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc'
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';

@Module({
  imports: [
    OpenTelemetryModule.forRoot({
      traceInjectors: [
        ControllerInjector,
        GuardInjector,
        EventEmitterInjector,
        ScheduleInjector,
        PipeInjector,
        LoggerInjector,
      ],
      spanProcessor: new SimpleSpanProcessor(
        new OTLPTraceExporter({
          url: 'http://<collector-hostname>:<port>',
        })
      ),
    }),
  ]
})
export class AppModule {}

List of Trace Injectors

| Instance | Description | |---------------------------|----------------------------------------------------------------------------------------------------------------------| | ControllerInjector | Auto trace all of module controllers | | DecoratorInjector | Auto trace all of decorator providers | | GuardInjector | Auto trace all of module guards including global guards | | PipeInjector | Auto trace all of module pipes including global pipes | | InterceptorInjector | Auto trace all of module interceptors including global interceptors | | ExceptionFilterInjector | Auto trace all of module exceptionFilters including global exceptionFilters | | MiddlewareInjector | Auto trace all of module middlewares including global middlewares | | ProviderInjector | Auto trace all of module providers | | ScheduleInjector | Auto trace for @nestjs/schedule library, supports all features | | LoggerInjector | Logger class tracer | | TypeormInjector | Auto trace for typeorm library |