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

@zonneplan/open-telemetry-node

v1.1.0

Published

![](https://github.com/zonneplan/open-telemetry-js/actions/workflows/ci-main.yml/badge.svg)

Downloads

132

Readme

OpenTelemetry Node

Find the source code at zonneplan/open-telemetry-js.

Set up

npm install @zonneplan/open-telemetry-node

Usage

Initialize OpenTelemetry before your application bootstraps

The usage of import ... = require('') is necessary so that the types are loaded in before the application is bootstrapped. Otherwise, the instrumentations are not loaded in time. This code would be placed on top of the main.ts in a NestJS application. For example, see main.ts

import otel = require('@zonneplan/open-telemetry-node');
import nest = require('@zonneplan/open-telemetry-nest');
import zonneplan = require('@zonneplan/open-telemetry-zonneplan');

new otel.OpenTelemetryBuilder('nest-example')
  .withTracing(zonneplan.DefaultTracingOptions)
  .withLogging(zonneplan.DefaultLoggingOptions)
  .withMetrics(zonneplan.DefaultMetricsOptions)
  .withMetrics((options) =>
    options.$if(process.env['NODE_ENV'] === 'development', (metricsOptions) =>
      metricsOptions.withMetricReader(new nest.PrometheusNestExporter())
    )
  )
  .start();

Alternatively, by not using predefined options:

new otel.OpenTelemetryBuilder('nest-example')
  .withInstrumentation(
    new MySQLInstrumentation({
      enabled: true
    }),
    new NestInstrumentation({
      enabled: true
    }),
  )
  .withSampler(new AlwaysOnSampler())
  .withSpanExporter(new OTLPTraceExporter())
  .withSpanProcessor((exporter) => new BatchSpanProcessor(exporter))

  .withLogging((options) =>
    options
      .withLogRecordExporter(new OTLPLogExporter())
  )
  .withMetrics((options) =>
    options
      .withMetricReader(
        new PeriodicExportingMetricReader({
          exporter: new OTLPMetricExporter(),
          exportIntervalMillis: 1000
        })
      )
  )
  .start();

Using spans (tracing)

import { setAttributeOnActiveSpan } from './set-attributes-on-active-span';
import { setSpanError } from './set-span-status';

@Injectable()
export class MyService {
  /**
   * Instead of manually starting a span, you can use the {@link span} decorator to automatically start a span for the given method.
   * Alternatively, use the `startSpan` method using the disposable pattern / manually ending it.
   * The span name can be overwritten, but defaults to AppService::getData.
   *
   * @note decorators require the following config options in the `tsconfig.json`:
   *     "emitDecoratorMetadata": true,
   *     "experimentalDecorators": true
   */
  @span()
  /**
   * Span attributes can be manually set in the method, by using the `setAttributeOnActiveSpan` method.
   * However, if you only want to set some input parameters as span attributes, you can use the {@link spanAttribute} decorator.
   *
   * @note primitive values (string, numbers and booleans) don't need a function for parsing. Other's do, because they are not valid span attribute values.
   * the name is automatically inferred, but technically does not match the Open telemetry spec, so it's recommended to always provide a name.
   */
  public methodWithSpanDecorator(@spanAttribute((val: Date) => val.toISOString()) date: Date, @spanAttribute() name: string) {
    setAttributeOnActiveSpan('name', name);
    setSpanError('This is an error');
  }

  public methodWithSpan() {
    const span = startSpan('methodWithSpan');

    span.setAttribute('name', 'John Doe');
    span.setStatus({
      code: SpanStatusCode.ERROR,
      message: 'This is an error'
    });

    span.end();
  }
  
  public methodWithDisposableSpan() {
    let span: Span;
    
    if (true) {
      using span = startSpan('methodWithDisposableSpan');
      span.end();
    }
    
    span.isRecording(); // false
  }
}

Using metrics

// We provide our own Gauge instance here to mimic the behaviour of a Prometheus Gauge (from prom-client)
// this is mainly because we use gauages for tracking time-related tasks, so we provide a simple utility to set the gauge to the current time.
const gauge = getOrCreateMetric({
  name: 'process_boot_time',
  unit: 's',
  type: 'Gauge',
  description: 'Time when the process started',
  valueType: ValueType.INT,
})

gauge.setToCurrentTime();

const counter = getOrCreateMetric({
  type: 'Counter',
  name: 'http_request', // automatically suffixed with '_total' by OTEL
  description: 'Total number of HTTP requests',
})

counter.add(1);

const histogram = getOrCreateMetric({
  type: 'Histogram',
  name: 'http_request_duration',
})

histogram.record(0.5);

Classes can also be decorated with the metricIncrement decorator to automatically increment a counter on a method call.

class MyClass {
  @metricIncrement('my_class_method_calls')
  public myMethod() {
    // ...
  }
}