@devopsplaybook.io/otel-utils 1.12.0-beta.44.7e03cb8 → 1.13.0-beta.45.6c6faf5

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.
package/README.md CHANGED
@@ -14,36 +14,75 @@ Requires Node.js 22 or newer (`engines` in `package.json`).
14
14
 
15
15
  All classes accept a `ConfigOTelInterface` object. The fields mirror environment variables in the consuming application (for example `common-utils`' `ConfigBase`); the library itself does not read `process.env`.
16
16
 
17
- | Field | Type | Default | Description |
18
- | --------------------------------------------------------- | --------------------------------------------------- | ---------- | --------------------------------------------------------- |
19
- | `SERVICE_ID` | `string` | — | Service identifier (required, non-empty) |
20
- | `VERSION` | `string` | — | Service version (required, non-empty) |
21
- | `OPENTELEMETRY_COLLECTOR_HTTP_TRACES` | `string?` | — | OTLP HTTP endpoint for traces |
22
- | `OPENTELEMETRY_COLLECTOR_HTTP_METRICS` | `string?` | — | OTLP HTTP endpoint for metrics |
23
- | `OPENTELEMETRY_COLLECTOR_HTTP_LOGS` | `string?` | — | OTLP HTTP endpoint for logs |
24
- | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_INTERVAL_SECONDS` | `number?` | `60` | Log export interval in seconds (clamped to ≥ 1) |
25
- | `OPENTELEMETRY_COLLECTOR_EXPORT_METRICS_INTERVAL_SECONDS` | `number?` | `60` | Metrics export interval in seconds (clamped to ≥ 1) |
26
- | `OPENTELEMETRY_COLLECTOR_EXPORT_TRACES_INTERVAL_SECONDS` | `number?` | `5` | Trace export interval in seconds (clamped to ≥ 1) |
27
- | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_MAX_QUEUE_SIZE` | `number?` | `2048` | Max log records buffered before export |
28
- | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_MAX_BATCH_SIZE` | `number?` | `512` | Max log records per export batch |
29
- | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_TIMEOUT_MILLIS` | `number?` | `30000` | Log export timeout in milliseconds |
30
- | `OPENTELEMETRY_COLLECTOR_EXPORT_TRACES_MAX_QUEUE_SIZE` | `number?` | `2048` | Max spans buffered before export |
31
- | `OPENTELEMETRY_COLLECTOR_EXPORT_TRACES_MAX_BATCH_SIZE` | `number?` | `512` | Max spans per export batch |
32
- | `OPENTELEMETRY_COLLECTOR_EXPORT_TRACES_TIMEOUT_MILLIS` | `number?` | `30000` | Trace export timeout in milliseconds |
33
- | `OPENTELEMETRY_COLLECTOR_EXPORT_METRICS_TIMEOUT_MILLIS` | `number?` | `30000` | Metrics reader export timeout (clamped to the interval) |
34
- | `OPENTELEMETRY_COLLECTOR_HTTP_HEADERS` | `Record<string, string>?` | `{}` | Extra OTLP HTTP headers for all signals |
35
- | `OPENTELEMETRY_COLLECTOR_HTTP_TIMEOUT_MILLIS` | `number?` | `10000` | Per-request OTLP HTTP exporter timeout |
36
- | `OPENTELEMETRY_COLLECTOR_HTTP_COMPRESSION` | `"gzip" \| "none"` | `"none"` | OTLP HTTP request compression |
37
- | `OPENTELEMETRY_CONSOLE_LOG_MODE` | `"always" \| "fallback" \| "never"` | `"always"` | Console mirroring mode for `ModuleLogger` |
38
- | `OPENTELEMETRY_LOG_LEVEL` | `"trace" \| "debug" \| "info" \| "warn" \| "error"` | `"info"` | Minimum level emitted to OTel and mirrored to the console |
39
- | `OPENTELEMETRY_COLLECT_AUTHORIZATION_HEADER` | `string?` | — | Bearer token for collector auth |
17
+ | Field | Type | Default | Description |
18
+ | --------------------------------------------------------- | --------------------------------------------------- | ----------------------- | --------------------------------------------------------- |
19
+ | `SERVICE_ID` | `string` | — | Service identifier (required, non-empty) |
20
+ | `VERSION` | `string` | — | Service version (required, non-empty) |
21
+ | `SERVICE_INSTANCE_ID` | `string?` | — | Opt-in `service.instance.id` resource attribute |
22
+ | `DEPLOYMENT_ENVIRONMENT_NAME` | `string?` | — | Opt-in `deployment.environment.name` resource attribute |
23
+ | `OPENTELEMETRY_RESOURCE_ATTRIBUTES` | `Record<string, string \| number \| boolean>?` | `{}` | Extra resource attributes shared by all three signals |
24
+ | `OPENTELEMETRY_TRACES_SAMPLER` | `TraceSampler?` | `parentbased_always_on` | Trace sampler — see [Trace sampling](#trace-sampling) |
25
+ | `OPENTELEMETRY_TRACES_SAMPLER_ARG` | `number?` | `1` | Sample ratio for the `*traceidratio` samplers, in `[0,1]` |
26
+ | `OPENTELEMETRY_COLLECTOR_HTTP_TRACES` | `string?` | — | OTLP HTTP endpoint for traces |
27
+ | `OPENTELEMETRY_COLLECTOR_HTTP_METRICS` | `string?` | — | OTLP HTTP endpoint for metrics |
28
+ | `OPENTELEMETRY_COLLECTOR_HTTP_LOGS` | `string?` | — | OTLP HTTP endpoint for logs |
29
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_INTERVAL_SECONDS` | `number?` | `60` | Log export interval in seconds (clamped to ≥ 1) |
30
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_METRICS_INTERVAL_SECONDS` | `number?` | `60` | Metrics export interval in seconds (clamped to ≥ 1) |
31
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_TRACES_INTERVAL_SECONDS` | `number?` | `5` | Trace export interval in seconds (clamped to ≥ 1) |
32
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_MAX_QUEUE_SIZE` | `number?` | `2048` | Max log records buffered before export |
33
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_MAX_BATCH_SIZE` | `number?` | `512` | Max log records per export batch |
34
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_TIMEOUT_MILLIS` | `number?` | `30000` | Log export timeout in milliseconds |
35
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_TRACES_MAX_QUEUE_SIZE` | `number?` | `2048` | Max spans buffered before export |
36
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_TRACES_MAX_BATCH_SIZE` | `number?` | `512` | Max spans per export batch |
37
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_TRACES_TIMEOUT_MILLIS` | `number?` | `30000` | Trace export timeout in milliseconds |
38
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_METRICS_TIMEOUT_MILLIS` | `number?` | `30000` | Metrics reader export timeout (clamped to the interval) |
39
+ | `OPENTELEMETRY_COLLECTOR_HTTP_HEADERS` | `Record<string, string>?` | `{}` | Extra OTLP HTTP headers for all signals |
40
+ | `OPENTELEMETRY_COLLECTOR_HTTP_TIMEOUT_MILLIS` | `number?` | `10000` | Per-request OTLP HTTP exporter timeout |
41
+ | `OPENTELEMETRY_COLLECTOR_HTTP_COMPRESSION` | `"gzip" \| "none"` | `"none"` | OTLP HTTP request compression |
42
+ | `OPENTELEMETRY_CONSOLE_LOG_MODE` | `"always" \| "fallback" \| "never"` | `"always"` | Console mirroring mode for `ModuleLogger` |
43
+ | `OPENTELEMETRY_LOG_LEVEL` | `"trace" \| "debug" \| "info" \| "warn" \| "error"` | `"info"` | Minimum level emitted to OTel and mirrored to the console |
44
+ | `OPENTELEMETRY_COLLECT_AUTHORIZATION_HEADER` | `string?` | — | Bearer token for collector auth |
40
45
 
41
46
  `SERVICE_ID` and `VERSION` must be non-empty strings. `StandardTracer`/`StandardMeter` constructors and `StandardLogger.initOTel` fail fast with `[otel-utils] SERVICE_ID must be a non-empty string` / `[otel-utils] VERSION must be a non-empty string` otherwise. A failed re-initialisation of `StandardLogger` keeps the previous provider in place.
42
47
 
48
+ `SERVICE_INSTANCE_ID` and `DEPLOYMENT_ENVIRONMENT_NAME` are optional: `undefined` or a blank/whitespace-only string means "unset", any other non-string value throws `[otel-utils] <VARIABLE> must be a string when set`. `OPENTELEMETRY_RESOURCE_ATTRIBUTES` must be an object whose values are strings, finite numbers or booleans; anything else throws an `Error` naming `OPENTELEMETRY_RESOURCE_ATTRIBUTES` and the offending key. An invalid `OPENTELEMETRY_TRACES_SAMPLER` logs one `console.warn` and falls back to `parentbased_always_on`; a missing or invalid `OPENTELEMETRY_TRACES_SAMPLER_ARG` for the ratio samplers logs one `console.warn` and falls back to `1` (see [Trace sampling](#trace-sampling)).
49
+
43
50
  Numeric export intervals below 1 s (including `0` and negative values from an empty environment variable) are clamped to 1 s; `NaN`/`Infinity` fall back to the signal's default (60 s for logs and metrics, 5 s for traces). Non-positive or non-integer batch values fall back to their defaults. The metrics export timeout is clamped to the export interval when it is larger, with one `console.warn` — see [StandardMeter](#standardmeter). An invalid `OPENTELEMETRY_LOG_LEVEL` logs one `console.warn` and falls back to `"info"`; an invalid `OPENTELEMETRY_CONSOLE_LOG_MODE` logs one `console.warn` and falls back to `"always"`; an invalid `OPENTELEMETRY_COLLECTOR_HTTP_COMPRESSION` logs one `console.warn` and falls back to `"none"`. Invalid collector URLs and header maps throw an `Error` naming the offending field (see [Exporter HTTP options](#exporter-http-options-all-signals)).
44
51
 
45
52
  When a collector endpoint is not provided, the corresponding signal (traces, logs, or metrics) is initialized with no export: traces and metrics still have a local provider but no data is sent, and `StandardLogger` creates no provider (its `getLogger()` returns `undefined`).
46
53
 
54
+ ## Resource identity
55
+
56
+ `StandardTracer`, `StandardLogger` and `StandardMeter` build the same OpenTelemetry resource, so filtering by service or environment behaves identically across traces, logs and metrics:
57
+
58
+ | Attribute | Source | Default |
59
+ | ----------------------------- | ------------------------------------------------- | -------------------- |
60
+ | `service.name` | `SERVICE_ID` | — (required) |
61
+ | `service.version` | `VERSION` | — (required) |
62
+ | `network.local.address` | hostname (`os.hostname()`, cached at module load) | the current hostname |
63
+ | `service.instance.id` | `SERVICE_INSTANCE_ID` | unset (opt-in) |
64
+ | `deployment.environment.name` | `DEPLOYMENT_ENVIRONMENT_NAME` | unset (opt-in) |
65
+ | any other attribute | `OPENTELEMETRY_RESOURCE_ATTRIBUTES` | `{}` |
66
+
67
+ `service.instance.id` and `deployment.environment.name` are stable OpenTelemetry semantic conventions; setting them (for example to the pod name and `production`) materially improves filtering in a shared collector such as otel-light. Both are opt-in: `undefined` or a blank string means the attribute is not set, so the default resource is exactly `service.name` + `service.version` + `network.local.address`.
68
+
69
+ `OPENTELEMETRY_RESOURCE_ATTRIBUTES` adds any `string | number | boolean` attribute (for example `{ "deployment.tier": "web" }`). **Precedence:** the custom map is applied first; the dedicated identity fields above are applied last and win when set, so a custom map cannot override `service.name`, `service.version`, `network.local.address`, or a configured `service.instance.id`/`deployment.environment.name`. Malformed maps throw an `Error` naming the field and key (see [Configuration](#configuration)).
70
+
71
+ ```typescript
72
+ const config = {
73
+ ...baseConfig,
74
+ SERVICE_INSTANCE_ID: process.env.HOSTNAME ?? "local",
75
+ DEPLOYMENT_ENVIRONMENT_NAME: "production",
76
+ OPENTELEMETRY_RESOURCE_ATTRIBUTES: {
77
+ "deployment.tier": "web",
78
+ canary: false,
79
+ },
80
+ };
81
+ const tracer = new StandardTracer(config);
82
+ await logger.initOTel(config);
83
+ const meter = new StandardMeter(config);
84
+ ```
85
+
47
86
  ## Exporter HTTP options (all signals)
48
87
 
49
88
  Traces, logs and metrics share the same OTLP HTTP exporter options:
@@ -76,7 +115,8 @@ Creates a `TracerProvider` with:
76
115
  - AWS X-Ray ID generator (`AWSXRayIdGenerator`)
77
116
  - OTLP HTTP trace exporter (optional, when `OPENTELEMETRY_COLLECTOR_HTTP_TRACES` is set)
78
117
  - one process-wide `AsyncLocalStorageContextManager`, installed on first construction when no other context manager is registered (kept for the process lifetime)
79
- - Service resource attributes (name, version, hostname)
118
+ - the configured trace sampler (default `parentbased_always_on`, the SDK default)
119
+ - Service resource attributes (name, version, hostname, plus the opt-in instance id, deployment environment and custom attributes)
80
120
 
81
121
  The instance exports its spans through its own provider (`tracer.startSpan(...)` is always routed to this instance). The first `StandardTracer` constructed in a process also registers its provider as the global one, so `trace.getTracer(...)` from `@opentelemetry/api` resolves to it. Later instances do not replace the global provider: they log a warning and keep exporting through their own provider — see [Provider lifecycle](#provider-lifecycle).
82
122
 
@@ -91,11 +131,47 @@ span.end();
91
131
 
92
132
  **Methods:**
93
133
 
94
- - `startSpan(name, parentSpan?, options?)` — Creates a span and returns the SDK `Span` from `@opentelemetry/sdk-trace`. Span names are sanitized to `[a-zA-Z0-9-_/]`. `parentSpan` accepts any API `Span` (for example from `trace.getSpan(context)` or `trace.wrapSpanContext(...)`), so callers need no cast. When neither `parentSpan` nor `options` is given, the span is `SpanKind.INTERNAL` and carries `http.request.method=BACKEND` and a synthetic `http.route` attribute with the value `${serviceName}-${version}-${sanitizedSpanName}`. Passing a `parentSpan`, an `options` object (e.g. `{ kind: SpanKind.SERVER }`), or both forwards them to the OpenTelemetry SDK instead and skips those synthetic attributes, because the caller then describes the span itself. Generic HTTP dashboards that group by `http.request.method`/`http.route` count these spans as `BACKEND` requests with a synthetic route; this is intentional and consumed by otel-light.
134
+ - `startSpan(name, parentSpan?, options?)` — Creates a span and returns the SDK `Span` from `@opentelemetry/sdk-trace`. Span names are sanitized to `[a-zA-Z0-9-_/]`. `parentSpan` accepts any API `Span` (for example from `trace.getSpan(context)` or `trace.wrapSpanContext(...)`), so callers need no cast. `options` is the full OpenTelemetry API `SpanOptions`: `kind`, `attributes`, `links`, `startTime` and `root`. `links` and `startTime` can only be set at span creation, not afterwards; `attributes` can also be added after creation with `span.setAttribute(...)`. When neither `parentSpan` nor `options` is given, the span is `SpanKind.INTERNAL` and carries `http.request.method=BACKEND` and a synthetic `http.route` attribute with the value `${serviceName}-${version}-${sanitizedSpanName}`. Passing a `parentSpan`, an `options` object (e.g. `{ kind: SpanKind.SERVER }`), or both forwards them to the OpenTelemetry SDK instead and skips those synthetic attributes, because the caller then describes the span itself. Generic HTTP dashboards that group by `http.request.method`/`http.route` count these spans as `BACKEND` requests with a synthetic route; this is intentional and consumed by otel-light.
95
135
  - `static updateHttpHeader<T extends object = Record<string, string>>(context, headers?)` — Injects the W3C trace context of `context` into an HTTP headers object for propagation to downstream services, and returns that same object (a new one when omitted). Only `traceparent` and `tracestate` are injected: the propagation context is built from the span alone, so baggage and other active-context values are **not** propagated and an existing `baggage` header is left untouched.
96
136
  - `shutdown()` — Flushes buffered spans and shuts the tracer provider down. Idempotent.
97
137
  - `forceFlush()` — Flushes buffered spans to the collector without shutting the provider down; resolves immediately when no collector is configured. Use it at checkpoints in short-lived jobs and serverless handlers.
98
138
 
139
+ ```typescript
140
+ import { SpanKind } from "@opentelemetry/api";
141
+
142
+ const span = tracer.startSpan("checkout", undefined, {
143
+ kind: SpanKind.CLIENT,
144
+ attributes: { "checkout.channel": "web" },
145
+ links: [{ context: upstreamSpan.spanContext() }],
146
+ startTime: new Date(Date.now() - 250),
147
+ });
148
+ span.setAttribute("checkout.items", 3); // attributes can also be added afterwards
149
+ span.end();
150
+ ```
151
+
152
+ #### Trace sampling
153
+
154
+ `OPENTELEMETRY_TRACES_SAMPLER` selects the SDK sampler used by the tracer provider. The default `parentbased_always_on` is the SDK default: root spans are always sampled and children follow their parent.
155
+
156
+ | Value | SDK sampler |
157
+ | -------------------------- | ------------------------------------------------------ |
158
+ | `always_on` | `AlwaysOnSampler` |
159
+ | `always_off` | `AlwaysOffSampler` |
160
+ | `traceidratio` | `TraceIdRatioBasedSampler` |
161
+ | `parentbased_always_on` | `ParentBasedSampler` (root `AlwaysOnSampler`) |
162
+ | `parentbased_always_off` | `ParentBasedSampler` (root `AlwaysOffSampler`) |
163
+ | `parentbased_traceidratio` | `ParentBasedSampler` (root `TraceIdRatioBasedSampler`) |
164
+
165
+ `OPENTELEMETRY_TRACES_SAMPLER_ARG` is the sampling ratio in `[0,1]` and is only used by `traceidratio` and `parentbased_traceidratio`; `0` samples nothing and `1` samples everything. It is ignored by the other samplers. An invalid sampler value logs one `console.warn` and falls back to `parentbased_always_on`; a missing or invalid ratio logs one `console.warn` and falls back to `1`.
166
+
167
+ ```typescript
168
+ const tracer = new StandardTracer({
169
+ ...config,
170
+ OPENTELEMETRY_TRACES_SAMPLER: "parentbased_traceidratio",
171
+ OPENTELEMETRY_TRACES_SAMPLER_ARG: 0.1, // sample 10% of root traces
172
+ });
173
+ ```
174
+
99
175
  **Trace batch tunables and loss window**
100
176
 
101
177
  When a traces endpoint is configured, spans flow through a `BatchSpanProcessor`. It buffers spans in memory and exports them periodically:
@@ -247,11 +323,23 @@ const cpuGauge = meter.createObservableGauge(
247
323
  (result) => result.observe(cpuPercent),
248
324
  "Current CPU usage",
249
325
  );
326
+
327
+ const queueProcessed = meter.createObservableCounter(
328
+ "queue.processed",
329
+ (result) => result.observe(processedJobs),
330
+ { description: "Processed jobs", unit: "1" },
331
+ );
332
+
333
+ const queueDepth = meter.createObservableUpDownCounter(
334
+ "queue.depth",
335
+ (result) => result.observe(backlogSize),
336
+ { description: "Queue backlog", unit: "{item}" },
337
+ );
250
338
  ```
251
339
 
252
340
  **Instrument options**
253
341
 
254
- All four factories accept an optional options argument with the standard OpenTelemetry `MetricOptions` — `description`, `unit`, `valueType` and `advice` — forwarded to the underlying `Meter`. `createObservableGauge` also keeps accepting a description string as its third argument.
342
+ All factories accept an optional options argument with the standard OpenTelemetry `MetricOptions` — `description`, `unit`, `valueType` and `advice` — forwarded to the underlying `Meter`. `createObservableGauge` also keeps accepting a description string as its third argument.
255
343
 
256
344
  These options matter most for histograms: the SDK default bucket boundaries (`[0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000]`) are millisecond-oriented. A consumer that records seconds with the defaults puts every value below 5 s into the first bucket, which makes percentiles meaningless. The OpenTelemetry semantic conventions for `http.server.request.duration` therefore expect seconds and these boundaries:
257
345
 
@@ -286,9 +374,10 @@ meter.createObservableGauge(
286
374
 
287
375
  **Metric naming**
288
376
 
289
- - Counters, up-down counters and histograms are exported as `${serviceName}.${key}`.
377
+ - Counters, up-down counters, histograms, observable counters and observable up-down counters are exported as `${serviceName}.${key}`.
290
378
  - A histogram created with `{ unprefixed: true }` is exported exactly as `key`; only histograms have this opt-out.
291
379
  - Observable gauges are always exported exactly as `key` (never prefixed), including when an options object is passed.
380
+ - Instruments created through `getMeter()` are exported exactly as named; that raw accessor never prefixes.
292
381
 
293
382
  These defaults are unchanged: existing metric names keep working.
294
383
 
@@ -298,6 +387,9 @@ These defaults are unchanged: existing metric names keep working.
298
387
  - `createUpDownCounter(key, options?)` — Creates an `UpDownCounter` named `${serviceName}.${key}`.
299
388
  - `createHistogram(key, options?)` — Creates a `Histogram` named `${serviceName}.${key}`; with `{ unprefixed: true }` the histogram is created exactly as `key`, without the service-name prefix. Options also accept the OTel instrument options (`description`, `unit`, `valueType`, `advice`).
300
389
  - `createObservableGauge(key, callback, descriptionOrOptions?)` — Creates an `ObservableGauge` named `key` with a callback. The third argument is an optional description string or an options object (`description`, `unit`, `valueType`, `advice`).
390
+ - `createObservableCounter(key, callback, options?)` — Creates an `ObservableCounter` named `${serviceName}.${key}` with a callback, for monotonically increasing asynchronous values (for example processed jobs). `callback` is `(observableResult) => void`; the instrument options are forwarded.
391
+ - `createObservableUpDownCounter(key, callback, options?)` — Creates an `ObservableUpDownCounter` named `${serviceName}.${key}` with a callback, for values that can increase or decrease (for example queue/backlog sizes). `callback` is `(observableResult) => void`; the instrument options are forwarded.
392
+ - `getMeter()` — Returns the underlying OTel `Meter` for advanced instruments. Instruments created through it are exported exactly as named, without the `${serviceName}.` prefix.
301
393
  - `shutdown()` — Flushes buffered metrics and shuts the meter provider down. Idempotent.
302
394
  - `forceFlush()` — Flushes buffered metrics to the collector without shutting the meter provider down; resolves immediately when no collector is configured. Use it at checkpoints in short-lived jobs and serverless handlers.
303
395
 
@@ -308,6 +400,7 @@ OpenTelemetry's global API accepts one provider per signal per process, and the
308
400
  - **One provider per signal per process.** The first `StandardTracer`, configured `StandardLogger` and configured `StandardMeter` created in a process each register their provider globally. Global-API calls (`trace.getTracer`, `logs.getLogger`, `metrics.getMeter`) resolve to those first providers until they shut down.
309
401
  - **Additional instances keep working, locally.** A second instance does not replace the global provider: it logs a `console.warn` and still exports through its own provider, with its own `service.name`/`service.version`. Its records/spans/metrics are never attributed to another service.
310
402
  - **Re-initialisation.** Calling `StandardLogger.initOTel()` again on the same instance flushes and shuts down the previous provider (its buffered records are exported), then registers the new one as the global provider if possible. Await the returned promise when re-initializing.
403
+ - **Single-instance contract for tracer and meter.** `StandardTracer` and `StandardMeter` are configured once, in their constructor; they have no re-initialisation method. Create one per process. A second instance keeps working locally but never replaces the global provider — only `StandardLogger` supports re-initialisation.
311
404
  - **Serialised init/shutdown (`StandardLogger`).** `initOTel()` and `shutdown()` run through one promise queue, in call order, and never interleave. An init queued while a shutdown is in flight waits for it, then creates and registers its provider; a shutdown queued behind an init shuts the provider created by that init. The queue survives validation failures (only the failing operation rejects), and `forceFlush()` is non-terminal: it never changes the lifecycle state or the global registration.
312
405
  - **Shutdown.** `shutdown()` flushes pending telemetry, shuts the provider down and is idempotent. If the instance owns the global provider, it also calls `trace.disable()` / `logs.disable()` / `metrics.disable()`, returning the global API to Noop and allowing a later instance to register again. Shutting down a non-owner leaves the global provider untouched. After `StandardLogger.shutdown()`, `getLogger()` is `undefined`.
313
406
  - **Context propagation.** One `AsyncLocalStorageContextManager` is installed per process on the first `StandardTracer` construction, only when no other context manager is registered. It stays active for the process lifetime (it is never disabled), so re-initialisation keeps working.
@@ -362,7 +455,7 @@ Each `shutdown()` flushes pending telemetry to the collector before resolving; t
362
455
 
363
456
  ### createOTelResource
364
457
 
365
- Shared internal utility that creates an `OTelResource` with `service.name`, `service.version`, and `network.local.address` (hostname). The hostname is cached at module load time to minimize system calls.
458
+ Shared internal utility that creates an `OTelResource` with `service.name`, `service.version` and `network.local.address` (hostname), plus the optional `service.instance.id`, `deployment.environment.name` and custom resource attributes. The hostname is cached at module load time to minimize system calls. The same resource is used by `StandardTracer`, `StandardLogger` and `StandardMeter`.
366
459
 
367
460
  ```typescript
368
461
  // Used internally by StandardTracer, StandardLogger, and StandardMeter
@@ -379,7 +472,7 @@ Application
379
472
  └── PeriodicExportingMetricReader
380
473
  ```
381
474
 
382
- All three signals share the same service identity (name + version) and resource attributes via `createOTelResource`. Export is optional per signal — only configured when the corresponding `OPENTELEMETRY_COLLECTOR_HTTP_*` endpoint is set.
475
+ All three signals share the same service identity (name + version), the optional instance id and deployment environment, and any custom resource attributes via `createOTelResource`. Export is optional per signal — only configured when the corresponding `OPENTELEMETRY_COLLECTOR_HTTP_*` endpoint is set.
383
476
 
384
477
  ## Dependencies
385
478
 
@@ -49,6 +49,9 @@ class StandardLogger {
49
49
  // Validate before releasing the previous provider: a bad re-init must keep
50
50
  // the working provider in place.
51
51
  (0, configValidation_1.validateServiceIdentity)(config);
52
+ const serviceName = config.SERVICE_ID;
53
+ const serviceVersion = config.VERSION;
54
+ const resource = (0, createResource_1.createOTelResource)(serviceName, serviceVersion, (0, createResource_1.resolveResourceOptions)(config));
52
55
  this.consoleMode = (0, configValidation_1.normalizeConsoleLogMode)(config.OPENTELEMETRY_CONSOLE_LOG_MODE);
53
56
  this.logLevel = (0, configValidation_1.normalizeLogLevel)(config.OPENTELEMETRY_LOG_LEVEL);
54
57
  // Build the exporter options before releasing the previous provider: a bad
@@ -60,8 +63,8 @@ class StandardLogger {
60
63
  if (this.loggerProvider) {
61
64
  await this.releaseProvider();
62
65
  }
63
- this.serviceName = config.SERVICE_ID;
64
- this.serviceVersion = config.VERSION;
66
+ this.serviceName = serviceName;
67
+ this.serviceVersion = serviceVersion;
65
68
  if (!exporterOptions) {
66
69
  return;
67
70
  }
@@ -76,7 +79,7 @@ class StandardLogger {
76
79
  scheduledDelayMillis: (0, configValidation_1.normalizeExportIntervalSeconds)(config.OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_INTERVAL_SECONDS, 60) * 1000,
77
80
  }),
78
81
  ],
79
- resource: (0, createResource_1.createOTelResource)(this.serviceName, this.serviceVersion),
82
+ resource,
80
83
  });
81
84
  this.logger = this.loggerProvider.getLogger(`${this.serviceName}:${this.serviceVersion}`);
82
85
  this.registerGlobalProvider();
@@ -1,4 +1,4 @@
1
- import { Counter, Histogram, type MetricOptions, ObservableGauge, UpDownCounter } from "@opentelemetry/api";
1
+ import { Counter, Histogram, Meter, type MetricOptions, ObservableCounter, type ObservableCallback, ObservableGauge, ObservableUpDownCounter, UpDownCounter } from "@opentelemetry/api";
2
2
  import { ConfigOTelInterface } from "./models/ConfigOTelInterface";
3
3
  /**
4
4
  * Options accepted by {@link StandardMeter.createHistogram}.
@@ -13,6 +13,15 @@ export interface StandardMeterCreateHistogramOptions extends MetricOptions {
13
13
  */
14
14
  unprefixed?: boolean;
15
15
  }
16
+ /**
17
+ * Creates instruments through a `MeterProvider` owned by this instance.
18
+ *
19
+ * Single-instance contract: create one `StandardMeter` per process. A second
20
+ * instance keeps working locally (it records through its own provider) but
21
+ * never replaces the global provider registered by the first one.
22
+ * Re-initialisation is only supported by `StandardLogger`; a `StandardMeter`
23
+ * is configured once, in its constructor.
24
+ */
16
25
  export declare class StandardMeter {
17
26
  private meter;
18
27
  private meterProvider;
@@ -23,9 +32,16 @@ export declare class StandardMeter {
23
32
  constructor(config: ConfigOTelInterface);
24
33
  shutdown(): Promise<void>;
25
34
  forceFlush(): Promise<void>;
35
+ /**
36
+ * Returns the underlying OTel `Meter` for advanced instruments. Instruments
37
+ * created through it are not prefixed with the service name.
38
+ */
39
+ getMeter(): Meter;
26
40
  createCounter(key: string, options?: MetricOptions): Counter;
27
41
  createUpDownCounter(key: string, options?: MetricOptions): UpDownCounter;
28
42
  createHistogram(key: string, options?: StandardMeterCreateHistogramOptions): Histogram;
43
+ createObservableCounter(key: string, callback: ObservableCallback, options?: MetricOptions): ObservableCounter;
44
+ createObservableUpDownCounter(key: string, callback: ObservableCallback, options?: MetricOptions): ObservableUpDownCounter;
29
45
  createObservableGauge(key: string, callback: (observableResult: any) => void, descriptionOrOptions?: string | MetricOptions): ObservableGauge;
30
46
  private registerGlobalProvider;
31
47
  private doShutdown;
@@ -9,6 +9,15 @@ const configValidation_1 = require("./utils/configValidation");
9
9
  const exporterConfig_1 = require("./utils/exporterConfig");
10
10
  let globalMeterProvider;
11
11
  const ALREADY_REGISTERED_WARNING = "[otel-utils] A global meter provider is already registered; StandardMeter will not replace it. This instance still records metrics through its own provider, but metrics.getMeter() keeps using the existing provider.";
12
+ /**
13
+ * Creates instruments through a `MeterProvider` owned by this instance.
14
+ *
15
+ * Single-instance contract: create one `StandardMeter` per process. A second
16
+ * instance keeps working locally (it records through its own provider) but
17
+ * never replaces the global provider registered by the first one.
18
+ * Re-initialisation is only supported by `StandardLogger`; a `StandardMeter`
19
+ * is configured once, in its constructor.
20
+ */
12
21
  class StandardMeter {
13
22
  constructor(config) {
14
23
  this.ownsGlobalProvider = false;
@@ -24,7 +33,7 @@ class StandardMeter {
24
33
  });
25
34
  const exportIntervalMillis = (0, configValidation_1.normalizeExportIntervalSeconds)(config.OPENTELEMETRY_COLLECTOR_EXPORT_METRICS_INTERVAL_SECONDS, 60) * 1000;
26
35
  this.meterProvider = new sdk_metrics_1.MeterProvider({
27
- resource: (0, createResource_1.createOTelResource)(this.serviceName, this.serviceVersion),
36
+ resource: (0, createResource_1.createOTelResource)(this.serviceName, this.serviceVersion, (0, createResource_1.resolveResourceOptions)(config)),
28
37
  readers: [
29
38
  new sdk_metrics_1.PeriodicExportingMetricReader({
30
39
  exporter: metricExporter,
@@ -36,7 +45,7 @@ class StandardMeter {
36
45
  }
37
46
  else {
38
47
  this.meterProvider = new sdk_metrics_1.MeterProvider({
39
- resource: (0, createResource_1.createOTelResource)(this.serviceName, this.serviceVersion),
48
+ resource: (0, createResource_1.createOTelResource)(this.serviceName, this.serviceVersion, (0, createResource_1.resolveResourceOptions)(config)),
40
49
  });
41
50
  }
42
51
  this.meter = this.meterProvider.getMeter(`${this.serviceName}:${this.serviceVersion}`);
@@ -53,6 +62,13 @@ class StandardMeter {
53
62
  forceFlush() {
54
63
  return this.meterProvider.forceFlush();
55
64
  }
65
+ /**
66
+ * Returns the underlying OTel `Meter` for advanced instruments. Instruments
67
+ * created through it are not prefixed with the service name.
68
+ */
69
+ getMeter() {
70
+ return this.meter;
71
+ }
56
72
  createCounter(key, options) {
57
73
  return this.meter.createCounter(`${this.serviceName}.${key}`, options);
58
74
  }
@@ -63,6 +79,16 @@ class StandardMeter {
63
79
  const { unprefixed, ...instrumentOptions } = options !== null && options !== void 0 ? options : {};
64
80
  return this.meter.createHistogram(unprefixed ? key : `${this.serviceName}.${key}`, instrumentOptions);
65
81
  }
82
+ createObservableCounter(key, callback, options) {
83
+ const observableCounter = this.meter.createObservableCounter(`${this.serviceName}.${key}`, options);
84
+ observableCounter.addCallback(callback);
85
+ return observableCounter;
86
+ }
87
+ createObservableUpDownCounter(key, callback, options) {
88
+ const observableUpDownCounter = this.meter.createObservableUpDownCounter(`${this.serviceName}.${key}`, options);
89
+ observableUpDownCounter.addCallback(callback);
90
+ return observableUpDownCounter;
91
+ }
66
92
  createObservableGauge(key,
67
93
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
68
94
  callback, descriptionOrOptions) {
@@ -1,20 +1,26 @@
1
- import { SpanKind } from "@opentelemetry/api";
2
- import type { Span as ApiSpan } from "@opentelemetry/api";
1
+ import type { Span as ApiSpan, SpanOptions } from "@opentelemetry/api";
3
2
  import { type Span } from "@opentelemetry/sdk-trace";
4
- import { ConfigOTelInterface } from "./models/ConfigOTelInterface";
3
+ import type { ConfigOTelInterface } from "./models/ConfigOTelInterface";
5
4
  /**
6
- * Options accepted by {@link StandardTracer.startSpan}.
5
+ * Options accepted by {@link StandardTracer.startSpan}. This is the
6
+ * OpenTelemetry API `SpanOptions`: `kind`, `attributes`, `links`, `startTime`
7
+ * and `root`.
8
+ *
9
+ * Providing options means the caller describes the span itself: the
10
+ * parentless default attributes (`http.request.method=BACKEND` and the
11
+ * synthetic `http.route`) are not added. `links` and `startTime` can only be
12
+ * set at span creation, not afterwards.
13
+ */
14
+ export type StandardTracerStartSpanOptions = SpanOptions;
15
+ /**
16
+ * Creates spans through a `TracerProvider` owned by this instance.
17
+ *
18
+ * Single-instance contract: create one `StandardTracer` per process. A second
19
+ * instance keeps working locally (it exports through its own provider) but
20
+ * never replaces the global provider registered by the first one.
21
+ * Re-initialisation is only supported by `StandardLogger`; a `StandardTracer`
22
+ * is configured once, in its constructor.
7
23
  */
8
- export interface StandardTracerStartSpanOptions {
9
- /**
10
- * OpenTelemetry span kind (default `SpanKind.INTERNAL`).
11
- *
12
- * Providing options means the caller describes the span itself: the
13
- * parentless default attributes (`http.request.method=BACKEND` and the
14
- * synthetic `http.route`) are not added.
15
- */
16
- kind?: SpanKind;
17
- }
18
24
  export declare class StandardTracer {
19
25
  private static readonly SPAN_NAME_SANITIZE_RE;
20
26
  private static readonly PROPAGATOR;
@@ -20,6 +20,35 @@ function getRegisteredTracerProvider() {
20
20
  : provider;
21
21
  }
22
22
  const ALREADY_REGISTERED_WARNING = "[otel-utils] A global tracer provider is already registered; StandardTracer will not replace it. This instance still exports spans through its own provider, but trace.getTracer() keeps using the existing provider.";
23
+ function buildSampler(config) {
24
+ const { sampler, ratio } = (0, configValidation_1.resolveTraceSampler)(config.OPENTELEMETRY_TRACES_SAMPLER, config.OPENTELEMETRY_TRACES_SAMPLER_ARG);
25
+ switch (sampler) {
26
+ case "always_on":
27
+ return new sdk_trace_1.AlwaysOnSampler();
28
+ case "always_off":
29
+ return new sdk_trace_1.AlwaysOffSampler();
30
+ case "traceidratio":
31
+ return new sdk_trace_1.TraceIdRatioBasedSampler(ratio);
32
+ case "parentbased_always_off":
33
+ return new sdk_trace_1.ParentBasedSampler({ root: new sdk_trace_1.AlwaysOffSampler() });
34
+ case "parentbased_traceidratio":
35
+ return new sdk_trace_1.ParentBasedSampler({
36
+ root: new sdk_trace_1.TraceIdRatioBasedSampler(ratio),
37
+ });
38
+ case "parentbased_always_on":
39
+ default:
40
+ return new sdk_trace_1.ParentBasedSampler({ root: new sdk_trace_1.AlwaysOnSampler() });
41
+ }
42
+ }
43
+ /**
44
+ * Creates spans through a `TracerProvider` owned by this instance.
45
+ *
46
+ * Single-instance contract: create one `StandardTracer` per process. A second
47
+ * instance keeps working locally (it exports through its own provider) but
48
+ * never replaces the global provider registered by the first one.
49
+ * Re-initialisation is only supported by `StandardLogger`; a `StandardTracer`
50
+ * is configured once, in its constructor.
51
+ */
23
52
  class StandardTracer {
24
53
  constructor(config) {
25
54
  this.ownsGlobalProvider = false;
@@ -39,7 +68,8 @@ class StandardTracer {
39
68
  }
40
69
  this.traceProvider = new sdk_trace_1.TracerProvider({
41
70
  idGenerator: new id_generator_aws_xray_1.AWSXRayIdGenerator(),
42
- resource: (0, createResource_1.createOTelResource)(this.serviceName, this.serviceVersion),
71
+ sampler: buildSampler(config),
72
+ resource: (0, createResource_1.createOTelResource)(this.serviceName, this.serviceVersion, (0, createResource_1.resolveResourceOptions)(config)),
43
73
  spanProcessors,
44
74
  });
45
75
  // Resolve the tracer from this instance's provider: the global API may be
@@ -1,9 +1,16 @@
1
1
  export type ConsoleLogMode = "always" | "fallback" | "never";
2
2
  export type LogLevel = "trace" | "debug" | "info" | "warn" | "error";
3
3
  export type Compression = "gzip" | "none";
4
+ export type TraceSampler = "always_on" | "always_off" | "traceidratio" | "parentbased_always_on" | "parentbased_always_off" | "parentbased_traceidratio";
5
+ export type ResourceAttributeValue = string | number | boolean;
4
6
  export interface ConfigOTelInterface {
5
7
  SERVICE_ID: string;
6
8
  VERSION: string;
9
+ SERVICE_INSTANCE_ID?: string;
10
+ DEPLOYMENT_ENVIRONMENT_NAME?: string;
11
+ OPENTELEMETRY_RESOURCE_ATTRIBUTES?: Record<string, ResourceAttributeValue>;
12
+ OPENTELEMETRY_TRACES_SAMPLER?: TraceSampler;
13
+ OPENTELEMETRY_TRACES_SAMPLER_ARG?: number;
7
14
  OPENTELEMETRY_COLLECTOR_HTTP_TRACES?: string;
8
15
  OPENTELEMETRY_COLLECTOR_HTTP_METRICS?: string;
9
16
  OPENTELEMETRY_COLLECTOR_HTTP_LOGS?: string;
@@ -1,5 +1,11 @@
1
- import type { Compression, ConfigOTelInterface, ConsoleLogMode, LogLevel } from "../models/ConfigOTelInterface";
1
+ import type { Compression, ConfigOTelInterface, ConsoleLogMode, LogLevel, ResourceAttributeValue, TraceSampler } from "../models/ConfigOTelInterface";
2
2
  export declare function validateServiceIdentity(config: Pick<ConfigOTelInterface, "SERVICE_ID" | "VERSION">): void;
3
+ export declare function resolveTraceSampler(samplerValue: unknown, ratioValue: unknown): {
4
+ sampler: TraceSampler;
5
+ ratio: number;
6
+ };
7
+ export declare function normalizeResourceAttributes(value: unknown): Record<string, ResourceAttributeValue>;
8
+ export declare function normalizeOptionalIdentityValue(value: unknown, variableName: string): string | undefined;
3
9
  export declare function normalizeExportIntervalSeconds(value: number | undefined, defaultSeconds: number): number;
4
10
  export declare function normalizePositiveInteger(value: number | undefined, defaultValue: number): number;
5
11
  export declare function normalizeConsoleLogMode(value: unknown): ConsoleLogMode;
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validateServiceIdentity = validateServiceIdentity;
4
+ exports.resolveTraceSampler = resolveTraceSampler;
5
+ exports.normalizeResourceAttributes = normalizeResourceAttributes;
6
+ exports.normalizeOptionalIdentityValue = normalizeOptionalIdentityValue;
4
7
  exports.normalizeExportIntervalSeconds = normalizeExportIntervalSeconds;
5
8
  exports.normalizePositiveInteger = normalizePositiveInteger;
6
9
  exports.normalizeConsoleLogMode = normalizeConsoleLogMode;
@@ -9,6 +12,19 @@ exports.normalizeHeaders = normalizeHeaders;
9
12
  exports.normalizeCompression = normalizeCompression;
10
13
  exports.resolveMetricExportTimeout = resolveMetricExportTimeout;
11
14
  exports.normalizeLogLevel = normalizeLogLevel;
15
+ const DEFAULT_TRACE_SAMPLER = "parentbased_always_on";
16
+ const TRACE_SAMPLERS = [
17
+ "always_on",
18
+ "always_off",
19
+ "traceidratio",
20
+ "parentbased_always_on",
21
+ "parentbased_always_off",
22
+ "parentbased_traceidratio",
23
+ ];
24
+ const RATIO_TRACE_SAMPLERS = [
25
+ "traceidratio",
26
+ "parentbased_traceidratio",
27
+ ];
12
28
  function validateServiceIdentity(config) {
13
29
  if (typeof config.SERVICE_ID !== "string" ||
14
30
  config.SERVICE_ID.trim() === "") {
@@ -18,6 +34,64 @@ function validateServiceIdentity(config) {
18
34
  throw new Error("[otel-utils] VERSION must be a non-empty string");
19
35
  }
20
36
  }
37
+ function resolveTraceSampler(samplerValue, ratioValue) {
38
+ const sampler = normalizeTraceSampler(samplerValue);
39
+ if (!RATIO_TRACE_SAMPLERS.includes(sampler)) {
40
+ return { sampler, ratio: 1 };
41
+ }
42
+ return { sampler, ratio: normalizeTraceSamplerRatio(ratioValue) };
43
+ }
44
+ function normalizeTraceSampler(value) {
45
+ if (value === undefined ||
46
+ (typeof value === "string" && value.trim() === "")) {
47
+ return DEFAULT_TRACE_SAMPLER;
48
+ }
49
+ if (TRACE_SAMPLERS.includes(value)) {
50
+ return value;
51
+ }
52
+ console.warn(`[otel-utils] Invalid OPENTELEMETRY_TRACES_SAMPLER value "${String(value)}"; expected ${TRACE_SAMPLERS.map((sampler) => `"${sampler}"`).join(", ")}. Defaulting to "${DEFAULT_TRACE_SAMPLER}".`);
53
+ return DEFAULT_TRACE_SAMPLER;
54
+ }
55
+ function normalizeTraceSamplerRatio(value) {
56
+ if (typeof value === "number" &&
57
+ Number.isFinite(value) &&
58
+ value >= 0 &&
59
+ value <= 1) {
60
+ return value;
61
+ }
62
+ console.warn(`[otel-utils] Invalid OPENTELEMETRY_TRACES_SAMPLER_ARG value "${String(value)}"; expected a number between 0 and 1. Defaulting to 1.`);
63
+ return 1;
64
+ }
65
+ function normalizeResourceAttributes(value) {
66
+ if (value === undefined) {
67
+ return {};
68
+ }
69
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
70
+ throw new Error("[otel-utils] OPENTELEMETRY_RESOURCE_ATTRIBUTES must be an object mapping attribute names to string, number or boolean values");
71
+ }
72
+ const attributes = {};
73
+ for (const [name, attributeValue] of Object.entries(value)) {
74
+ if (typeof attributeValue !== "string" &&
75
+ typeof attributeValue !== "boolean" &&
76
+ !(typeof attributeValue === "number" && Number.isFinite(attributeValue))) {
77
+ throw new Error(`[otel-utils] OPENTELEMETRY_RESOURCE_ATTRIBUTES["${name}"] must be a string, number or boolean`);
78
+ }
79
+ attributes[name] = attributeValue;
80
+ }
81
+ return attributes;
82
+ }
83
+ function normalizeOptionalIdentityValue(value, variableName) {
84
+ if (value === undefined) {
85
+ return undefined;
86
+ }
87
+ if (typeof value !== "string") {
88
+ throw new Error(`[otel-utils] ${variableName} must be a string when set`);
89
+ }
90
+ if (value.trim() === "") {
91
+ return undefined;
92
+ }
93
+ return value;
94
+ }
21
95
  function normalizeExportIntervalSeconds(value, defaultSeconds) {
22
96
  if (value === undefined || !Number.isFinite(value)) {
23
97
  return defaultSeconds;
@@ -1 +1,8 @@
1
- export declare function createOTelResource(serviceName: string, serviceVersion: string): import("@opentelemetry/resources").Resource;
1
+ import type { ConfigOTelInterface, ResourceAttributeValue } from "../models/ConfigOTelInterface";
2
+ export interface CreateOTelResourceOptions {
3
+ serviceInstanceId?: string;
4
+ deploymentEnvironmentName?: string;
5
+ resourceAttributes?: Record<string, ResourceAttributeValue>;
6
+ }
7
+ export declare function createOTelResource(serviceName: string, serviceVersion: string, options?: CreateOTelResourceOptions): import("@opentelemetry/resources").Resource;
8
+ export declare function resolveResourceOptions(config: Pick<ConfigOTelInterface, "SERVICE_INSTANCE_ID" | "DEPLOYMENT_ENVIRONMENT_NAME" | "OPENTELEMETRY_RESOURCE_ATTRIBUTES">): CreateOTelResourceOptions;
@@ -34,14 +34,34 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.createOTelResource = createOTelResource;
37
+ exports.resolveResourceOptions = resolveResourceOptions;
37
38
  const resources_1 = require("@opentelemetry/resources");
38
39
  const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
39
40
  const os = __importStar(require("os"));
41
+ const configValidation_1 = require("./configValidation");
40
42
  const CACHED_HOSTNAME = os.hostname();
41
- function createOTelResource(serviceName, serviceVersion) {
42
- return (0, resources_1.resourceFromAttributes)({
43
+ function createOTelResource(serviceName, serviceVersion, options = {}) {
44
+ // Custom attributes are applied first; the dedicated identity fields below
45
+ // win so identity cannot be overridden by the custom map.
46
+ const attributes = {
47
+ ...options.resourceAttributes,
43
48
  [semantic_conventions_1.ATTR_SERVICE_NAME]: serviceName,
44
49
  [semantic_conventions_1.ATTR_SERVICE_VERSION]: serviceVersion,
45
50
  [semantic_conventions_1.ATTR_NETWORK_LOCAL_ADDRESS]: CACHED_HOSTNAME,
46
- });
51
+ };
52
+ if (options.serviceInstanceId !== undefined) {
53
+ attributes[semantic_conventions_1.ATTR_SERVICE_INSTANCE_ID] = options.serviceInstanceId;
54
+ }
55
+ if (options.deploymentEnvironmentName !== undefined) {
56
+ attributes[semantic_conventions_1.ATTR_DEPLOYMENT_ENVIRONMENT_NAME] =
57
+ options.deploymentEnvironmentName;
58
+ }
59
+ return (0, resources_1.resourceFromAttributes)(attributes);
60
+ }
61
+ function resolveResourceOptions(config) {
62
+ return {
63
+ serviceInstanceId: (0, configValidation_1.normalizeOptionalIdentityValue)(config.SERVICE_INSTANCE_ID, "SERVICE_INSTANCE_ID"),
64
+ deploymentEnvironmentName: (0, configValidation_1.normalizeOptionalIdentityValue)(config.DEPLOYMENT_ENVIRONMENT_NAME, "DEPLOYMENT_ENVIRONMENT_NAME"),
65
+ resourceAttributes: (0, configValidation_1.normalizeResourceAttributes)(config.OPENTELEMETRY_RESOURCE_ATTRIBUTES),
66
+ };
47
67
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devopsplaybook.io/otel-utils",
3
- "version": "1.12.0-beta.44.7e03cb8",
3
+ "version": "1.13.0-beta.45.6c6faf5",
4
4
  "description": "Utility to simplify integration with Open Telemetry",
5
5
  "keywords": [
6
6
  "Open",