@opentelemetry/sdk-node 0.301.1 → 0.302.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +326 -217
  2. package/dist/_virtual/_rolldown/runtime.cjs +1 -2
  3. package/dist/component-provider.cjs +37 -0
  4. package/dist/component-provider.cjs.map +1 -0
  5. package/dist/component-provider.d.cts +40 -0
  6. package/dist/component-provider.d.cts.map +1 -0
  7. package/dist/component-provider.d.mts +40 -0
  8. package/dist/component-provider.d.mts.map +1 -0
  9. package/dist/component-provider.mjs +37 -0
  10. package/dist/component-provider.mjs.map +1 -0
  11. package/dist/create-from-config.cjs +374 -287
  12. package/dist/create-from-config.cjs.map +1 -1
  13. package/dist/create-from-config.mjs +372 -286
  14. package/dist/create-from-config.mjs.map +1 -1
  15. package/dist/create-from-env.cjs +1 -2
  16. package/dist/create-from-env.cjs.map +1 -1
  17. package/dist/create-from-env.mjs +1 -2
  18. package/dist/create-from-env.mjs.map +1 -1
  19. package/dist/diag.cjs +2 -3
  20. package/dist/diag.cjs.map +1 -1
  21. package/dist/diag.mjs +2 -3
  22. package/dist/diag.mjs.map +1 -1
  23. package/dist/index.d.cts +3 -2
  24. package/dist/index.d.mts +3 -2
  25. package/dist/sdk.cjs +2 -3
  26. package/dist/sdk.cjs.map +1 -1
  27. package/dist/sdk.d.cts +3 -6
  28. package/dist/sdk.d.cts.map +1 -1
  29. package/dist/sdk.d.mts +3 -6
  30. package/dist/sdk.d.mts.map +1 -1
  31. package/dist/sdk.mjs +2 -3
  32. package/dist/sdk.mjs.map +1 -1
  33. package/dist/start.cjs +18 -13
  34. package/dist/start.cjs.map +1 -1
  35. package/dist/start.d.cts +3 -5
  36. package/dist/start.d.cts.map +1 -1
  37. package/dist/start.d.mts +3 -5
  38. package/dist/start.d.mts.map +1 -1
  39. package/dist/start.mjs +22 -17
  40. package/dist/start.mjs.map +1 -1
  41. package/dist/types.d.cts +99 -42
  42. package/dist/types.d.cts.map +1 -1
  43. package/dist/types.d.mts +99 -42
  44. package/dist/types.d.mts.map +1 -1
  45. package/dist/utils.cjs +1 -2
  46. package/dist/utils.cjs.map +1 -1
  47. package/dist/utils.mjs +1 -2
  48. package/dist/utils.mjs.map +1 -1
  49. package/package.json +28 -27
package/README.md CHANGED
@@ -5,254 +5,361 @@
5
5
 
6
6
  **Note: This is an experimental package under active development. New releases may include breaking changes.**
7
7
 
8
- This package provides the full OpenTelemetry SDK for Node.js including tracing and metrics.
8
+ The `@opentelemetry/sdk-node` package provides functionality to configure and start a full OpenTelemetry SDK for Node.js including traces, metrics, and logs.
9
+ It does *not* include instrumentations. Many users should consider the [`@opentelemetry/auto-instrumentations-node`](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/auto-instrumentations-node) package, which combines this package and a number of curated instrumentations for popular Node.js modules.
9
10
 
10
- ## Quick Start
11
+ (For usage of OpenTelemetry JS in the browser, please see the [OpenTelemetry Browser repository](https://github.com/open-telemetry/opentelemetry-browser).)
11
12
 
12
- **Note: Much of OpenTelemetry JS documentation is written assuming the compiled application is run as CommonJS.**
13
- For more details on ECMAScript Modules vs CommonJS, refer to [esm-support](https://github.com/open-telemetry/opentelemetry-js/blob/main/doc/esm-support.md).
14
-
15
- To get started you need to install `@opentelemetry/sdk-node`, a metrics and/or tracing exporter, and any appropriate instrumentation for the node modules used by your application.
13
+ ## `NodeSDK` or `startNodeSdk`?
16
14
 
17
- ### Installation
15
+ This package is currently in a transition period from the long-time `new NodeSDK()` class for starting an SDK, to the newer `startNodeSdk()` function.
18
16
 
19
- ```sh
20
- $ # Install the SDK
21
- $ npm install @opentelemetry/sdk-node
17
+ The [`NodeSDK()`](#nodesdk) class:
22
18
 
23
- $ # Install exporters and plugins
24
- $ npm install \
25
- @opentelemetry/exporter-trace-otlp-proto \ # add tracing exporters as needed
26
- @opentelemetry/exporter-prometheus \ # add metrics exporters as needed
27
- @opentelemetry/instrumentation-http # add instrumentations as needed
19
+ - supports configuration via `OTEL_*` environment variables, [per the OpenTelemetry specification](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration), plus some Node.js-specific environment variables; and
20
+ - supports programmatic configuration via options to the constructor
28
21
 
29
- $ # or install all officially supported core and contrib plugins
30
- $ npm install @opentelemetry/auto-instrumentations-node
31
-
32
- ```
22
+ The [`startNodeSdk()`](#startnodesdk) function:
33
23
 
34
- > Note: this example is for Node.js. See [examples/opentelemetry-web](https://github.com/open-telemetry/opentelemetry-js/tree/main/examples/opentelemetry-web) for a browser example.
24
+ - supports the same environment variable configuration;
25
+ - supports programmatic configuration, but with **some changes** to the supported options; and
26
+ - adds support for [Declarative Configuration](https://opentelemetry.io/docs/specs/otel/configuration/#declarative-configuration)
35
27
 
36
- ### Initialize the SDK
28
+ `startNodeSdk()` is currently under active development.
37
29
 
38
- Before any other module in your application is loaded, you must initialize the SDK.
39
- If you fail to initialize the SDK or initialize it too late, no-op implementations will be provided to any library which acquires a tracer or meter from the API.
30
+ ## `startNodeSdk`
40
31
 
41
- This example uses Jaeger (via OTLP) and Prometheus, but exporters exist for [other tracing backends][other-tracing-backends].
42
- OTLP in particular is widely supported by a wide-variety of backends.
43
- As shown in the installation instructions, exporters passed to the SDK must be installed alongside `@opentelemetry/sdk-node`.
32
+ To get started, call the `startNodeSdk()` function.
44
33
 
45
- ```javascript
46
- const opentelemetry = require("@opentelemetry/sdk-node");
47
- const { OTLPTraceExporter } = require("@opentelemetry/exporter-trace-otlp-proto");
48
- const { PrometheusExporter } = require("@opentelemetry/exporter-prometheus");
49
- const {
50
- getNodeAutoInstrumentations,
51
- } = require("@opentelemetry/auto-instrumentations-node");
34
+ ```js
35
+ // telemetry.mjs
36
+ import * as os from 'node:os';
37
+ import { startNodeSdk } from '@opentelemetry/sdk-node';
52
38
 
53
- const otlpExporter = new OTLPTraceExporter();
54
- const prometheusExporter = new PrometheusExporter();
55
-
56
- const sdk = new opentelemetry.NodeSDK({
57
- // Optional - if omitted, the tracing SDK will be initialized from environment variables
58
- traceExporter: otlpExporter,
59
- // Optional - If omitted, the metrics SDK will not be initialized
60
- metricReader: prometheusExporter,
61
- // Optional - you can use the metapackage or load each instrumentation individually
62
- instrumentations: [getNodeAutoInstrumentations()],
63
- // See the Configuration section below for additional configuration options
39
+ const sdk = startNodeSdk({
40
+ resourceAttributes: {
41
+ // It is good practice to at least set `service.name`.
42
+ // https://opentelemetry.io/docs/specs/semconv/resource/service/
43
+ 'service.name': 'my-app',
44
+ },
64
45
  });
65
46
 
66
- sdk.start();
67
-
68
- // You can also use the shutdown method to gracefully shut down the SDK before process shutdown
69
- // or on some operating system signal.
70
- const process = require("process");
71
- process.on("SIGTERM", () => {
72
- sdk
73
- .shutdown()
74
- .then(
75
- () => console.log("SDK shut down successfully"),
76
- (err) => console.log("Error shutting down SDK", err)
77
- )
78
- .finally(() => process.exit(0));
47
+ // It is good practice to call the returned `shutdown` function before process
48
+ // exit, to ensure any buffered telemetry is sent.
49
+ // Error handling for sdk.shutdown() is omitted for brevity.
50
+ process.once('beforeExit', async () => {
51
+ await sdk.shutdown();
52
+ });
53
+ process.on('SIGTERM', async () => {
54
+ await sdk.shutdown();
55
+ process.exit(128 + os.constants.signals.SIGTERM);
79
56
  });
80
57
  ```
81
58
 
82
- ## Configuration
83
-
84
- Below is a full list of configuration options which may be passed into the `NodeSDK` constructor;
85
-
86
- ### autoDetectResources
87
-
88
- Detect resources automatically from the environment using the default resource detectors. Default `true`.
89
-
90
- ### contextManager
91
-
92
- Use a custom context manager. Default: [AsyncLocalStorageContextManager](../../../packages/opentelemetry-context-async-hooks/README.md)
93
-
94
- ### textMapPropagator
95
-
96
- Use a custom propagator. Default: [CompositePropagator](../../../packages/opentelemetry-core/src/propagation/composite.ts) using [W3C Trace Context](../../../packages/opentelemetry-core/README.md#w3ctracecontextpropagator-propagator) and [Baggage](../../../packages/opentelemetry-core/README.md#baggage-propagator)
97
-
98
- ### logRecordProcessor
99
-
100
- Deprecated, please use [logRecordProcessors](#logrecordprocessors) instead.
101
-
102
- ### logRecordProcessors
103
-
104
- An array of log record processors to register to the logger provider.
105
-
106
- ### metricReader
107
-
108
- Add a [MetricReader](../../../packages/sdk-metrics/src/export/MetricReader.ts)
109
- that will be passed to the `MeterProvider`. If `metricReader` is not configured,
110
- the metrics SDK will not be initialized and registered.
111
-
112
- ### views
113
-
114
- A list of views to be passed to the `MeterProvider`.
115
- Accepts an array of [View](../../../packages/sdk-metrics/src/view/View.ts)-instances.
116
- This parameter can be used to configure explicit bucket sizes of histogram metrics.
117
-
118
- ### instrumentations
119
-
120
- Configure instrumentations. By default none of the instrumentation is enabled,
121
- if you want to enable them you can use either [metapackage](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/auto-instrumentations-node)
122
- or configure each instrumentation individually.
123
-
124
- ### resource
125
-
126
- A [Resource](https://opentelemetry.io/docs/specs/otel/resource/sdk/) to associate with generated telemetry.
127
- This resource will be use as the basis for additional resource attributes determined by [resource detectors](#resourcedetectors).
128
- See also the [`autoDetectResources` setting](#autodetectresources).
129
-
130
- If not specified, the [default resource](https://opentelemetry.io/docs/specs/semconv/resource/#semantic-attributes-with-sdk-provided-default-value) will be used.
131
-
132
- > [!WARNING]
133
- > If specifying the `resource` option, it is recommended that the default resource be included.
134
- > Otherwise the important `service.name` and `telemetry.sdk.*` resource attributes might not be included on telemetry,
135
- > which can adversely impact downstream processing or visualization.
136
- > The default resource can be include as follows:
137
- >
138
- > ```js
139
- > import { NodeSDK } from '@opentelemetry/sdk-node';
140
- > import { resourceFromAttributes, defaultResource } from '@opentelemetry/resources';
141
- > const sdk = new NodeSDK({
142
- > resource: defaultResource().merge(
143
- > resourceFromAttributes({
144
- > 'my.custom.attr': 'some value',
145
- > })
146
- > ),
147
- > // ...
148
- > });
149
- > ```
150
- >
151
- > Alternatively, consider setting custom resource attributes via the
152
- > [`OTEL_RESOURCE_ATTRIBUTES`](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration)
153
- > environment variable.
154
-
155
- ### resourceDetectors
156
-
157
- Configure resource detectors.
158
- If not specified, then detectors will be determined from the `OTEL_NODE_RESOURCE_DETECTORS` environment variable.
159
- If neither is specified, the default set of detectors is `[serviceInstanceIdDetector, processDetector, hostDetector, osDetector, envDetector]`.
160
- NOTE: In order to enable the detection, the parameter `autoDetectResources` has to be `true`.
161
-
162
- `OTEL_NODE_RESOURCE_DETECTORS` is a comma-separated list of the following detector names:
163
-
164
- - `host`
165
- - `os`
166
- - `process`
167
- - `serviceinstance` - provides the `service.instance.id` attribute
168
- - `env` - reads attributes from `OTEL_RESOURCE_ATTRIBUTES` and `OTEL_SERVICE_NAME`
169
- - `all` - enable all resource detectors above
170
- - **NOTE:** future versions of `@opentelemetry/sdk-node` may include additional detectors that will be covered by this scope.
171
- - `none` - disable resource detection
59
+ Typically you will want to include some instrumentations, to get automatic
60
+ telemetry from common npm packages that your application uses:
61
+
62
+ ```js
63
+ // telemetry.mjs
64
+ // ...
65
+
66
+ // For example, explicitly provide some instrumentations:
67
+ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
68
+ import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';
69
+ const sdk = startNodeSdk({
70
+ // ...
71
+ instrumentations: [
72
+ new HttpInstrumentation(),
73
+ new ExpressInstrumentation(),
74
+ ],
75
+ });
172
76
 
173
- For example, to enable only the `process` and `env` detectors:
77
+ // OR, use the curated and supported set of instrumentations from the
78
+ // auto-instrumentations-node package.
79
+ import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
80
+ const sdk = startNodeSdk({
81
+ // ...
82
+ instrumentations: getNodeAutoInstrumentations(),
83
+ });
174
84
 
175
- ```shell
176
- export OTEL_NODE_RESOURCE_DETECTORS="process,env"
85
+ // ...
177
86
  ```
178
87
 
179
- Detectors are processed in the order they are defined. Attributes from a later detector wins.
180
- You typically want the 'env' detector to be last, so that attributes explicitly set by `OTEL_RESOURCE_ATTRIBUTES` will win over the same attribute from an earlier detector.
181
- For example with `OTEL_RESOURCE_ATTRIBUTES="service.instance.id=custom-name"` and `OTEL_NODE_RESOURCE_DETECTORS=env,serviceinstance` the "custom-name" value will be lost to the `service.instance.id` value from the "serviceinstance" detector.
182
-
183
- ### sampler
184
-
185
- Configure a custom sampler. By default, all traces will be sampled.
186
-
187
- ### spanProcessor
188
-
189
- Deprecated, please use [spanProcessors](#spanprocessors) instead.
190
-
191
- ### spanProcessors
192
-
193
- An array of span processors to register to the tracer provider.
194
-
195
- ### traceExporter
196
-
197
- Configure a trace exporter. If an exporter is configured, it will be used with a [BatchSpanProcessor](../../../packages/sdk-trace/src/platform/node/export/BatchSpanProcessor.ts). If an exporter OR span processor is not configured programmatically, this package will auto setup the default `otlp` exporter with `http/protobuf` protocol with a `BatchSpanProcessor`.
198
-
199
- ### spanLimits
200
-
201
- Configure tracing parameters. These are the same trace parameters used to [configure a tracer](../../../packages/sdk-trace/src/types.ts#L20).
202
-
203
- ### serviceName
204
-
205
- Configure the [service name](https://github.com/open-telemetry/semantic-conventions/blob/main/docs/registry/attributes/service.md#service-name).
206
-
207
- ## Disable the SDK from the environment
208
-
209
- Disable the SDK by setting the `OTEL_SDK_DISABLED` environment variable to `true`.
210
-
211
- ## Configure log level from the environment
212
-
213
- Set the log level by setting the `OTEL_LOG_LEVEL` environment variable to enums:
214
-
215
- - `NONE`,
216
- - `ERROR`,
217
- - `WARN`,
218
- - `INFO`,
219
- - `DEBUG`,
220
- - `VERBOSE`,
221
- - `ALL`.
88
+ Then use Node.js `--import` to load this SDK bootstrap file before your
89
+ application starts. Many instrumentations need to start before application code
90
+ loads the modules to be instrumented. A good way (but not the only way) to
91
+ ensure that, is to use `--import`.
222
92
 
223
- The default level is `INFO`.
93
+ ```bash
94
+ node --import ./telemetry.mjs app.js
95
+ ```
224
96
 
225
- ## Configure Exporters from environment
97
+ **Note: Much of OpenTelemetry JS documentation is written assuming the compiled application is run as CommonJS.**
98
+ For more details on ECMAScript Modules vs CommonJS, refer to [esm-support](https://github.com/open-telemetry/opentelemetry-js/blob/main/doc/esm-support.md).
226
99
 
227
- This is an alternative to programmatically configuring an exporter or span processor. For traces this package will auto setup the default `otlp` exporter with `http/protobuf` protocol if `traceExporter` or `spanProcessor` hasn't been passed into the `NodeSDK` constructor.
100
+ ### startNodeSdk Configuration
101
+
102
+ When calling `startNodeSdk()`, how the SDK is configured is determined as follows:
103
+
104
+ 1. If the `OTEL_CONFIG_FILE` environment variable is set, the file it points to
105
+ is processed as a [Declarative Config](https://opentelemetry.io/docs/specs/otel/configuration/#declarative-configuration)
106
+ YAML file that fully describes the SDK.
107
+ See the [declarative config example](../../examples/declarative-config/).
108
+
109
+ With declarative config, **none of the `OTEL_*` environment variables are used** (unless they are specifically referenced in the YAML file).
110
+ As well, most of the programmatic options to `startNodeSdk()` are ignored.
111
+ The only programmatic options used with declarative config are:
112
+ `instrumentations`, `componentProviderRegistries`, and `customizeConfig`.
113
+ See [`interface StartSdkFromConfigOptions`](https://open-telemetry.github.io/opentelemetry-js/interfaces/_opentelemetry_sdk-node.StartSdkFromConfigOptions.html) in the API docs.
114
+
115
+ 2. Otherwise, the SDK is configured from (a) programmatic options to `startNodeSdk()`, and (b) `OTEL_*` environment variables.
116
+
117
+ Programmatic options include `logLevel`, `resourceAttributes`, `spanProcessors`, etc.
118
+ See [`interface StartSdkFromEnvOptions`](https://open-telemetry.github.io/opentelemetry-js/interfaces/_opentelemetry_sdk-node.StartSdkFromEnvOptions.html) in the API docs.
119
+ **Note**: These options differ from `new NodeSDK()`. See the [Migrating from `NodeSDK` to `startNodeSdk`](#migrating-from-nodesdk-to-startnodesdk) below.
120
+
121
+ If programmatic options for a component are not given, then a default
122
+ component is created configured with relevant `OTEL_*` envvars.
123
+ The full set of `OTEL_*` envvars described [by the spec](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration)
124
+ are supported, plus a few Node.js-specific `OTEL_NODE_*` envvars.
125
+ See [Environment Variable Configuration](#environment-variable-configuration) below.
126
+
127
+ ## Migrating from `NodeSDK` to `startNodeSdk`
128
+
129
+ If migrating from `new NodeSDK(...)` to `startNodeSdk(...)`, there are number of differences in the programmatic options and environment variables.
130
+
131
+ - **Default diagnostic log level is "info"**.
132
+ With `NodeSDK` if the `OTEL_LOG_LEVEL` envvar was not set, then *no diagnostic logger was created*.
133
+ This meant that SDK `diag.warn` and `diag.error` messages were not printed.
134
+ To get the old behavior use:
135
+
136
+ ```js
137
+ import { getStringFromEnv } from '@opentelemetry/core';
138
+ const logLevel = getStringFromEnv('OTEL_LOG_LEVEL') ?? 'none';
139
+ startNodeSdk({ logLevel });
140
+ ```
141
+
142
+ - Options to configure the *Resource* have changed:
143
+ - Dropped the unnecessary `autoDetectResources`. To disable resource detection, pass in `resourceDetectors: []`.
144
+ - **Replaced `resource` with `resourceAttributes`** and `baseResource`.
145
+ [`resource` is a footgun](https://github.com/open-telemetry/opentelemetry-js/pull/6988#discussion_r3754084464) that was frequently used incorrectly.
146
+ Naive usage would result in the spec-mandated `service.name` fallback value and `telemetry.sdk.*` attributes *not* being set.
147
+ Most users will never need to use `baseResource`.
148
+ - Dropped `serviceName`: Use `resourceAttributes`, for example:
149
+
150
+ ```js
151
+ resourceAttributes: {
152
+ 'service.name': 'my-svc',
153
+ 'service.version': '1.2.3',
154
+ }
155
+ ```
156
+
157
+ - The **mapping of resource detector names to functionality in the `OTEL_NODE_RESOURCE_DETECTORS` envvar has changed.**
158
+ Note that the *default* behavior, if the envvar is not specified, *has not changed*.
159
+
160
+ With `NodeSDK`:
161
+ - `host`: `host.*` resource attributes
162
+ - `os`: `os.*` resource attributes
163
+ - `serviceinstance`: `service.instance.id` resource attribute
164
+ - `process`: `process.*` resource attributes
165
+ - `env`: reads `service.name` from the `OTEL_SERVICE_NAME` envvar and
166
+ attributes from the `OTEL_RESOURCE_ATTRIBUTES` envvar
167
+ - `all`: special value indicating that all of the above detectors should be used
168
+ - `none`: special value indicating that no resource detectors should be used
169
+
170
+ With `startNodeSdk` the names and semantics have changed to conform with
171
+ the spec requirement that [`OTEL_RESOURCE_ATTRIBUTES` is always read](https://opentelemetry.io/docs/specs/otel/resource/sdk/#specifying-resource-information-via-an-environment-variable)
172
+ and some [recommended names from the declarative config schema](https://github.com/open-telemetry/opentelemetry-configuration/blob/v1.2.0/schema/resource.yaml#L110-L139). Changes are in bold.
173
+ - **`host`**: `host.*` and `os.*` resource attributes
174
+ - **`service`**: reads `service.name` from the `OTEL_SERVICE_NAME` envvar and sets `service.instance.id`
175
+ - `process`: `process.*` resource attributes
176
+ - `all`: special value indicating that all of the above detectors should be used
177
+ - `none`: special value indicating that no resource detectors should be used
178
+ - **Removed** `os`, `serviceinstance`, and `env`.
179
+ - **`OTEL_RESOURCE_ATTRIBUTES` is always read.** It no longer requires specifying the `env` detector name.
180
+
181
+ - Dropped `traceExporter`.
182
+ This overlaps with `spanProcessors`, which can lead to some confusion. Use one of:
183
+ - `OTEL_TRACES_EXPORTER` environment variable
184
+ - `spanProcessors` option, e.g.:
185
+ `spanProcessors: [new BatchSpanProcessor({ exporter: myTraceExporter })],`
186
+ Note: Using this example means that `OTEL_BSP_` environment variables to configure the `BatchSpanProcessor` are not read.
187
+
188
+ - Dropped `contextManager`.
189
+ Node.js users should always want `AsyncLocalStorageContextManager`, which is used by default.
190
+ This option can be re-added later if there is a demonstrable need.
191
+
192
+ - Dropped `idGenerator`.
193
+ All users should want the `RandomIdGenerator` used by default by the `@opentelemetry/sdk-trace` package.
194
+ This option can be re-added later if there is a demonstrable need.
195
+
196
+ There are also some new options:
197
+
198
+ - New `logLevel` option.
199
+ With `NodeSDK` the diagnostic log level can only be set via `OTEL_LOG_LEVEL`.
200
+ - New `logRecordLimits` option.
201
+ Added for parity with the existing `spanLimits`.
202
+
203
+ ## `NodeSDK`
204
+
205
+ To get started, create a `NodeSDK` instance and `.start()` it.
206
+
207
+ ```js
208
+ // telemetry.mjs
209
+ import * as os from 'node:os';
210
+ import { NodeSDK } from '@opentelemetry/sdk-node';
211
+
212
+ const sdk = new NodeSDK({
213
+ // It is good practice to at least set `service.name`.
214
+ // https://opentelemetry.io/docs/specs/semconv/resource/service/
215
+ serviceName: 'my-app',
216
+ });
217
+ sdk.start();
228
218
 
229
- ### Exporters
219
+ // It is good practice to call the returned `shutdown` function before process
220
+ // exit, to ensure any buffered telemetry is sent.
221
+ // Error handling for sdk.shutdown() is omitted for brevity.
222
+ process.once('beforeExit', async () => {
223
+ await sdk.shutdown();
224
+ });
225
+ process.on('SIGTERM', async () => {
226
+ await sdk.shutdown();
227
+ process.exit(128 + os.constants.signals.SIGTERM);
228
+ });
229
+ ```
230
230
 
231
- | Environment variable | Description |
232
- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
233
- | OTEL_TRACES_EXPORTER | List of exporters to be used for tracing, separated by commas. Options include `otlp`, `zipkin`, and `none`. Default is `otlp`. `none` means no autoconfigured exporter. |
234
- | OTEL_LOGS_EXPORTER | List of exporters to be used for logging, separated by commas. Options include `otlp`, `console` and `none`. Default is `otlp`. `none` means no autoconfigured exporter. |
231
+ Typically you will want to include some instrumentations, to get automatic
232
+ telemetry from common npm packages that your application uses:
233
+
234
+ ```js
235
+ // telemetry.mjs
236
+ // ...
237
+
238
+ // For example, explicitly provide some instrumentations:
239
+ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
240
+ import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';
241
+ const sdk = new NodeSDK({
242
+ // ...
243
+ instrumentations: [
244
+ new HttpInstrumentation(),
245
+ new ExpressInstrumentation(),
246
+ ],
247
+ });
235
248
 
236
- ### OTLP Exporter
249
+ // OR, use the curated and supported set of instrumentations from the
250
+ // auto-instrumentations-node package.
251
+ import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
252
+ const sdk = new NodeSDK({
253
+ // ...
254
+ instrumentations: getNodeAutoInstrumentations(),
255
+ });
237
256
 
238
- | Environment variable | Description |
239
- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
240
- | OTEL_EXPORTER_OTLP_PROTOCOL | The transport protocol to use on OTLP trace, metric, and log requests. Options include `grpc`, `http/protobuf`, and `http/json`. Default is `http/protobuf`. |
241
- | OTEL_EXPORTER_OTLP_TRACES_PROTOCOL | The transport protocol to use on OTLP trace requests. Options include `grpc`, `http/protobuf`, and `http/json`. Default is `http/protobuf`. |
242
- | OTEL_EXPORTER_OTLP_METRICS_PROTOCOL | The transport protocol to use on OTLP metric requests. Options include `grpc`, `http/protobuf`, and `http/json`. Default is `http/protobuf`. |
243
- | OTEL_EXPORTER_OTLP_LOGS_PROTOCOL | The transport protocol to use on OTLP log requests. Options include `grpc`, `http/protobuf`, and `http/json`. Default is `http/protobuf`. |
244
- | OTEL_METRICS_EXPORTER | Metrics exporter to be used. options are `otlp`, `prometheus`, `console` or `none`. Default is `otlp`. |
245
- | OTEL_METRIC_EXPORT_INTERVAL | The export interval when using a push Metric Reader. Default is `60000`. |
246
- | OTEL_METRIC_EXPORT_TIMEOUT | The export timeout when using a push Metric Reader. Default is `30000`. |
257
+ // ...
258
+ ```
247
259
 
248
- Additionally, you can specify other applicable environment variables that apply to each exporter such as the following:
260
+ Then use Node.js `--import` to load this SDK bootstrap file before your
261
+ application starts. Many instrumentations need to start before application code
262
+ loads the modules to be instrumented. A good way (but not the only way) to
263
+ ensure that, is to use `--import`.
249
264
 
250
- - [OTLP exporter environment configuration](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options)
251
- - [Zipkin exporter environment configuration](https://github.com/open-telemetry/opentelemetry-specification/blob/6ce62202e5407518e19c56c445c13682ef51a51d/specification/sdk-environment-variables.md#zipkin-exporter)
265
+ ```bash
266
+ node --import ./telemetry.mjs app.js
267
+ ```
252
268
 
253
- ## Enable OpenTelemetry SDK internal metrics from environment
269
+ **Note: Much of OpenTelemetry JS documentation is written assuming the compiled application is run as CommonJS.**
270
+ For more details on ECMAScript Modules vs CommonJS, refer to [esm-support](https://github.com/open-telemetry/opentelemetry-js/blob/main/doc/esm-support.md).
254
271
 
255
- OpenTelemetry defines [metrics for monitoring SDK components](https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/).
272
+ ### NodeSDK Configuration
273
+
274
+ When creating a `new NodeSDK()`, the SDK is configured from (a) programmatic options, and (b) `OTEL_*` environment variables.
275
+
276
+ Programmatic options include `serviceName`, `spanProcessors`, `sampler`, etc.
277
+ See [`interface NodeSDKConfiguration`](https://open-telemetry.github.io/opentelemetry-js/interfaces/_opentelemetry_sdk-node.NodeSDKConfiguration.html) in the API docs.
278
+ **Note**: These options differ from `startNodeSdk()`. See the [Migrating from `NodeSDK` to `startNodeSdk`](#migrating-from-nodesdk-to-startnodesdk).
279
+
280
+ If programmatic options for a component are not given, then a default component
281
+ is created configured with relevant `OTEL_*` envvars.
282
+ The full set of `OTEL_*` envvars described [by the spec](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration)
283
+ are supported, plus a few Node.js-specific `OTEL_NODE_*` envvars.
284
+ See [Environment Variable Configuration](#environment-variable-configuration) below.
285
+
286
+ ## Environment Variable Configuration
287
+
288
+ `OTEL_*` environment variables may be used to configure SDK components.
289
+ For both `startNodeSdk()` and `NodeSDK()`, the full set of `OTEL_*` envvars described [by the spec](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration)
290
+ are supported.
291
+ Some common SDK environment variables are:
292
+
293
+ - `OTEL_EXPORTER_OTLP_ENDPOINT` and `OTEL_EXPORTER_OTLP_HEADERS` are commonly used to specify where the SDK should send telemetry data and any required authentication information.
294
+ - `OTEL_SERVICE_NAME`: Set the important `service.name` resource attribute.
295
+ - `OTEL_SDK_DISABLED`: Setting `OTEL_SDK_DISABLED=true` can be useful to temporarily disable the SDK for debugging.
296
+ - `OTEL_LOG_LEVEL`: See below.
297
+ - [`OTEL_TRACES_EXPORTER`, `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#exporter-selection)
298
+ can be useful to disable a signal (`OTEL_METRICS_EXPORTER=none`)
299
+ or to duplicate telemetry to stdout for debugging (`OTEL_TRACES_EXPORTER=otlp,console`).
300
+ - `OTEL_CONFIG_FILE`: Specify a [Declarative Config](https://opentelemetry.io/docs/specs/otel/configuration/#declarative-configuration) YAML file to fully specify the SDK config. (*Note*: this is not supported by `NodeSDK`. Use `startNodeSdk()`.)
301
+
302
+ In addition, a few Node.js-specific `OTEL_NODE_*` environment variables are also used. These are described here.
303
+
304
+ ### `OTEL_LOG_LEVEL`
305
+
306
+ Though `OTEL_LOG_LEVEL` is specify in [the spec](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration),
307
+ the particular values supported vary between languages.
308
+ For Node.js the values supported are (case-insensitive):
309
+
310
+ - `NONE`
311
+ - `ERROR`
312
+ - `WARN`
313
+ - `INFO`
314
+ - `DEBUG`
315
+ - `VERBOSE`
316
+ - `ALL`
317
+
318
+ With `startNodeSdk()` the default level is `INFO`.
319
+ With `NodeSDK()` the default level is effectively `NONE`: if `OTEL_LOG_LEVEL` is
320
+ not set, then no diagnostic logger is created.
321
+
322
+ ### `OTEL_NODE_RESOURCE_DETECTORS`
323
+
324
+ `OTEL_NODE_RESOURCE_DETECTORS` is a comma-separated list of the detector names.
325
+ If not specified, the *default behavior* is that all of the following resource
326
+ detectors are used.
327
+
328
+ The default behavior is the same with `startNodeSdk()` and `NodeSDK()`.
329
+ However, if `OTEL_NODE_RESOURCE_DETECTORS` is specified then the supported
330
+ detector names and semantics **differs between `startNodeSdk()` and `NodeSDK`.
331
+
332
+ With `NodeSDK`:
333
+
334
+ - `host`: `host.*` resource attributes
335
+ - `os`: `os.*` resource attributes
336
+ - `serviceinstance`: `service.instance.id` resource attribute
337
+ - `process`: `process.*` resource attributes
338
+ - `env`: reads `service.name` from the `OTEL_SERVICE_NAME` envvar and
339
+ attributes from the `OTEL_RESOURCE_ATTRIBUTES` envvar
340
+ - `all`: special value indicating that all of the above detectors should be used
341
+ - `none`: special value indicating that no resource detectors should be used
342
+
343
+ When using `NodeSDK` one should always specify the `env` detector *last*,
344
+ e.g. `OTEL_NODE_RESOURCE_DETECTORS=os,serviceinstance,env`. This is because
345
+ the *last* detector wins. If `OTEL_RESOURCE_ATTRIBUTES` attempts to override
346
+ an attribute value from another detector, then it should win.
347
+
348
+ With `startNodeSdk` the names and semantics have changed to conform with
349
+ the spec requirement that [`OTEL_RESOURCE_ATTRIBUTES` is always read](https://opentelemetry.io/docs/specs/otel/resource/sdk/#specifying-resource-information-via-an-environment-variable)
350
+ and some [recommended names from the declarative config schema](https://github.com/open-telemetry/opentelemetry-configuration/blob/v1.2.0/schema/resource.yaml#L110-L139). Changes are in bold.
351
+
352
+ - **`host`**: `host.*` and `os.*` resource attributes
353
+ - **`service`**: reads `service.name` from the `OTEL_SERVICE_NAME` envvar and sets `service.instance.id`
354
+ - `process`: `process.*` resource attributes
355
+ - `all`: special value indicating that all of the above detectors should be used
356
+ - `none`: special value indicating that no resource detectors should be used
357
+ - **Removed** `os`, `serviceinstance`, and `env`.
358
+ - **`OTEL_RESOURCE_ATTRIBUTES` is always read.** It no longer requires specifying the `env` detector name.
359
+
360
+ ### `OTEL_NODE_EXPERIMENTAL_SDK_METRICS`
361
+
362
+ OpenTelemetry defines internal [metrics for self-monitoring of SDK components](https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/).
256
363
  Until this spec is stabilized, the following environment variable must be used
257
364
  to enable these metrics:
258
365
 
@@ -267,6 +374,9 @@ linkes for details:
267
374
  - Logger metrics: [LoggerMetrics.ts](../sdk-logs/src/LoggerMetrics.ts)
268
375
  - Span metrics: [TracerMetrics.ts](../../../packages/sdk-trace/src/TracerMetrics.ts)
269
376
 
377
+ Limitation: When using `startNodeSdk()` and declarative config (via `OTEL_CONFIG_FILE`)
378
+ there is currently **no way** to enable SDK self-monitoring metrics.
379
+
270
380
  ## Useful links
271
381
 
272
382
  - For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
@@ -282,4 +392,3 @@ Apache 2.0 - See [LICENSE][license-url] for more information.
282
392
  [license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat
283
393
  [npm-url]: https://www.npmjs.com/package/@opentelemetry/sdk-node
284
394
  [npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fsdk-node.svg
285
- [other-tracing-backends]: https://github.com/open-telemetry/opentelemetry-js#trace-exporters
@@ -1,4 +1,4 @@
1
- //#region \0rolldown/runtime.js
1
+ // \0rolldown/runtime.js
2
2
  var __create = Object.create;
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -19,5 +19,4 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
19
19
  value: mod,
20
20
  enumerable: true
21
21
  }) : target, mod));
22
- //#endregion
23
22
  exports.__toESM = __toESM;
@@ -0,0 +1,37 @@
1
+ // src/component-provider.ts
2
+ /**
3
+ * Merge multiple `ComponentProviderRegistry`'s into one.
4
+ *
5
+ * Generally a collision (two registries providing for the same component type
6
+ * and name) is an *error*. The same is true for collisions with the built-in registry.
7
+ *
8
+ * @throws {Error} if multiple registries provided in `regs` attempt to provide
9
+ * for the same component type and name.
10
+ */
11
+ function mergeComponentProviderRegistries(builtinReg, regs) {
12
+ const mergedReg = {};
13
+ const componentTypes = [
14
+ "ExperimentalResourceDetector",
15
+ "TextMapPropagator",
16
+ "SpanExporter",
17
+ "SpanProcessor",
18
+ "Sampler",
19
+ "IdGenerator",
20
+ "PushMetricExporter",
21
+ "MetricProducer",
22
+ "LogRecordExporter",
23
+ "LogRecordProcessor"
24
+ ];
25
+ for (const reg of [builtinReg, ...regs ?? []]) for (const componentType of componentTypes) {
26
+ const providerFromName = reg[componentType];
27
+ if (providerFromName !== void 0) for (const name of Object.keys(providerFromName)) if (mergedReg[componentType]?.[name]) throw new Error(`a ComponentProvider of type "${componentType}" and name="${name}" is already registered: ${mergedReg[componentType]?.[name]}`);
28
+ else {
29
+ mergedReg[componentType] ??= {};
30
+ mergedReg[componentType][name] = providerFromName[name];
31
+ }
32
+ }
33
+ return mergedReg;
34
+ }
35
+ exports.mergeComponentProviderRegistries = mergeComponentProviderRegistries;
36
+
37
+ //# sourceMappingURL=component-provider.cjs.map