Socket
Socket
Sign inDemoInstall

@opentelemetry/api

Package Overview
Dependencies
1
Maintainers
4
Versions
62
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @opentelemetry/api

Public API for OpenTelemetry


Version published
Weekly downloads
8.7M
increased by2.44%
Maintainers
4
Install size
236 kB
Created
Weekly downloads
 

Package description

What is @opentelemetry/api?

The @opentelemetry/api package provides a set of APIs to instrument JavaScript applications for telemetry purposes. It allows developers to collect traces and metrics from their applications, which can then be exported to various observability backends for monitoring and analysis. The API is designed to be minimal, extensible, and vendor-neutral.

What are @opentelemetry/api's main functionalities?

Tracing

This feature allows the creation and management of traces to monitor the flow of a request through various services. The code sample demonstrates how to create a tracer, start a new span, and then end the span.

const { trace } = require('@opentelemetry/api');
const tracer = trace.getTracer('example-tracer');
const span = tracer.startSpan('example-span');
span.end();

Context Propagation

This feature enables the propagation of context information across asynchronous operations or service boundaries. The code sample shows how to associate a span with a context and execute a function within this context.

const { context, trace } = require('@opentelemetry/api');
const currentContext = context.active();
const span = trace.getTracer('example-tracer').startSpan('example-span');
context.with(trace.setSpan(currentContext, span), () => {
  // Your synchronous or asynchronous operation here
  span.end();
});

Metrics

This feature supports the collection of quantitative measurements of operational events, such as request counts. The code sample illustrates how to create a meter, define a counter metric, and increment the counter.

const { metrics } = require('@opentelemetry/api');
const meter = metrics.getMeter('example-meter');
const counter = meter.createCounter('example-counter');
counter.add(1);

Other packages similar to @opentelemetry/api

Changelog

Source

0.12.0

:boom: Breaking Change

  • opentelemetry-api, opentelemetry-exporter-collector-grpc, opentelemetry-exporter-collector-proto, opentelemetry-exporter-collector, opentelemetry-exporter-prometheus, opentelemetry-metrics
    • #1588 Update to Proto v0.5.0 (@obecny)
  • opentelemetry-api, opentelemetry-core, opentelemetry-plugin-http, opentelemetry-plugin-https, opentelemetry-shim-opentracing
  • opentelemetry-resource-detector-aws, opentelemetry-resources
    • #1581 chore: remove duplicate hostname resource attribute (@mwear)
  • opentelemetry-api, opentelemetry-core, opentelemetry-plugin-fetch, opentelemetry-plugin-xml-http-request
  • opentelemetry-core, opentelemetry-tracing
    • #1562 feat(core): rename ProbabilitySampler to TraceIdRatioBasedSampler (@legendecas)
  • opentelemetry-exporter-prometheus
  • opentelemetry-core, opentelemetry-exporter-prometheus, opentelemetry-metrics, opentelemetry-sdk-node, opentelemetry-tracing

:rocket: (Enhancement)

  • opentelemetry-api, opentelemetry-exporter-collector-grpc, opentelemetry-exporter-collector-proto, opentelemetry-exporter-collector, opentelemetry-exporter-prometheus, opentelemetry-metrics
  • opentelemetry-core, opentelemetry-tracing
  • opentelemetry-instrumentation
    • #1572 feat: adding function for checking wrapped into instrumentation (@obecny)
  • opentelemetry-core
  • opentelemetry-exporter-prometheus
  • opentelemetry-api, opentelemetry-core, opentelemetry-exporter-collector-proto, opentelemetry-exporter-collector, opentelemetry-exporter-jaeger, opentelemetry-exporter-prometheus, opentelemetry-exporter-zipkin, opentelemetry-metrics, opentelemetry-tracing
  • opentelemetry-api, opentelemetry-core, opentelemetry-node, opentelemetry-plugin-http, opentelemetry-plugin-https, opentelemetry-shim-opentracing, opentelemetry-tracing
  • opentelemetry-node, opentelemetry-sdk-node
    • #1525 feat(node-tracer): use AsyncLocalStorageContextManager by default starting Node 14.8 #1511 (@vmarchaud)
  • opentelemetry-exporter-collector, opentelemetry-exporter-jaeger, opentelemetry-exporter-zipkin, opentelemetry-grpc-utils, opentelemetry-plugin-grpc-js, opentelemetry-plugin-grpc, opentelemetry-plugin-http, opentelemetry-plugin-https
    • #1548 chore(http): remove x-opentelemetry-outgoing-request header #1547 (@vmarchaud)
  • Other
  • opentelemetry-api, opentelemetry-instrumentation, opentelemetry-node
    • #1540 Plugins refactoring - new instrumentation package for plugins (@obecny)
  • opentelemetry-api, opentelemetry-tracing
  • opentelemetry-resource-detector-aws, opentelemetry-resources
    • #1404 Feat: Added AWS ECS Plugins Resource Detector (@EdZou)
  • opentelemetry-node
  • opentelemetry-resources, opentelemetry-sdk-node
  • opentelemetry-api, opentelemetry-context-async-hooks, opentelemetry-context-base, opentelemetry-context-zone-peer-dep, opentelemetry-core, opentelemetry-shim-opentracing, opentelemetry-tracing, opentelemetry-web
  • opentelemetry-exporter-zipkin
    • #1399 chore: refactoring zipkin to be able to use it in web (@obecny)
  • opentelemetry-exporter-collector-grpc, opentelemetry-exporter-collector-proto, opentelemetry-exporter-collector, opentelemetry-exporter-jaeger, opentelemetry-exporter-prometheus, opentelemetry-exporter-zipkin, opentelemetry-metrics, opentelemetry-plugin-fetch, opentelemetry-plugin-xml-http-request, opentelemetry-tracing

:bug: (Bug Fix)

  • opentelemetry-plugin-http
    • #1546 fix(http): do not set outgoing http span as active in the context #1479 (@vmarchaud)
  • opentelemetry-metrics
    • #1567 fix: histogram aggregator lastUpdateTime (@AndrewGrachov)
    • #1470 IMPORTANT - Fixing collecting data from observers when using batch observer in first run (@obecny)
  • opentelemetry-plugin-http, opentelemetry-plugin-https
  • opentelemetry-context-async-hooks
    • #1530 fix: ignore TIMERWRAP in AsyncHooksContextManager (@Flarna)
  • opentelemetry-exporter-collector-grpc, opentelemetry-exporter-collector-proto
    • #1539 fix: include missing proto files in npm distribution (@blumamir)

:books: (Refine Doc)

  • Other
  • opentelemetry-exporter-collector-proto, opentelemetry-exporter-collector

:sparkles: (Feature)

  • opentelemetry-resource-detector-aws, opentelemetry-resources
    • #1404 Feat: Added AWS ECS Plugins Resource Detector (@EdZou)
  • opentelemetry-exporter-zipkin
    • #1399 chore: refactoring zipkin to be able to use it in web (@obecny)

Committers: 19

Readme

Source

OpenTelemetry API for JavaScript

Gitter chat NPM Published Version dependencies devDependencies Apache License

This package provides everything needed to interact with the OpenTelemetry API, including all TypeScript interfaces, enums, and no-op implementations. It is intended for use both on the server and in the browser.

Quick Start

To get started you need to install the SDK and plugins, create a TracerProvider and/or MeterProvider, and register it with the API.

Install Dependencies

$ # Install tracing dependencies
$ npm install \
    @opentelemetry/api \
    @opentelemetry/core \
    @opentelemetry/node \
    @opentelemetry/tracing \
    @opentelemetry/exporter-jaeger \ # add exporters as needed
    @opentelemetry/plugin-http # add plugins as needed

$ # Install metrics dependencies
$ npm install \
    @opentelemetry/metrics \
    @opentelemetry/exporter-prometheus # add exporters as needed

Note: this example is for node.js. See examples/tracer-web for a browser example.

Initialize the SDK

Before any other module in your application is loaded, you must initialize the global tracer and meter providers. If you fail to initialize a provider, no-op implementations will be provided to any library which acquires them from the API.

To collect traces and metrics, you will have to tell the SDK where to export telemetry data to. This example uses Jaeger and Prometheus, but exporters exist for other tracing backends. If you're not sure if there is an exporter for your tracing backend, contact your tracing provider.

Tracing
const { NodeTracerProvider } = require("@opentelemetry/node");
const { SimpleSpanProcessor } = require("@opentelemetry/tracing");
const { JaegerExporter } = require("@opentelemetry/exporter-jaeger");

const tracerProvider = new NodeTracerProvider();

/**
 * The SimpleSpanProcessor does no batching and exports spans
 * immediately when they end. For most production use cases,
 * OpenTelemetry recommends use of the BatchSpanProcessor.
 */
tracerProvider.addSpanProcessor(
  new SimpleSpanProcessor(
    new JaegerExporter({
      serviceName: 'my-service'
    })
  )
);

/**
 * Registering the provider with the API allows it to be discovered
 * and used by instrumentation libraries. The OpenTelemetry API provides
 * methods to set global SDK implementations, but the default SDK provides
 * a convenience method named `register` which registers same defaults
 * for you.
 *
 * By default the NodeTracerProvider uses Trace Context for propagation
 * and AsyncHooksScopeManager for context management. To learn about
 * customizing this behavior, see API Registration Options below.
 */
tracerProvider.register();
Metrics
const api = require("@opentelemetry/api");
const { MeterProvider } = require("@opentelemetry/metrics");
const { PrometheusExporter } = require("@opentelemetry/exporter-prometheus");

const meterProvider = new MeterProvider({
  // The Prometheus exporter runs an HTTP server which
  // the Prometheus backend scrapes to collect metrics.
  exporter: new PrometheusExporter({ startServer: true }),
  interval: 1000,
});

/**
 * Registering the provider with the API allows it to be discovered
 * and used by instrumentation libraries.
 */
api.metrics.setGlobalMeterProvider(meterProvider);

Version Compatibility

Because the npm installer and node module resolution algorithm could potentially allow two or more copies of any given package to exist within the same node_modules structure, the OpenTelemetry API takes advantage of a variable on the global object to store the global API. When an API method in the API package is called, it checks if this global API exists and proxies calls to it if and only if it is a compatible API version. This means if a package has a dependency on an OpenTelemetry API version which is not compatible with the API used by the end user, the package will receive a no-op implementation of the API.

Advanced Use

API Registration Options

If you prefer to choose your own propagator or context manager, you may pass an options object into the tracerProvider.register() method. Omitted or undefined options will be replaced by a default value and null values will be skipped.

const { B3Propagator } = require("@opentelemetry/core");

tracerProvider.register({
  // Use B3 Propagation
  propagator: new B3Propagator(),

  // Skip registering a default context manager
  contextManager: null,
});

API Methods

If you are writing an instrumentation library, or prefer to call the API methods directly rather than using the register method on the Tracer/Meter Provider, OpenTelemetry provides direct access to the underlying API methods through the @opentelemetry/api package. API entry points are defined as global singleton objects trace, metrics, propagation, and context which contain methods used to initialize SDK implementations and acquire resources from the API.

const api = require("@opentelemetry/api");

/* Initialize TracerProvider */
api.trace.setGlobalTracerProvider(tracerProvider);
/* returns tracerProvider (no-op if a working provider has not been initialized) */
api.trace.getTracerProvider();
/* returns a tracer from the registered global tracer provider (no-op if a working provider has not been initialized) */
api.trace.getTracer(name, version);

/* Initialize MeterProvider */
api.metrics.setGlobalMeterProvider(meterProvider);
/* returns meterProvider (no-op if a working provider has not been initialized) */
api.metrics.getMeterProvider();
/* returns a meter from the registered global meter provider (no-op if a working provider has not been initialized) */
api.metrics.getMeter(name, version);

/* Initialize Propagator */
api.propagation.setGlobalPropagator(httpTraceContextPropagator);

/* Initialize Context Manager */
api.context.setGlobalContextManager(asyncHooksContextManager);

Library Authors

Library authors need only to depend on the @opentelemetry/api package and trust that the application owners which use their library will initialize an appropriate SDK.

const api = require("@opentelemetry/api");

const tracer = api.trace.getTracer("my-library-name", "0.2.3");

async function doSomething() {
  const span = tracer.startSpan("doSomething", { parent: tracer.getCurrentSpan() });
  try {
    const result = await doSomethingElse();
    span.end();
    return result;
  } catch (err) {
    span.setStatus({
      // use an appropriate status code here
      code: api.CanonicalCode.INTERNAL,
      message: err.message,
    });
    span.end();
    return null;
  }
}

License

Apache 2.0 - See LICENSE for more information.

Keywords

FAQs

Last updated on 19 Oct 2020

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc