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

@icano/nestjs-opentelemetry

v1.0.0

Published

OpenTelemetry NestJS Module and Service

Downloads

102

Readme

Description

OpenTelemetry module for Nest

Installation

npm install @icano/nestjs-opentelemetry @opentelemetry/sdk-node @opentelemetry/sdk-trace-node @opentelemetry/auto-instrumentations-node @opentelemetry/api @opentelemetry/sdk-metrics

Getting Started

With installation out of the way, we now need to configure OpenTelemetry and our NestJS Application.

Lets first create an instrumentation.ts this is where we will configure the OpenTelemetry SDK, lets go ahead and create this in our src directory next to the main.ts. The file below is just an example, which makes all our outputs go to console and makes use of the @opentelemetry/auto-instrumentations-node to get some default nodejs instrumentations.

/*instrumentation.ts*/
import { NodeSDK } from '@opentelemetry/sdk-node';
import { ConsoleSpanExporter } from '@opentelemetry/sdk-trace-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import {
  PeriodicExportingMetricReader,
  ConsoleMetricExporter,
} from '@opentelemetry/sdk-metrics';

export const sdk = new NodeSDK({
  traceExporter: new ConsoleSpanExporter(),
  metricReader: new PeriodicExportingMetricReader({
    exporter: new ConsoleMetricExporter(),
  }),
  instrumentations: [getNodeAutoInstrumentations()],
});

With our instrumentations.ts created, please ensure that the NodeSDK is exported, as we will actually start it in our main.ts and also use it in our app.module.ts when we init the OpenTelemetryModule.

Ensure that the NodeSDK is started at the top of the bootstrap function, and make sure to enable NestJS Shutdown Hooks app.enableShutdownHooks() this will allow the module to shutdown the NodeSDK and ensure data is sent over when the NestJS app is shutdown.

/*main.ts*/
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { sdk } from './instrumentation';

async function bootstrap() {
  sdk.start();
  const app = await NestFactory.create(AppModule);
  app.enableShutdownHooks();
  await app.listen(3000);
}
bootstrap();

With the NodeSDK started, now we just need to setup the OpenTelemetryModule in our AppModule, and pass in the NodeSDK to ensure that we call the shutdown method when the NestJS app shutsdown.

/*app.module.ts*/
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { sdk } from './instrumentation';
import { OpenTelemetryModule } from '@icano/nestjs-opentelemetry';
import { LoggerModule } from 'nestjs-pino';

@Module({
  imports: [OpenTelemetryModule.forRoot({ sdk })],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

With this, you've got a starting point that you can work with, next steps would be to improve your instrumentation.ts to use the correct exporters depending on where you will send the data to (Prometheus, Jagger, GCP....), as well as defining the instrumentations you will need, as @opentelemetry/auto-instrumentations-node has a lot of things, but not everything, for example it has no out of the box instrumentation for nest-commander

Custom Metrics & Traces

The OpenTelemetry metrics and traces API has been exposed via custom providers, to get access to them you can inject them into any of the services where you will need them. You could also access them through the @opentelemetry/api metrics, trace global instances, but by injecting them it allows for easier testing aftewards.

/*app.service.ts*/
import {
  InjectOtelMetrics,
  InjectOtelTrace,
} from '@icano/nestjs-opentelemetry';
import { Injectable } from '@nestjs/common';
import { TraceAPI, MetricsAPI } from '@opentelemetry/api';

@Injectable()
export class AppService {
  constructor(
    @InjectOtelTrace() private trace: TraceAPI,
    @InjectOtelMetrics() private metrics: MetricsAPI,
  ) {}
  getHello(): string {
    // create a counter
    const counter = this.metrics
      .getMeterProvider()
      .getMeter('default')
      .createCounter('GetHello', {
        description: 'the times that getHello was called',
      });
    counter.add(1);

    // access trace to create custom span
    const trace = this.trace.getTracer('default');
    trace.startSpan('custom');
    return 'Hello World!';
  }
}

Test

# unit tests
$ npm run test

# test coverage
$ npm run test:cov

License

MIT licensed.