open-telemetry / opentelemetry-js
- пятница, 23 декабря 2022 г. в 00:36:44
OpenTelemetry JavaScript Client
Getting Started • API and SDK Reference
This is the JavaScript version of OpenTelemetry, a framework for collecting traces and metrics from applications.
The following describes how to set up tracing for a basic web application. For more detailed documentation, see the website at https://opentelemetry.io/docs/instrumentation/js/.
Dependencies with the latest tag on NPM should be compatible with each other.
See the version compatibility matrix below for more information.
npm install --save @opentelemetry/api
npm install --save @opentelemetry/sdk-node
npm install --save @opentelemetry/auto-instrumentations-nodeNote: auto-instrumentations-node is a meta package from opentelemetry-js-contrib that provides a simple way to initialize multiple Node.js instrumentations.
// tracing.js
'use strict'
const process = require('process');
const opentelemetry = require('@opentelemetry/sdk-node');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const { ConsoleSpanExporter } = require('@opentelemetry/sdk-trace-base');
const { Resource } = require('@opentelemetry/resources');
const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions');
// configure the SDK to export telemetry data to the console
// enable all auto-instrumentations from the meta package
const traceExporter = new ConsoleSpanExporter();
const sdk = new opentelemetry.NodeSDK({
resource: new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: 'my-service',
}),
traceExporter,
instrumentations: [getNodeAutoInstrumentations()]
});
// initialize the SDK and register with the OpenTelemetry API
// this enables the API to record telemetry
sdk.start()
.then(() => console.log('Tracing initialized'))
.catch((error) => console.log('Error initializing tracing', error));
// gracefully shut down the SDK on process exit
process.on('SIGTERM', () => {
sdk.shutdown()
.then(() => console.log('Tracing terminated'))
.catch((error) => console.log('Error terminating tracing', error))
.finally(() => process.exit(0));
});node -r ./tracing.js app.jsThe above example will emit auto-instrumented telemetry about your Node.js application to the console. For a more in-depth example, see the Getting Started Guide. For more information about automatic instrumentation see @opentelemetry/sdk-trace-node, which provides auto-instrumentation for Node.js applications. If the automatic instrumentation does not suit your needs, or you would like to create manual traces, see @opentelemetry/sdk-trace-base
If you are a library author looking to build OpenTelemetry into your library, please see the documentation. As a library author, it is important that you only depend on properties and methods published on the public API. If you use any properties or methods from the SDK that are not officially a part of the public API, your library may break if an Application Owner uses a different SDK implementation.
| Platform Version | Supported |
|---|---|
Node.JS v18 |
|
Node.JS v16 |
|
Node.JS v14 |
|
| Older Node Versions | See Node Support |
| Web Browsers |
Only Node.js Active or Maintenance LTS versions are supported.
Previous versions of node may work, but they are not tested by OpenTelemetry and they are not guaranteed to work.
Please note that versions of Node.JS v8 prior to v8.12.0 will NOT work, because OpenTelemetry Node depends on the perf_hooks module introduced in v8.5.0 and performance.timeOrigin that is set correctly starting in v8.12.0.
Automated browser tests are run in the latest version of Headless Chrome. There is currently no list of officially supported browsers, but OpenTelemetry is developed using standard web technologies with wide support and should work in currently supported versions of major browsers.
OpenTelemetry is released as a set of distinct packages in 3 categories: API, stable SDK, and experimental. The API is located at /api, the stable SDK packages are in the /packages directory, and the experimental packages are listed in the /experimental/packages directory. There may also be API packages for experimental signals in the experimental directory. All stable packages are released with the same version, and all experimental packages are released with the same version. The below table describes which versions of each set of packages are expected to work together.
| API | Stable Packages | Experimental Packages |
|---|---|---|
| 1.3.x | 1.8.x | 0.34.x |
| 1.2.x | 1.7.x | 0.33.x |
| 1.2.x | 1.6.x | 0.32.x |
| 1.1.x | 1.5.x | 0.31.x |
| 1.1.x | 1.4.x | 0.30.x |
| 1.1.x | 1.3.x | 0.29.x |
| 1.1.x | 1.2.x | 0.29.x |
| 1.1.x | 1.1.x | 0.28.x |
| 1.0.x | 1.0.x | 0.27.x |
| 1.0.x | 1.0.x | 0.26.x |
The current version for each package can be found in the respective package.json file for that module. For additional details see the versioning and stability document in the specification.
| Signal | API Status | SDK Status |
|---|---|---|
| Tracing | Stable | Stable |
| Metrics | Stable | Stable |
| Logs | Development | Development |
For a more detailed breakdown of feature support see the specification compliance matrix.
We'd love your help!. Use tags up-for-grabs and good first issue to get started with the project. For instructions to build and make changes to this project, see the CONTRIBUTING guide.
We have a weekly SIG meeting! See the community page for meeting details and notes.
Approvers (@open-telemetry/js-approvers):
Find more about the approver role in community repository.
Maintainers (@open-telemetry/js-maintainers):
Find more about the maintainer role in community repository.
| Package | Description |
|---|---|
| @opentelemetry/api | This package provides TypeScript interfaces, enums and no-op implementations for the OpenTelemetry core trace and metrics model. It is intended for use both on the server and in the browser. |
| @opentelemetry/core | This package provides default and no-op implementations of the OpenTelemetry api for trace and metrics. It's intended for use both on the server and in the browser. |
| Package | Description |
|---|---|
| @opentelemetry/sdk-trace-base | This module provides a full control over instrumentation and span creation. It doesn't load async_hooks or any instrumentation by default. It is intended for use both on the server and in the browser. |
| @opentelemetry/sdk-metrics | This module provides instruments and meters for reporting of time series data. |
| @opentelemetry/sdk-trace-node | This module provides automatic tracing for Node.js applications. It is intended for use on the server only. |
| @opentelemetry/sdk-trace-web | This module provides automated instrumentation and tracing for Web applications. It is intended for use in the browser only. |
OpenTelemetry is vendor-agnostic and can upload data to any backend with various exporter implementations. Even though, OpenTelemetry provides support for many backends, vendors/users can also implement their own exporters for proprietary and unofficially supported backends.
See the OpenTelemetry registry for a list of exporters available.
OpenTelemetry can collect tracing data automatically using instrumentations.
To request automatic tracing support for a module not on this list, please file an issue. Alternatively, Vendor/Users can write an instrumentation yourself.
Currently, OpenTelemetry supports automatic tracing for:
These instrumentations are hosted at https://github.com/open-telemetry/opentelemetry-js-contrib/tree/master/plugins/node
These instrumentations are hosted at https://github.com/open-telemetry/opentelemetry-js-contrib/tree/master/plugins/web
| Package | Description |
|---|---|
| @opentelemetry/shim-opentracing | OpenTracing shim allows existing OpenTracing instrumentation to report to OpenTelemetry |
@opentelemetry/exporter-trace-otlp-http is now exporting scopeSpans instead of instrumentationLibrarySpans
0.48 and up.@opentelemetry/exporter-metrics-otlp-http is now exporting scopeMetrics instead of instrumentationLibraryMetrics
0.48 and up.@opentelemetry/exporter-trace-otlp-http, OTLPExporterBase._isShutdown is replaced with _shutdownOnce.Metric and trace exporters are split into separate packages:
@opentelemetry/exporter-otlp-http => @opentelemetry/exporter-trace-otlp-http and @opentelemetry/exporter-metrics-otlp-http@opentelemetry/exporter-otlp-grpc => @opentelemetry/exporter-trace-otlp-grpc and @opentelemetry/exporter-metrics-otlp-grpc@opentelemetry/exporter-otlp-proto => @opentelemetry/exporter-trace-otlp-proto and @opentelemetry/exporter-metrics-otlp-protoMetric types are renamed:
@openetelemetry/api-metrics
Meter
createValueRecorder => createHistogramcreateValueObserver => createObservableGaugecreateSumObserver => createObservableCountercreateUpDownSumObserver => createObservableUpDownCounterValueRecorder => HistogramValueObserver => ObservableGaugeSumObserver => ObservableCounterUpDownSumObserver => ObservableUpDownCounterObserverResult => ObservableResultObservation.observer => Observation.observable@opentelemetry/sdk-metrics-base
MetricKind
VALUE_RECORDER => HISTOGRAMSUM_OBSERVER => OBSERVABLE_COUNTERUP_DOWN_SUM_OBSERVER => OBSERVABLE_UP_DOWN_COUNTERVALUE_OBSERVER => OBSERVABLE_GAUGECollector exporter packages and types are renamed:
@opentelemetry/exporter-collector => @opentelemetry/exporter-otlp-http
CollectorExporterBase => OTLPExporterBaseCollectorTraceExporter => OTLPTraceExporterCollectorMetricExporter => OTLPMetricExporterCollectorExporterBrowserBase => OTLPExporterBrowserBaseCollectorExporterNodeBase => OTLPExporterNodeBaseCollectorExporterConfigBase => OTLPExporterConfigBaseCollectorExporterError => OTLPExporterErrorCOLLECTOR_SPAN_KIND_MAPPING => OTLP_SPAN_KIND_MAPPINGcollectorTypes => otlpTypes@opentelemetry/exporter-collector-grpc => @opentelemetry/exporter-otlp-grpc
CollectorTraceExporter => OTLPTraceExporterCollectorMetricExporter => OTLPMetricExporterCollectorExporterConfigNode => OTLPExporterConfigNode@opentelemetry/exporter-collector-proto => @opentelemetry/exporter-otlp-proto
CollectorExporterNodeBase => OTLPExporterNodeBaseCollectorMetricExporter => OTLPMetricExporterCollectorTraceExporter => OTLPTraceExporterHttpTraceContextPropagator -> W3CTraceContextPropagatorHttpBaggagePropagator -> W3CBaggagePropagatorResourceAttributes renamed to SemanticResourceAttributes in the @opentelemetry/semantic-conventions packageHttpBaggage renamed to HttpBaggagePropagator
HttpTraceContext renamed to HttpTraceContextPropagator
JaegerHttpTracePropagator renamed to JaegerPropagator
serviceName configuration removed from Collector exporters. Use service.name Resource attribute instead.
Prometheus exporter added suffix _total to counter metrics.
API is now a peer dependency. This means that users will need to include @opentelemetry/api as a dependency of their project in order to use the SDK. NPM version 7+ (Node 15+) should do this automatically.
All plugins have been removed in favor of instrumentations.
The @opentelemetry/propagator-b3 package previously exported three propagators: B3Propagator,B3SinglePropagator, and B3MultiPropagator, but now only exports the B3Propagator. It extracts b3 context in single and multi-header encodings, and injects context using the single-header encoding by default, but can be configured to inject context using the multi-header endcoding during construction: new B3Propagator({ injectEncoding: B3InjectEncoding.MULTI_HEADER }). If you were previously using the B3SinglePropagator or B3MultiPropagator directly, you should update your code to use the B3Propagator with the appropriate configuration. See the readme for full details and usage.
Sampling configuration via environment variable has changed. If you were using OTEL_SAMPLING_PROBABILITY then you should replace it with OTEL_TRACES_SAMPLER=parentbased_traceidratio and OTEL_TRACES_SAMPLER_ARG=<number> where <number> is a number in the [0..1] range, e.g. "0.25". Default is 1.0 if unset.
diag.setLogLevel is removed and LogLevel can be set by an optional second parameter to setLoggerPR-1880 feat(diag-logger): introduce a new global level api.diag for internal diagnostic logging
PR-1925 feat(diag-logger): part 2 - breaking changes - remove api.Logger, api.NoopLogger, core.LogLevel, core.ConsoleLogger
Logger and LogLevel implementations and change the way you should use the replacement DiagLogger and DiagLogLevel, below are simple examples of how to change your existing usages.The new global api.diag provides the ability to set the global diagnostic logger setLogger() and logging level setLogLevel(), it is also a DiagLogger implementation and should be directly to log diagnostic messages.
All included logger references have been removed in preference to using the global api.diag directly, so you no longer need to pass around the logger instance via function parameters or included as part of the configuration for a component.
import { diag, DiagConsoleLogger, DiagLogLevel } from "@opentelemetry/api";
// Setting the default Global logger to use the Console
// And optionally change the logging level (Defaults to INFO)
diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.ERROR)import { diag } from "@opentelemetry/api";
// Remove or make optional the parameter and don't use it.
export function MyFunction() {
diag.debug("...");
diag.info("...");
diag.warn("...");
diag.error("...");
diag.verbose("..");
}import { diag } from "@opentelemetry/api";
diag.setLogger();PR-1855 Use instrumentation loader to load plugins and instrumentations
registerInstrumentations instead//Previously in node
const provider = new NodeTracerProvider({
plugins: {
'@grpc/grpc-js': {
enabled: true,
path: '@opentelemetry/plugin-grpc-js',
},
}
});
// Now
const provider = new NodeTracerProvider();
const { registerInstrumentations } = require('@opentelemetry/instrumentation');
registerInstrumentations({
instrumentations: [
{
plugins: {
'@grpc/grpc-js': {
enabled: true,
path: '@opentelemetry/plugin-grpc-js',
},
}
}
],
tracerProvider: provider,
});
// or if you want to load only default instrumentations / plugins
registerInstrumentations({
tracerProvider: provider,
});
//Previously in browser
const provider = new WebTracerProvider({
plugins: [
new DocumentLoad()
]
});
// Now
const { registerInstrumentations } = require('@opentelemetry/instrumentation');
const provider = new WebTracerProvider();
registerInstrumentations({
instrumentations: [
new DocumentLoad(),
],
});registerInstrumentations supports loading old plugins and instrumentations together. It also supports setting tracer provider and meter provider on instrumentationsPR-1874 More specific API type names
Some types exported from "@opentelemetry/api" have been changed to be more specific.
AttributeValue renamed to SpanAttributeValueAttributes renamed to SpanAttributesEntryTtl renamed to BaggageEntryTtlEntryValue renamed to BaggageEntryValueStatus renamed to SpanStatusStatusCode renamed to SpanStatusCodePR-1863 removed public attributes keepAlive and httpAgentOptions from nodejs CollectorTraceExporter and CollectorMetricExporter
PR-1764 removed some APIs from Tracer:
Tracer.getCurrentSpan(): use api.getSpan(api.context.active())Tracer.withSpan(span): use api.context.with(api.setSpan(api.context.active(), span))Tracer.bind(target): use api.context.bind(target)PR-1797 chore!: split metrics into its own api package:
require("@opentelemetry/api").metrics will need to be changed to require("@opentelemetry/api-metrics").metricsPR-1725 Use new gRPC default port
@opentelemetry/exporter-collector-grpc is changed from 55680 to 4317PR-1749 chore: improve naming of span related context APIs
[gs]etActiveSpan() to [gs]etSpan()setExtractedSpanContext() to setSpanContext()getParentSpanContext() to getSpanContext()Apache 2.0 - See LICENSE for more information.