@bymax-one/nest-telemetry 1.0.3 → 1.0.5

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/CHANGELOG.md CHANGED
@@ -8,6 +8,77 @@ The `release.yml` workflow extracts the section matching the pushed `vX.Y.Z` tag
8
8
  as the GitHub Release body, so each released version needs a matching `## [X.Y.Z]`
9
9
  heading here.
10
10
 
11
+ ## [Unreleased]
12
+
13
+ ## [1.0.5] - 2026-11-17
14
+
15
+ ### Added
16
+
17
+ - **A start warning for a ratio sampler that has no usable ratio.** With `OTEL_TRACES_SAMPLER` set to
18
+ `traceidratio` or `parentbased_traceidratio`, the SDK reads `OTEL_TRACES_SAMPLER_ARG` with `Number` and
19
+ falls back to a ratio of 1 when it is unset, empty, not a number or outside 0 to 1, noting it only on a
20
+ diagnostic channel. Every trace was then sampled without a word, which is the cost a ratio was set to
21
+ avoid. The start now warns once with `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID`, naming the variable and,
22
+ when one was given, the value. Measured with the real SDK: `1.5`, `-1`, `10%`, `NaN`, `Infinity` and no
23
+ value sampled all 200 root spans; `0` sampled none.
24
+
25
+ ### Fixed
26
+
27
+ - **Winston log forwarding says when it cannot work.** The winston instrumentation forwards a record by
28
+ adding a transport from `@opentelemetry/winston-transport`, which it loads with a `require` and which is
29
+ not one of its dependencies. An application that had not installed the package got no winston record in
30
+ the logs pipeline and no message, although 1.0.4 and the README said `sendLogs` covers winston. The start
31
+ now warns once with `BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING` when log sending is on, winston is
32
+ installed for the application and the transport cannot be resolved from the instrumentation. The README
33
+ says to install `@opentelemetry/winston-transport` as a direct dependency of the application, with what
34
+ was measured under npm and pnpm. The check asks whether winston is installed, not loaded, so an installed
35
+ winston the application never uses can warn once for nothing.
36
+
37
+ ### Documentation
38
+
39
+ - The README says the node-redis measurements were taken with `redis` 5 and 6.
40
+
41
+ ## [1.0.4] - 2026-11-14
42
+
43
+ ### Security
44
+
45
+ - **`host.id` is no longer exported by default.** It is dropped from the resource, and `host.name` stays. `unsafe.exportHostId: true`
46
+ keeps it and emits a `SecurityWarning`.
47
+ - **`process.command` is dropped with the command-line attributes.** It is `argv[1]`, which for
48
+ `node -e code ARG` is the first argument. `unsafe.exportProcessCommandArgs: true` keeps it, with
49
+ `process.command_args` and `process.command_line`.
50
+
51
+ ### Fixed
52
+
53
+ - **A batch-processor timer value a timer cannot hold is ignored.** An `OTEL_BSP_SCHEDULE_DELAY` above
54
+ 2147483647 ms reached `setTimeout`, which Node clamps to 1 ms, and the SDK exported once per span: 40
55
+ exports in 2 seconds in a measurement, against none at the default. An `OTEL_BSP_EXPORT_TIMEOUT` above it
56
+ became a 1 ms timeout on the processor side. Both are now ignored, the default applies, and
57
+ `BYMAX_TELEMETRY_BSP_VALUE_IGNORED` names the variable. The two sizes are not timers and are not limited.
58
+ - **`instrumentations.sendLogs: false` now keeps winston and bunyan records off the logs pipeline too.** It
59
+ set the log-sending key of pino only, so with `OTEL_LOGS_EXPORTER=otlp` the records of the other two were
60
+ forwarded whatever the option said. One option now sets the key of all three.
61
+
62
+ ### Added
63
+
64
+ - `unsafe.exportHostId` on `UnsafeOptions`.
65
+ - `BYMAX_TELEMETRY_BSP_VALUE_IGNORED`: a timer variable was ignored for being longer than a timer holds.
66
+
67
+ ### Apply to a derived backend
68
+
69
+ The declarations gained `unsafe.exportHostId`; a derived backend acts on these behaviours:
70
+
71
+ 1. A dashboard, an alert or a join keyed on `host.id` stops matching. Key it on `host.name` or
72
+ `service.instance.id`, or set `unsafe.exportHostId: true` and accept that the machine identifier goes to
73
+ every collector and backend.
74
+ 2. A query that reads `process.command` stops matching. `service.name` and `process.executable.path` identify
75
+ the process, or set `unsafe.exportProcessCommandArgs: true`.
76
+ 3. An application that set `instrumentations.sendLogs: false` and uses winston or bunyan with
77
+ `OTEL_LOGS_EXPORTER=otlp` stops sending those records to the logs pipeline. Set `sendLogs: true`, or an
78
+ override for the one library, to keep them.
79
+ 4. An `OTEL_BSP_SCHEDULE_DELAY` or `OTEL_BSP_EXPORT_TIMEOUT` above 2147483647 now falls back to the default
80
+ with a warning. Set a value up to 2147483647.
81
+
11
82
  ## [1.0.3] - 2026-11-14
12
83
 
13
84
  ### Added
@@ -166,6 +237,8 @@ First release.
166
237
  - Verification from the packed tarball: real `node --import` processes in a CommonJS and a native-ESM
167
238
  application, with planted secrets absent from the exported body and negative controls.
168
239
 
240
+ [1.0.5]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.5
241
+ [1.0.4]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.4
169
242
  [1.0.3]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.3
170
243
  [1.0.2]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.2
171
244
  [1.0.1]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.1
package/README.md CHANGED
@@ -72,7 +72,7 @@ Install it with the OpenTelemetry peers you use: the command is in [Quick Start]
72
72
  - ✅ **Span-end query redaction** — `url.query` is replaced and the query is cut from `url.full`, `http.url` and `http.target`, on spans from any instrumentation
73
73
  - ✅ **Outgoing-URL credential list** — A list of credential-bearing parameters, checked in a test against the SDK's own default list; a host can add names and never drop them
74
74
  - ✅ **Redis commands reduced to their name** — for `ioredis` and node-redis (`redis`), arguments and keys never leave the process, `EVAL` and `EVALSHA` payloads included
75
- - ✅ **Command line kept out of the resource** — `process.command_args` and `process.command_line` are dropped
75
+ - ✅ **Command line kept out of the resource** — `process.command_args`, `process.command_line` and `process.command` are dropped
76
76
  - ✅ **Explicit, loud opt-outs** — Each off switch is a literal `unsafe.*: true` and emits a `SecurityWarning`
77
77
 
78
78
  ---
@@ -165,33 +165,34 @@ This package installs no signal handler and shows none, because handling signals
165
165
 
166
166
  Every field is the host's policy, and none is required.
167
167
 
168
- | Option | Default | What it does |
169
- | -------------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
170
- | `enabled` | `true` | `false` never starts the SDK. `OTEL_SDK_DISABLED=true` disables it regardless. |
171
- | `serviceName` | `unknown_service:node` | The service name. `OTEL_SERVICE_NAME` overrides it. |
172
- | `serviceVersion` | none | The service version. |
173
- | `ignoreIncomingRequest` | none | Returns `true` for an incoming request that must produce no server span. `ignorePaths(patterns)` builds one from anchored patterns. |
174
- | `instrumentations.fs` | `false` | File-system instrumentation. |
175
- | `instrumentations.sendLogs` | follows `OTEL_LOGS_EXPORTER` | Whether pino's records are forwarded to the OpenTelemetry logs pipeline. |
176
- | `instrumentations.overrides` | none | Per-instrumentation configuration, merged over the library's. Redaction settings cannot be replaced here. |
177
- | `extraRedactedQueryParams` | none | Names added to the list redacted from outgoing request URLs. They add to the defaults and never replace them. |
178
- | `unsafe.disableUrlRedaction` | off | Keeps `url.query`, `url.full`, `http.url` and `http.target` as recorded. Literal `true`. Warns. |
179
- | `unsafe.disableRedisArgumentRedaction` | off | Keeps Redis command arguments in `db.query.text`. Literal `true`. Warns. |
180
- | `unsafe.exportProcessCommandArgs` | off | Keeps `process.command_args` and `process.command_line` in the resource. Literal `true`. Warns. |
181
- | `shutdownTimeoutMs` | `5000` | The longest shutdown waits for the final flush. Past it, shutdown warns and resolves. A value that is not a finite number above zero, or is above `120000`, means the default. |
182
- | `env` | the process environment | The environment the library reads. The OpenTelemetry SDK itself always reads the process environment. |
168
+ | Option | Default | What it does |
169
+ | -------------------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
170
+ | `enabled` | `true` | `false` never starts the SDK. `OTEL_SDK_DISABLED=true` disables it regardless. |
171
+ | `serviceName` | `unknown_service:node` | The service name. `OTEL_SERVICE_NAME` overrides it. |
172
+ | `serviceVersion` | none | The service version. |
173
+ | `ignoreIncomingRequest` | none | Returns `true` for an incoming request that must produce no server span. `ignorePaths(patterns)` builds one from anchored patterns. |
174
+ | `instrumentations.fs` | `false` | File-system instrumentation. |
175
+ | `instrumentations.sendLogs` | follows `OTEL_LOGS_EXPORTER` | Whether the records of pino, winston and bunyan are forwarded to the OpenTelemetry logs pipeline. Winston also needs `@opentelemetry/winston-transport` installed by your application, see [Forwarding log records](#forwarding-log-records). |
176
+ | `instrumentations.overrides` | none | Per-instrumentation configuration, merged over the library's. Redaction settings cannot be replaced here. |
177
+ | `extraRedactedQueryParams` | none | Names added to the list redacted from outgoing request URLs. They add to the defaults and never replace them. |
178
+ | `unsafe.disableUrlRedaction` | off | Keeps `url.query`, `url.full`, `http.url` and `http.target` as recorded. Literal `true`. Warns. |
179
+ | `unsafe.disableRedisArgumentRedaction` | off | Keeps Redis command arguments in `db.query.text`. Literal `true`. Warns. |
180
+ | `unsafe.exportProcessCommandArgs` | off | Keeps `process.command_args`, `process.command_line` and `process.command` in the resource. Literal `true`. Warns. |
181
+ | `unsafe.exportHostId` | off | Keeps `host.id`, the machine identifier, in the resource. Literal `true`. Warns. |
182
+ | `shutdownTimeoutMs` | `5000` | The longest shutdown waits for the final flush. Past it, shutdown warns and resolves. A value that is not a finite number above zero, or is above `120000`, means the default. |
183
+ | `env` | the process environment | The environment the library reads. The OpenTelemetry SDK itself always reads the process environment. |
183
184
 
184
185
  ### Environment variables
185
186
 
186
187
  The library reads these in one source file, and a test fails if any other file names `process.env`:
187
188
 
188
- | Variable | Effect |
189
- | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
190
- | `OTEL_SDK_DISABLED` | `true` disables the SDK, in any letter case and with surrounding whitespace ignored, as the SDK reads it. |
191
- | `OTEL_SERVICE_NAME` | Service name; overrides the option, because the operator's standard variable wins over what the code chose. Blank values count as absent. |
192
- | `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER` | Metrics and logs are exported only when these name an exporter. |
193
- | `OTEL_BSP_MAX_QUEUE_SIZE`, `OTEL_BSP_SCHEDULE_DELAY`, `OTEL_BSP_EXPORT_TIMEOUT`, `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` | Mapped onto the batch span processor the library passes; the SDK applies them only to one it builds itself. |
194
- | `OTEL_NODE_RESOURCE_DETECTORS` | Selects resource detectors, under the specification's names (`service`, `host`, `process`) and the SDK's older ones. |
189
+ | Variable | Effect |
190
+ | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
191
+ | `OTEL_SDK_DISABLED` | `true` disables the SDK, in any letter case and with surrounding whitespace ignored, as the SDK reads it. |
192
+ | `OTEL_SERVICE_NAME` | Service name; overrides the option, because the operator's standard variable wins over what the code chose. Blank values count as absent. |
193
+ | `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER` | Metrics and logs are exported only when these name an exporter. |
194
+ | `OTEL_BSP_MAX_QUEUE_SIZE`, `OTEL_BSP_SCHEDULE_DELAY`, `OTEL_BSP_EXPORT_TIMEOUT`, `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` | Mapped onto the batch span processor the library passes; the SDK applies them only to one it builds itself. A schedule delay or export timeout above 2147483647 ms is ignored with a warning, because a timer cannot hold it. |
195
+ | `OTEL_NODE_RESOURCE_DETECTORS` | Selects resource detectors, under the specification's names (`service`, `host`, `process`) and the SDK's older ones. |
195
196
 
196
197
  The OpenTelemetry SDK reads these itself, and the library never touches them: `OTEL_EXPORTER_OTLP_*`, `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG`, `OTEL_RESOURCE_ATTRIBUTES`.
197
198
 
@@ -215,15 +216,24 @@ The start emits these warnings:
215
216
  | `BYMAX_TELEMETRY_RESTART_UNSUPPORTED` | `startTelemetry` was called after a shutdown in the same process, and is refused. |
216
217
  | `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT` | The final flush did not finish within `shutdownTimeoutMs`. Shutdown resolved without it, and spans still queued may be lost. With `TelemetryModule` and a bound `TELEMETRY_LOGGER`, it is reported through `errorStructured` under `TRACING_SHUTDOWN_TIMEOUT` instead. |
217
218
  | `BYMAX_TELEMETRY_EXPORT_FAILED` | A span export failed, so the batch was dropped. The warning names the exporter and a short error code, never the payload or the endpoint, and repeats at most once a minute. With `TelemetryModule` and a bound `TELEMETRY_LOGGER` that has `warnStructured`, it is reported through it under `TRACING_EXPORT_FAILED` instead. |
219
+ | `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID` | A ratio sampler (`traceidratio` or `parentbased_traceidratio`) is selected and `OTEL_TRACES_SAMPLER_ARG` is not a number from 0 to 1, so the SDK samples every trace. Set the share of traces to keep, such as `0.1`. |
220
+ | `BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING` | Log forwarding is on and winston is installed, but `@opentelemetry/winston-transport` cannot be resolved from the winston instrumentation, so winston records are not forwarded. Install it as a direct dependency of the application. |
221
+ | `BYMAX_TELEMETRY_BSP_VALUE_IGNORED` | An `OTEL_BSP_SCHEDULE_DELAY` or `OTEL_BSP_EXPORT_TIMEOUT` above 2147483647 ms was ignored, because a timer cannot hold it and Node would clamp it to 1 ms. The default applies. |
218
222
 
219
223
  The programmatic `startTelemetry` keeps its rejection when the SDK cannot start, for callers that want it.
220
224
 
221
225
  ### What is traced
222
226
 
223
227
  - **Load order matters only for modules your application loads itself.** The core `http` module is patched even when the preload runs after it. A client such as `ioredis` is patched only if the preload ran before the application required it. Measured: an application that required `ioredis` first exported no `ioredis` span.
224
- - **`ioredis` commands are traced only under an active span; node-redis commands are not.** The `ioredis` instrumentation defaults to `requireParentSpan: true`, so a command issued outside any request produces no span. The node-redis (`redis`) instrumentation defaults to `false`, so it traces a command with no request around it too. Measured with `redis` 5.
228
+ - **`ioredis` commands are traced only under an active span; node-redis commands are not.** The `ioredis` instrumentation defaults to `requireParentSpan: true`, so a command issued outside any request produces no span. The node-redis (`redis`) instrumentation defaults to `false`, so it traces a command with no request around it too. Measured with `redis` 5 and 6.
225
229
  - **`fs` instrumentation is off by default**, because it floods traces with disk activity that has no context. Turn it on with `instrumentations.fs`.
226
230
 
231
+ ### Forwarding log records
232
+
233
+ With `OTEL_LOGS_EXPORTER=otlp`, or `instrumentations.sendLogs: true`, the records of pino, winston and bunyan go to the OpenTelemetry logs pipeline. Winston needs one more package: install `@opentelemetry/winston-transport` as a direct dependency of your application. The winston instrumentation loads it with a `require` from its own directory, and the package is not one of that instrumentation's dependencies, so without it winston records are not forwarded. Measured with winston 3.19.0 and `@opentelemetry/winston-transport` 0.35.0: a winston record reached the collector when the package was a direct dependency under npm, under pnpm 11.20.0 with the default layout and under pnpm with `hoist=false`, and it did not under npm without the package. A package that reaches the project only as another package's dependency was not measured.
234
+
235
+ At start the library warns once, with `BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING`, when log sending is on, winston resolves from the script that started the application (from the working directory when there is none), and the transport does not resolve from the winston instrumentation, which is found through `@opentelemetry/auto-instrumentations-node`. The check asks whether winston is installed, not whether it is loaded, because winston is usually not loaded yet at start: an installed winston that your application never uses causes one warning for nothing.
236
+
227
237
  ### Flushing
228
238
 
229
239
  Awaiting `shutdown()` or `shutdownTelemetry()` means the spans were exported, whoever started the flush, unless the deadline below passed first: overlapping callers wait for the same flush, and a shutdown that arrives while the SDK is still starting waits for the start and then stops what it built. A flush the collector refuses is reported, never thrown into your shutdown path, by the Nest module; the programmatic functions reject, so their caller decides.
@@ -238,7 +248,7 @@ A start after a shutdown in the same process is refused: `startTelemetry` reject
238
248
 
239
249
  Every figure here was measured on one laptop, with Node 24 and a handler that does nothing but answer. Read them as orders of magnitude for your own measurement to confirm, not as promises.
240
250
 
241
- - **Sampling.** The default samples every trace. For high traffic set `OTEL_TRACES_SAMPLER=parentbased_traceidratio` and `OTEL_TRACES_SAMPLER_ARG=0.1`. Of 2,000 spans created in one run each, the default exported all of them, a ratio of `0.1` exported 210 and a ratio of `0.01` exported 25.
251
+ - **Sampling.** The default samples every trace. For high traffic set `OTEL_TRACES_SAMPLER=parentbased_traceidratio` and `OTEL_TRACES_SAMPLER_ARG=0.1`. Of 2,000 spans created in one run each, the default exported all of them, a ratio of `0.1` exported 210 and a ratio of `0.01` exported 25. A ratio sampler needs `OTEL_TRACES_SAMPLER_ARG` to be a number from 0 to 1. When it is unset, empty, not a number or outside that range, the SDK falls back to a ratio of 1 and samples every trace, noting it only on a diagnostic channel; the start warns once with `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID`, naming the variable and, when one was given, the value. It reads the process environment, as the SDK does, and not the `env` option.
242
252
  - **TLS to the collector.** Against a collector whose certificate Node does not trust, every export failed with `self-signed certificate`. Setting `OTEL_EXPORTER_OTLP_CERTIFICATE` to the CA file, or `NODE_EXTRA_CA_CERTS`, exported all 2,000 spans in the same setup.
243
253
  - **A collector that is down.** The batch is dropped and the library emits `BYMAX_TELEMETRY_EXPORT_FAILED`, at most once a minute. Shutdown stops waiting at `shutdownTimeoutMs`, 5 seconds by default. Before that deadline existed, shutdown against a closed port took 7,048 ms and 7,214 ms in two runs.
244
254
  - **CPU.** One process, 4 runs per mode, median CPU time per request: 25 µs without the library, 26 µs with it loaded and disabled, 58 µs with a healthy collector (range 35 to 66) and 43 µs with the collector down (range 26 to 65). The extra cost in that handler is roughly 10 to 40 µs per request, and a handler that does real I/O dilutes it. The same configuration varied by up to a factor of two between runs.
@@ -272,6 +282,8 @@ A caret on a `0.x` version allows patch releases only, so each OpenTelemetry min
272
282
  | Spans arrive but carry no service name | `BYMAX_TELEMETRY_SERVICE_NAME_MISSING`: set `OTEL_SERVICE_NAME` or the `serviceName` option. A name set only through `OTEL_RESOURCE_ATTRIBUTES` still reaches the spans, unless `OTEL_NODE_RESOURCE_DETECTORS` leaves out both the `env` and the `service` detector. |
273
283
  | `BYMAX_TELEMETRY_START_FAILED` | The warning names the cause, usually an OpenTelemetry peer that is not installed. |
274
284
  | HTTP spans but no Redis spans | `ioredis` commands are traced under an active span only, and the client must be loaded after the preload. |
285
+ | More traces than the sampling ratio should keep | `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID`: `OTEL_TRACES_SAMPLER_ARG` is unset, blank or not a number from 0 to 1, so the SDK samples every trace. |
286
+ | Winston records missing from the logs pipeline | `BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING`: install `@opentelemetry/winston-transport` as a direct dependency of the application. |
275
287
  | Metrics or logs missing | They are off unless `OTEL_METRICS_EXPORTER` or `OTEL_LOGS_EXPORTER` names an exporter. |
276
288
  | The last spans of another module are lost when the application closes | List `TelemetryModule` first in the application module's imports, so it closes last. |
277
289
  | No spans arrive and nothing else is logged | `BYMAX_TELEMETRY_EXPORT_FAILED`: the collector did not accept the export. Check the endpoint in `OTEL_EXPORTER_OTLP_ENDPOINT` and that the collector is reachable. |
@@ -313,7 +325,7 @@ The layers are in the [Security Table](#-security-table) below.
313
325
 
314
326
  ### Exported on purpose
315
327
 
316
- The resource carries `host.name`, `os.*`, `process.pid`, `process.owner`, the executable path and runtime facts, and `service.instance.id`. They identify the instance during an incident. If you do not want them, set `OTEL_NODE_RESOURCE_DETECTORS`.
328
+ The resource carries `host.name`, `os.*`, `process.pid`, `process.owner`, the executable path and runtime facts, and `service.instance.id`. They identify the instance during an incident. If you do not want them, set `OTEL_NODE_RESOURCE_DETECTORS`. It does not carry `host.id`, the machine identifier: that is a stable hardware id, the platform UUID or `/etc/machine-id`, and it is dropped unless you set `unsafe.exportHostId`.
317
329
 
318
330
  ### How this is verified
319
331
 
@@ -330,7 +342,8 @@ What is **not** redacted is listed flat in [What This Library Does NOT Do](#-wha
330
342
  | Query redaction | `url.query` is replaced by `[redacted]` and the query is cut from `url.full`, `http.url` and `http.target` as each span ends, for any instrumentation |
331
343
  | Outgoing URLs | The HTTP instrumentation redacts a credential-parameter list (`token`, `code`, `access_token`, `signature`, `X-Amz-*`, and more); hosts add names, never drop them; a test compares the list with the SDK's own, so a name the SDK adds later is caught |
332
344
  | Redis | `db.query.text` holds the command name only, for `ioredis` and node-redis; `EVAL` and `EVALSHA` payloads, which carry `KEYS` and `ARGV`, and every key never leave the process |
333
- | Process command line | `process.command_args` and `process.command_line` are dropped from the resource, because command-line arguments are a common carrier of secrets |
345
+ | Process command line | `process.command_args`, `process.command_line` and `process.command` are dropped from the resource, because command-line arguments are a common carrier of secrets |
346
+ | Host id | `host.id`, the machine identifier (the platform UUID, or `/etc/machine-id`), is dropped from the resource; `host.name` stays |
334
347
  | Opt-outs | Literal `unsafe.*: true` options only, each emitting a `SecurityWarning`; no environment variable turns redaction off |
335
348
  | Overrides | `instrumentations.overrides` is merged under the library's redaction, which is applied again on top |
336
349
  | Environment | Read in one module; a test fails if any other file names `process.env` |
@@ -1,8 +1,11 @@
1
- import { register } from 'module';
1
+ import { register, createRequire } from 'module';
2
+ import { join } from 'path';
2
3
 
3
4
  // src/register/boot.ts
4
5
 
5
6
  // src/sdk/environment.ts
7
+ var MAX_TIMER_MS = 2147483647;
8
+ var RATIO_SAMPLERS = ["traceidratio", "parentbased_traceidratio"];
6
9
  function readExporterList(raw) {
7
10
  return (raw ?? "").split(",").map((name) => name.trim()).filter((name) => name !== "");
8
11
  }
@@ -10,13 +13,30 @@ function readPositiveNumber(raw) {
10
13
  const value = Number(raw);
11
14
  return Number.isFinite(value) && value > 0 ? value : void 0;
12
15
  }
16
+ function readTimerMillis(name, raw, oversized) {
17
+ const value = readPositiveNumber(raw);
18
+ if (value !== void 0 && value > MAX_TIMER_MS) {
19
+ oversized.push(name);
20
+ return void 0;
21
+ }
22
+ return value;
23
+ }
13
24
  function readTelemetryEnvironment(source = process.env) {
14
25
  const tuning = {};
15
26
  const maxQueueSize = readPositiveNumber(source["OTEL_BSP_MAX_QUEUE_SIZE"]);
16
27
  if (maxQueueSize !== void 0) tuning.maxQueueSize = maxQueueSize;
17
- const scheduledDelayMillis = readPositiveNumber(source["OTEL_BSP_SCHEDULE_DELAY"]);
28
+ const oversizedTimers = [];
29
+ const scheduledDelayMillis = readTimerMillis(
30
+ "OTEL_BSP_SCHEDULE_DELAY",
31
+ source["OTEL_BSP_SCHEDULE_DELAY"],
32
+ oversizedTimers
33
+ );
18
34
  if (scheduledDelayMillis !== void 0) tuning.scheduledDelayMillis = scheduledDelayMillis;
19
- const exportTimeoutMillis = readPositiveNumber(source["OTEL_BSP_EXPORT_TIMEOUT"]);
35
+ const exportTimeoutMillis = readTimerMillis(
36
+ "OTEL_BSP_EXPORT_TIMEOUT",
37
+ source["OTEL_BSP_EXPORT_TIMEOUT"],
38
+ oversizedTimers
39
+ );
20
40
  if (exportTimeoutMillis !== void 0) tuning.exportTimeoutMillis = exportTimeoutMillis;
21
41
  const maxExportBatchSize = readPositiveNumber(source["OTEL_BSP_MAX_EXPORT_BATCH_SIZE"]);
22
42
  if (maxExportBatchSize !== void 0) tuning.maxExportBatchSize = maxExportBatchSize;
@@ -28,9 +48,15 @@ function readTelemetryEnvironment(source = process.env) {
28
48
  metricsExporters: readExporterList(source["OTEL_METRICS_EXPORTER"]),
29
49
  logsExporters: readExporterList(source["OTEL_LOGS_EXPORTER"]),
30
50
  batchSpanProcessor: tuning,
51
+ oversizedTimers,
31
52
  resourceDetectors: detectors === void 0 || detectors.trim() === "" ? void 0 : readExporterList(detectors)
32
53
  };
33
54
  }
55
+ function readRatioSampler(source = process.env) {
56
+ const name = source["OTEL_TRACES_SAMPLER"];
57
+ const arg = source["OTEL_TRACES_SAMPLER_ARG"];
58
+ return name !== void 0 && RATIO_SAMPLERS.includes(name) ? { name, arg: arg?.trim() === "" ? void 0 : arg } : void 0;
59
+ }
34
60
 
35
61
  // src/sdk/redaction.ts
36
62
  var REDACTED_QUERY_VALUE = "[redacted]";
@@ -87,12 +113,27 @@ function serializeRedisCommandName(commandName) {
87
113
  return commandName;
88
114
  }
89
115
 
116
+ // src/sdk/warning-sink.ts
117
+ var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
118
+ function reportWarning(warning) {
119
+ try {
120
+ const sink = Reflect.get(globalThis, SINK_KEY);
121
+ if (sink?.(warning) === true) {
122
+ return;
123
+ }
124
+ } catch {
125
+ }
126
+ process.emitWarning(warning.text, { type: "Warning", code: warning.code });
127
+ }
128
+
90
129
  // src/sdk/assembly.ts
91
130
  var FS_INSTRUMENTATION = "@opentelemetry/instrumentation-fs";
92
131
  var HTTP_INSTRUMENTATION = "@opentelemetry/instrumentation-http";
93
132
  var IOREDIS_INSTRUMENTATION = "@opentelemetry/instrumentation-ioredis";
94
133
  var REDIS_INSTRUMENTATION = "@opentelemetry/instrumentation-redis";
95
134
  var PINO_INSTRUMENTATION = "@opentelemetry/instrumentation-pino";
135
+ var WINSTON_INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
136
+ var BUNYAN_INSTRUMENTATION = "@opentelemetry/instrumentation-bunyan";
96
137
  var LOG_EXPORTERS = /* @__PURE__ */ new Set(["otlp", "console"]);
97
138
  var UNKNOWN_SERVICE_NAME = "unknown_service:node";
98
139
  var WARNING_OPTIONS = {
@@ -128,10 +169,13 @@ function buildInstrumentationConfig(options, signals) {
128
169
  if (config !== void 0) overrides[name] = { ...config };
129
170
  }
130
171
  const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
172
+ const disableLogSending = !(instrumentations.sendLogs ?? signals.sendLogs);
131
173
  const library = {
132
174
  [FS_INSTRUMENTATION]: { enabled: instrumentations.fs === true },
133
175
  [HTTP_INSTRUMENTATION]: {},
134
- [PINO_INSTRUMENTATION]: { disableLogSending: !(instrumentations.sendLogs ?? signals.sendLogs) }
176
+ [PINO_INSTRUMENTATION]: { disableLogSending },
177
+ [WINSTON_INSTRUMENTATION]: { disableLogSending },
178
+ [BUNYAN_INSTRUMENTATION]: { disableLogSending }
135
179
  };
136
180
  const merged = {};
137
181
  for (const name of /* @__PURE__ */ new Set([...Object.keys(library), ...Object.keys(overrides)])) {
@@ -172,7 +216,13 @@ function warnAboutUnsafeOptions(options) {
172
216
  }
173
217
  if (options.unsafe?.exportProcessCommandArgs === true) {
174
218
  process.emitWarning(
175
- "Process command-line redaction is disabled: process.command_args and process.command_line are exported in the resource, and command-line arguments can carry secrets.",
219
+ "Process command-line redaction is disabled: process.command_args, process.command_line and process.command are exported in the resource, and command-line arguments can carry secrets.",
220
+ WARNING_OPTIONS
221
+ );
222
+ }
223
+ if (options.unsafe?.exportHostId === true) {
224
+ process.emitWarning(
225
+ "Host id redaction is disabled: host.id, the machine identifier, is exported in the resource, and it identifies the machine to every collector and backend.",
176
226
  WARNING_OPTIONS
177
227
  );
178
228
  }
@@ -183,6 +233,25 @@ function warnAboutUnsafeOptions(options) {
183
233
  );
184
234
  }
185
235
  }
236
+ var SHOWN_VALUE_LENGTH = 40;
237
+ function warnAboutSamplerRatio(sampler) {
238
+ if (sampler === void 0) return;
239
+ const ratio = Number(sampler.arg);
240
+ if (ratio >= 0 && ratio <= 1) return;
241
+ const given = sampler.arg === void 0 ? "not set" : `${JSON.stringify(sampler.arg.slice(0, SHOWN_VALUE_LENGTH))}, which is not a number from 0 to 1`;
242
+ reportWarning({
243
+ code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
244
+ text: `OTEL_TRACES_SAMPLER is ${sampler.name}, but OTEL_TRACES_SAMPLER_ARG is ${given}, so the SDK samples every trace. Set it to the share of traces to keep, from 0 to 1, such as 0.1.`
245
+ });
246
+ }
247
+ function warnAboutOversizedTimers(env) {
248
+ for (const name of env.oversizedTimers) {
249
+ process.emitWarning(
250
+ `${name} is above 2147483647 ms, which a timer cannot hold, so the default applies. Set a value up to 2147483647.`,
251
+ { type: "Warning", code: "BYMAX_TELEMETRY_BSP_VALUE_IGNORED" }
252
+ );
253
+ }
254
+ }
186
255
  function warnAboutIgnoredOptions(options) {
187
256
  const stop = options.enabled === false;
188
257
  if (stop || Object.values(options).some((v) => v !== void 0)) {
@@ -193,19 +262,6 @@ function warnAboutIgnoredOptions(options) {
193
262
  }
194
263
  }
195
264
 
196
- // src/sdk/warning-sink.ts
197
- var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
198
- function reportWarning(warning) {
199
- try {
200
- const sink = Reflect.get(globalThis, SINK_KEY);
201
- if (sink?.(warning) === true) {
202
- return;
203
- }
204
- } catch {
205
- }
206
- process.emitWarning(warning.text, { type: "Warning", code: warning.code });
207
- }
208
-
209
265
  // src/sdk/export-failure.ts
210
266
  var WINDOW_MS = 6e4;
211
267
  var SUCCESS = 0;
@@ -310,7 +366,12 @@ function createHandle(stopSdk, shutdownTimeoutMs) {
310
366
  }
311
367
 
312
368
  // src/sdk/resource-detectors.ts
313
- var COMMAND_LINE_ATTRIBUTES = ["process.command_args", "process.command_line"];
369
+ var COMMAND_LINE_ATTRIBUTES = [
370
+ "process.command_args",
371
+ "process.command_line",
372
+ "process.command"
373
+ ];
374
+ var HOST_ID_ATTRIBUTES = ["host.id"];
314
375
  var NAMED = /* @__PURE__ */ new Map([
315
376
  ["process", ["process"]],
316
377
  ["host", ["host", "os"]],
@@ -342,8 +403,12 @@ function withoutAttributes(detector, names) {
342
403
  }
343
404
  };
344
405
  }
345
- function selectResourceDetectors(selection, detectors, keepCommandLine) {
346
- const available = keepCommandLine ? detectors : { ...detectors, process: withoutAttributes(detectors.process, COMMAND_LINE_ATTRIBUTES) };
406
+ function selectResourceDetectors(selection, detectors, keeps) {
407
+ const available = {
408
+ ...detectors,
409
+ process: keeps.keepCommandLine ? detectors.process : withoutAttributes(detectors.process, COMMAND_LINE_ATTRIBUTES),
410
+ host: keeps.keepHostId ? detectors.host : withoutAttributes(detectors.host, HOST_ID_ATTRIBUTES)
411
+ };
347
412
  if (selection?.includes("none") === true && !selection.includes("all")) {
348
413
  return [];
349
414
  }
@@ -355,6 +420,33 @@ function selectResourceDetectors(selection, detectors, keepCommandLine) {
355
420
  }
356
421
  return [...new Set(chosen)].map((name) => available[name]);
357
422
  }
423
+ var TRANSPORT = "@opentelemetry/winston-transport";
424
+ var BUNDLE = "@opentelemetry/auto-instrumentations-node";
425
+ var INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
426
+ var MESSAGE = `Log forwarding is on and winston is installed, but ${TRANSPORT} cannot be resolved from ${INSTRUMENTATION}, so winston records will not reach the logs pipeline. Install ${TRANSPORT} as a direct dependency of the application, or set instrumentations.sendLogs to false. Ignore this if the application does not use winston.`;
427
+ var resolveFrom = (id, from) => {
428
+ try {
429
+ return createRequire(from).resolve(id);
430
+ } catch {
431
+ return void 0;
432
+ }
433
+ };
434
+ function entryFile(argv = process.argv, cwd = process.cwd()) {
435
+ return argv[1] ?? join(cwd, "entry.js");
436
+ }
437
+ function transportMissing(entry, resolve) {
438
+ if (resolve("winston", entry) === void 0) return false;
439
+ const bundle = resolve(BUNDLE, entry);
440
+ if (bundle === void 0) return false;
441
+ const instrumentation = resolve(INSTRUMENTATION, bundle);
442
+ if (instrumentation === void 0) return false;
443
+ return resolve(TRANSPORT, instrumentation) === void 0;
444
+ }
445
+ function warnAboutMissingWinstonTransport(sendLogs, entry = entryFile(), resolve = resolveFrom) {
446
+ if (sendLogs && transportMissing(entry, resolve)) {
447
+ reportWarning({ code: "BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING", text: MESSAGE });
448
+ }
449
+ }
358
450
 
359
451
  // src/sdk/start.ts
360
452
  var RESTART_MESSAGE = "Telemetry cannot start again after it was shut down in the same process: the modules the first start instrumented stay patched against its tracer provider, so a second SDK would export nothing for them. Start telemetry once per process; in a test suite, start it once in a global setup.";
@@ -418,7 +510,10 @@ function buildSdk(packages, options, env) {
418
510
  process: resources.processDetector,
419
511
  serviceinstance: resources.serviceInstanceIdDetector
420
512
  },
421
- options.unsafe?.exportProcessCommandArgs === true
513
+ {
514
+ keepCommandLine: options.unsafe?.exportProcessCommandArgs === true,
515
+ keepHostId: options.unsafe?.exportHostId === true
516
+ }
422
517
  ),
423
518
  spanProcessors: [
424
519
  // Ordered before the batch processor, so each span is redacted in place before it is exported.
@@ -436,6 +531,9 @@ function buildSdk(packages, options, env) {
436
531
  async function boot(options, env) {
437
532
  warnAboutUnsafeOptions(options);
438
533
  warnAboutMissingServiceName(options, env);
534
+ warnAboutOversizedTimers(env);
535
+ warnAboutSamplerRatio(readRatioSampler());
536
+ warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
439
537
  const sdk = buildSdk(await loadPackages(), options, env);
440
538
  sdk.start();
441
539
  const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
@@ -1,5 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ var module$1 = require('module');
4
+ var path = require('path');
5
+
3
6
  // src/sdk/redaction.ts
4
7
  var REDACTED_QUERY_VALUE = "[redacted]";
5
8
  var URL_QUERY_ATTRIBUTE = "url.query";
@@ -166,6 +169,8 @@ var HTTP_INSTRUMENTATION = "@opentelemetry/instrumentation-http";
166
169
  var IOREDIS_INSTRUMENTATION = "@opentelemetry/instrumentation-ioredis";
167
170
  var REDIS_INSTRUMENTATION = "@opentelemetry/instrumentation-redis";
168
171
  var PINO_INSTRUMENTATION = "@opentelemetry/instrumentation-pino";
172
+ var WINSTON_INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
173
+ var BUNYAN_INSTRUMENTATION = "@opentelemetry/instrumentation-bunyan";
169
174
  var LOG_EXPORTERS = /* @__PURE__ */ new Set(["otlp", "console"]);
170
175
  var UNKNOWN_SERVICE_NAME = "unknown_service:node";
171
176
  var WARNING_OPTIONS = {
@@ -201,10 +206,13 @@ function buildInstrumentationConfig(options, signals) {
201
206
  if (config !== void 0) overrides[name] = { ...config };
202
207
  }
203
208
  const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
209
+ const disableLogSending = !(instrumentations.sendLogs ?? signals.sendLogs);
204
210
  const library = {
205
211
  [FS_INSTRUMENTATION]: { enabled: instrumentations.fs === true },
206
212
  [HTTP_INSTRUMENTATION]: {},
207
- [PINO_INSTRUMENTATION]: { disableLogSending: !(instrumentations.sendLogs ?? signals.sendLogs) }
213
+ [PINO_INSTRUMENTATION]: { disableLogSending },
214
+ [WINSTON_INSTRUMENTATION]: { disableLogSending },
215
+ [BUNYAN_INSTRUMENTATION]: { disableLogSending }
208
216
  };
209
217
  const merged = {};
210
218
  for (const name of /* @__PURE__ */ new Set([...Object.keys(library), ...Object.keys(overrides)])) {
@@ -245,7 +253,13 @@ function warnAboutUnsafeOptions(options) {
245
253
  }
246
254
  if (options.unsafe?.exportProcessCommandArgs === true) {
247
255
  process.emitWarning(
248
- "Process command-line redaction is disabled: process.command_args and process.command_line are exported in the resource, and command-line arguments can carry secrets.",
256
+ "Process command-line redaction is disabled: process.command_args, process.command_line and process.command are exported in the resource, and command-line arguments can carry secrets.",
257
+ WARNING_OPTIONS
258
+ );
259
+ }
260
+ if (options.unsafe?.exportHostId === true) {
261
+ process.emitWarning(
262
+ "Host id redaction is disabled: host.id, the machine identifier, is exported in the resource, and it identifies the machine to every collector and backend.",
249
263
  WARNING_OPTIONS
250
264
  );
251
265
  }
@@ -256,6 +270,25 @@ function warnAboutUnsafeOptions(options) {
256
270
  );
257
271
  }
258
272
  }
273
+ var SHOWN_VALUE_LENGTH = 40;
274
+ function warnAboutSamplerRatio(sampler) {
275
+ if (sampler === void 0) return;
276
+ const ratio = Number(sampler.arg);
277
+ if (ratio >= 0 && ratio <= 1) return;
278
+ const given = sampler.arg === void 0 ? "not set" : `${JSON.stringify(sampler.arg.slice(0, SHOWN_VALUE_LENGTH))}, which is not a number from 0 to 1`;
279
+ reportWarning({
280
+ code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
281
+ text: `OTEL_TRACES_SAMPLER is ${sampler.name}, but OTEL_TRACES_SAMPLER_ARG is ${given}, so the SDK samples every trace. Set it to the share of traces to keep, from 0 to 1, such as 0.1.`
282
+ });
283
+ }
284
+ function warnAboutOversizedTimers(env) {
285
+ for (const name of env.oversizedTimers) {
286
+ process.emitWarning(
287
+ `${name} is above 2147483647 ms, which a timer cannot hold, so the default applies. Set a value up to 2147483647.`,
288
+ { type: "Warning", code: "BYMAX_TELEMETRY_BSP_VALUE_IGNORED" }
289
+ );
290
+ }
291
+ }
259
292
  function warnAboutIgnoredOptions(options) {
260
293
  const stop = options.enabled === false;
261
294
  if (stop || Object.values(options).some((v) => v !== void 0)) {
@@ -267,6 +300,8 @@ function warnAboutIgnoredOptions(options) {
267
300
  }
268
301
 
269
302
  // src/sdk/environment.ts
303
+ var MAX_TIMER_MS = 2147483647;
304
+ var RATIO_SAMPLERS = ["traceidratio", "parentbased_traceidratio"];
270
305
  function readExporterList(raw) {
271
306
  return (raw ?? "").split(",").map((name) => name.trim()).filter((name) => name !== "");
272
307
  }
@@ -274,13 +309,30 @@ function readPositiveNumber(raw) {
274
309
  const value = Number(raw);
275
310
  return Number.isFinite(value) && value > 0 ? value : void 0;
276
311
  }
312
+ function readTimerMillis(name, raw, oversized) {
313
+ const value = readPositiveNumber(raw);
314
+ if (value !== void 0 && value > MAX_TIMER_MS) {
315
+ oversized.push(name);
316
+ return void 0;
317
+ }
318
+ return value;
319
+ }
277
320
  function readTelemetryEnvironment(source = process.env) {
278
321
  const tuning = {};
279
322
  const maxQueueSize = readPositiveNumber(source["OTEL_BSP_MAX_QUEUE_SIZE"]);
280
323
  if (maxQueueSize !== void 0) tuning.maxQueueSize = maxQueueSize;
281
- const scheduledDelayMillis = readPositiveNumber(source["OTEL_BSP_SCHEDULE_DELAY"]);
324
+ const oversizedTimers = [];
325
+ const scheduledDelayMillis = readTimerMillis(
326
+ "OTEL_BSP_SCHEDULE_DELAY",
327
+ source["OTEL_BSP_SCHEDULE_DELAY"],
328
+ oversizedTimers
329
+ );
282
330
  if (scheduledDelayMillis !== void 0) tuning.scheduledDelayMillis = scheduledDelayMillis;
283
- const exportTimeoutMillis = readPositiveNumber(source["OTEL_BSP_EXPORT_TIMEOUT"]);
331
+ const exportTimeoutMillis = readTimerMillis(
332
+ "OTEL_BSP_EXPORT_TIMEOUT",
333
+ source["OTEL_BSP_EXPORT_TIMEOUT"],
334
+ oversizedTimers
335
+ );
284
336
  if (exportTimeoutMillis !== void 0) tuning.exportTimeoutMillis = exportTimeoutMillis;
285
337
  const maxExportBatchSize = readPositiveNumber(source["OTEL_BSP_MAX_EXPORT_BATCH_SIZE"]);
286
338
  if (maxExportBatchSize !== void 0) tuning.maxExportBatchSize = maxExportBatchSize;
@@ -292,9 +344,15 @@ function readTelemetryEnvironment(source = process.env) {
292
344
  metricsExporters: readExporterList(source["OTEL_METRICS_EXPORTER"]),
293
345
  logsExporters: readExporterList(source["OTEL_LOGS_EXPORTER"]),
294
346
  batchSpanProcessor: tuning,
347
+ oversizedTimers,
295
348
  resourceDetectors: detectors === void 0 || detectors.trim() === "" ? void 0 : readExporterList(detectors)
296
349
  };
297
350
  }
351
+ function readRatioSampler(source = process.env) {
352
+ const name = source["OTEL_TRACES_SAMPLER"];
353
+ const arg = source["OTEL_TRACES_SAMPLER_ARG"];
354
+ return name !== void 0 && RATIO_SAMPLERS.includes(name) ? { name, arg: arg?.trim() === "" ? void 0 : arg } : void 0;
355
+ }
298
356
 
299
357
  // src/sdk/export-failure.ts
300
358
  var WINDOW_MS = 6e4;
@@ -328,7 +386,12 @@ function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
328
386
  }
329
387
 
330
388
  // src/sdk/resource-detectors.ts
331
- var COMMAND_LINE_ATTRIBUTES = ["process.command_args", "process.command_line"];
389
+ var COMMAND_LINE_ATTRIBUTES = [
390
+ "process.command_args",
391
+ "process.command_line",
392
+ "process.command"
393
+ ];
394
+ var HOST_ID_ATTRIBUTES = ["host.id"];
332
395
  var NAMED = /* @__PURE__ */ new Map([
333
396
  ["process", ["process"]],
334
397
  ["host", ["host", "os"]],
@@ -360,8 +423,12 @@ function withoutAttributes(detector, names) {
360
423
  }
361
424
  };
362
425
  }
363
- function selectResourceDetectors(selection, detectors, keepCommandLine) {
364
- const available = keepCommandLine ? detectors : { ...detectors, process: withoutAttributes(detectors.process, COMMAND_LINE_ATTRIBUTES) };
426
+ function selectResourceDetectors(selection, detectors, keeps) {
427
+ const available = {
428
+ ...detectors,
429
+ process: keeps.keepCommandLine ? detectors.process : withoutAttributes(detectors.process, COMMAND_LINE_ATTRIBUTES),
430
+ host: keeps.keepHostId ? detectors.host : withoutAttributes(detectors.host, HOST_ID_ATTRIBUTES)
431
+ };
365
432
  if (selection?.includes("none") === true && !selection.includes("all")) {
366
433
  return [];
367
434
  }
@@ -373,6 +440,33 @@ function selectResourceDetectors(selection, detectors, keepCommandLine) {
373
440
  }
374
441
  return [...new Set(chosen)].map((name) => available[name]);
375
442
  }
443
+ var TRANSPORT = "@opentelemetry/winston-transport";
444
+ var BUNDLE = "@opentelemetry/auto-instrumentations-node";
445
+ var INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
446
+ var MESSAGE = `Log forwarding is on and winston is installed, but ${TRANSPORT} cannot be resolved from ${INSTRUMENTATION}, so winston records will not reach the logs pipeline. Install ${TRANSPORT} as a direct dependency of the application, or set instrumentations.sendLogs to false. Ignore this if the application does not use winston.`;
447
+ var resolveFrom = (id, from) => {
448
+ try {
449
+ return module$1.createRequire(from).resolve(id);
450
+ } catch {
451
+ return void 0;
452
+ }
453
+ };
454
+ function entryFile(argv = process.argv, cwd = process.cwd()) {
455
+ return argv[1] ?? path.join(cwd, "entry.js");
456
+ }
457
+ function transportMissing(entry, resolve) {
458
+ if (resolve("winston", entry) === void 0) return false;
459
+ const bundle = resolve(BUNDLE, entry);
460
+ if (bundle === void 0) return false;
461
+ const instrumentation = resolve(INSTRUMENTATION, bundle);
462
+ if (instrumentation === void 0) return false;
463
+ return resolve(TRANSPORT, instrumentation) === void 0;
464
+ }
465
+ function warnAboutMissingWinstonTransport(sendLogs, entry = entryFile(), resolve = resolveFrom) {
466
+ if (sendLogs && transportMissing(entry, resolve)) {
467
+ reportWarning({ code: "BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING", text: MESSAGE });
468
+ }
469
+ }
376
470
 
377
471
  // src/sdk/start.ts
378
472
  var RESTART_MESSAGE = "Telemetry cannot start again after it was shut down in the same process: the modules the first start instrumented stay patched against its tracer provider, so a second SDK would export nothing for them. Start telemetry once per process; in a test suite, start it once in a global setup.";
@@ -436,7 +530,10 @@ function buildSdk(packages, options, env) {
436
530
  process: resources.processDetector,
437
531
  serviceinstance: resources.serviceInstanceIdDetector
438
532
  },
439
- options.unsafe?.exportProcessCommandArgs === true
533
+ {
534
+ keepCommandLine: options.unsafe?.exportProcessCommandArgs === true,
535
+ keepHostId: options.unsafe?.exportHostId === true
536
+ }
440
537
  ),
441
538
  spanProcessors: [
442
539
  // Ordered before the batch processor, so each span is redacted in place before it is exported.
@@ -454,6 +551,9 @@ function buildSdk(packages, options, env) {
454
551
  async function boot(options, env) {
455
552
  warnAboutUnsafeOptions(options);
456
553
  warnAboutMissingServiceName(options, env);
554
+ warnAboutOversizedTimers(env);
555
+ warnAboutSamplerRatio(readRatioSampler());
556
+ warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
457
557
  const sdk = buildSdk(await loadPackages(), options, env);
458
558
  sdk.start();
459
559
  const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
@@ -41,18 +41,25 @@ interface UnsafeOptions {
41
41
  /** Keeps Redis command arguments in `db.query.text`, including `EVAL` and `EVALSHA` payloads. */
42
42
  readonly disableRedisArgumentRedaction?: true;
43
43
  /**
44
- * Keeps `process.command_args` and `process.command_line` in the exported resource. They are
45
- * removed by default, because command-line arguments are a common carrier of secrets.
44
+ * Keeps `process.command_args`, `process.command_line` and `process.command` in the exported
45
+ * resource. They are removed by default, because command-line arguments are a common carrier of
46
+ * secrets, and `process.command` is the first argument for `node -e code ARG`.
46
47
  */
47
48
  readonly exportProcessCommandArgs?: true;
49
+ /**
50
+ * Keeps `host.id` in the exported resource. It is removed by default: it is the machine
51
+ * identifier (the platform UUID, or `/etc/machine-id`), a stable hardware id that every collector
52
+ * and backend would see. `host.name` stays.
53
+ */
54
+ readonly exportHostId?: true;
48
55
  }
49
56
  /** Instrumentation choices that are the host's policy, with their safe defaults. */
50
57
  interface InstrumentationOptions {
51
58
  /** File-system instrumentation. Off by default: it floods traces with context-free disk activity. */
52
59
  readonly fs?: boolean;
53
60
  /**
54
- * Whether pino's records are forwarded to the OpenTelemetry logs pipeline. Defaults to whether
55
- * `OTEL_LOGS_EXPORTER` names an exporter that exports logs.
61
+ * Whether the records of pino, winston and bunyan are forwarded to the OpenTelemetry logs
62
+ * pipeline. Defaults to whether `OTEL_LOGS_EXPORTER` names an exporter that exports logs.
56
63
  */
57
64
  readonly sendLogs?: boolean;
58
65
  /**
@@ -41,18 +41,25 @@ interface UnsafeOptions {
41
41
  /** Keeps Redis command arguments in `db.query.text`, including `EVAL` and `EVALSHA` payloads. */
42
42
  readonly disableRedisArgumentRedaction?: true;
43
43
  /**
44
- * Keeps `process.command_args` and `process.command_line` in the exported resource. They are
45
- * removed by default, because command-line arguments are a common carrier of secrets.
44
+ * Keeps `process.command_args`, `process.command_line` and `process.command` in the exported
45
+ * resource. They are removed by default, because command-line arguments are a common carrier of
46
+ * secrets, and `process.command` is the first argument for `node -e code ARG`.
46
47
  */
47
48
  readonly exportProcessCommandArgs?: true;
49
+ /**
50
+ * Keeps `host.id` in the exported resource. It is removed by default: it is the machine
51
+ * identifier (the platform UUID, or `/etc/machine-id`), a stable hardware id that every collector
52
+ * and backend would see. `host.name` stays.
53
+ */
54
+ readonly exportHostId?: true;
48
55
  }
49
56
  /** Instrumentation choices that are the host's policy, with their safe defaults. */
50
57
  interface InstrumentationOptions {
51
58
  /** File-system instrumentation. Off by default: it floods traces with context-free disk activity. */
52
59
  readonly fs?: boolean;
53
60
  /**
54
- * Whether pino's records are forwarded to the OpenTelemetry logs pipeline. Defaults to whether
55
- * `OTEL_LOGS_EXPORTER` names an exporter that exports logs.
61
+ * Whether the records of pino, winston and bunyan are forwarded to the OpenTelemetry logs
62
+ * pipeline. Defaults to whether `OTEL_LOGS_EXPORTER` names an exporter that exports logs.
56
63
  */
57
64
  readonly sendLogs?: boolean;
58
65
  /**
@@ -1,3 +1,6 @@
1
+ import { createRequire } from 'module';
2
+ import { join } from 'path';
3
+
1
4
  // src/sdk/redaction.ts
2
5
  var REDACTED_QUERY_VALUE = "[redacted]";
3
6
  var URL_QUERY_ATTRIBUTE = "url.query";
@@ -164,6 +167,8 @@ var HTTP_INSTRUMENTATION = "@opentelemetry/instrumentation-http";
164
167
  var IOREDIS_INSTRUMENTATION = "@opentelemetry/instrumentation-ioredis";
165
168
  var REDIS_INSTRUMENTATION = "@opentelemetry/instrumentation-redis";
166
169
  var PINO_INSTRUMENTATION = "@opentelemetry/instrumentation-pino";
170
+ var WINSTON_INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
171
+ var BUNYAN_INSTRUMENTATION = "@opentelemetry/instrumentation-bunyan";
167
172
  var LOG_EXPORTERS = /* @__PURE__ */ new Set(["otlp", "console"]);
168
173
  var UNKNOWN_SERVICE_NAME = "unknown_service:node";
169
174
  var WARNING_OPTIONS = {
@@ -199,10 +204,13 @@ function buildInstrumentationConfig(options, signals) {
199
204
  if (config !== void 0) overrides[name] = { ...config };
200
205
  }
201
206
  const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
207
+ const disableLogSending = !(instrumentations.sendLogs ?? signals.sendLogs);
202
208
  const library = {
203
209
  [FS_INSTRUMENTATION]: { enabled: instrumentations.fs === true },
204
210
  [HTTP_INSTRUMENTATION]: {},
205
- [PINO_INSTRUMENTATION]: { disableLogSending: !(instrumentations.sendLogs ?? signals.sendLogs) }
211
+ [PINO_INSTRUMENTATION]: { disableLogSending },
212
+ [WINSTON_INSTRUMENTATION]: { disableLogSending },
213
+ [BUNYAN_INSTRUMENTATION]: { disableLogSending }
206
214
  };
207
215
  const merged = {};
208
216
  for (const name of /* @__PURE__ */ new Set([...Object.keys(library), ...Object.keys(overrides)])) {
@@ -243,7 +251,13 @@ function warnAboutUnsafeOptions(options) {
243
251
  }
244
252
  if (options.unsafe?.exportProcessCommandArgs === true) {
245
253
  process.emitWarning(
246
- "Process command-line redaction is disabled: process.command_args and process.command_line are exported in the resource, and command-line arguments can carry secrets.",
254
+ "Process command-line redaction is disabled: process.command_args, process.command_line and process.command are exported in the resource, and command-line arguments can carry secrets.",
255
+ WARNING_OPTIONS
256
+ );
257
+ }
258
+ if (options.unsafe?.exportHostId === true) {
259
+ process.emitWarning(
260
+ "Host id redaction is disabled: host.id, the machine identifier, is exported in the resource, and it identifies the machine to every collector and backend.",
247
261
  WARNING_OPTIONS
248
262
  );
249
263
  }
@@ -254,6 +268,25 @@ function warnAboutUnsafeOptions(options) {
254
268
  );
255
269
  }
256
270
  }
271
+ var SHOWN_VALUE_LENGTH = 40;
272
+ function warnAboutSamplerRatio(sampler) {
273
+ if (sampler === void 0) return;
274
+ const ratio = Number(sampler.arg);
275
+ if (ratio >= 0 && ratio <= 1) return;
276
+ const given = sampler.arg === void 0 ? "not set" : `${JSON.stringify(sampler.arg.slice(0, SHOWN_VALUE_LENGTH))}, which is not a number from 0 to 1`;
277
+ reportWarning({
278
+ code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
279
+ text: `OTEL_TRACES_SAMPLER is ${sampler.name}, but OTEL_TRACES_SAMPLER_ARG is ${given}, so the SDK samples every trace. Set it to the share of traces to keep, from 0 to 1, such as 0.1.`
280
+ });
281
+ }
282
+ function warnAboutOversizedTimers(env) {
283
+ for (const name of env.oversizedTimers) {
284
+ process.emitWarning(
285
+ `${name} is above 2147483647 ms, which a timer cannot hold, so the default applies. Set a value up to 2147483647.`,
286
+ { type: "Warning", code: "BYMAX_TELEMETRY_BSP_VALUE_IGNORED" }
287
+ );
288
+ }
289
+ }
257
290
  function warnAboutIgnoredOptions(options) {
258
291
  const stop = options.enabled === false;
259
292
  if (stop || Object.values(options).some((v) => v !== void 0)) {
@@ -265,6 +298,8 @@ function warnAboutIgnoredOptions(options) {
265
298
  }
266
299
 
267
300
  // src/sdk/environment.ts
301
+ var MAX_TIMER_MS = 2147483647;
302
+ var RATIO_SAMPLERS = ["traceidratio", "parentbased_traceidratio"];
268
303
  function readExporterList(raw) {
269
304
  return (raw ?? "").split(",").map((name) => name.trim()).filter((name) => name !== "");
270
305
  }
@@ -272,13 +307,30 @@ function readPositiveNumber(raw) {
272
307
  const value = Number(raw);
273
308
  return Number.isFinite(value) && value > 0 ? value : void 0;
274
309
  }
310
+ function readTimerMillis(name, raw, oversized) {
311
+ const value = readPositiveNumber(raw);
312
+ if (value !== void 0 && value > MAX_TIMER_MS) {
313
+ oversized.push(name);
314
+ return void 0;
315
+ }
316
+ return value;
317
+ }
275
318
  function readTelemetryEnvironment(source = process.env) {
276
319
  const tuning = {};
277
320
  const maxQueueSize = readPositiveNumber(source["OTEL_BSP_MAX_QUEUE_SIZE"]);
278
321
  if (maxQueueSize !== void 0) tuning.maxQueueSize = maxQueueSize;
279
- const scheduledDelayMillis = readPositiveNumber(source["OTEL_BSP_SCHEDULE_DELAY"]);
322
+ const oversizedTimers = [];
323
+ const scheduledDelayMillis = readTimerMillis(
324
+ "OTEL_BSP_SCHEDULE_DELAY",
325
+ source["OTEL_BSP_SCHEDULE_DELAY"],
326
+ oversizedTimers
327
+ );
280
328
  if (scheduledDelayMillis !== void 0) tuning.scheduledDelayMillis = scheduledDelayMillis;
281
- const exportTimeoutMillis = readPositiveNumber(source["OTEL_BSP_EXPORT_TIMEOUT"]);
329
+ const exportTimeoutMillis = readTimerMillis(
330
+ "OTEL_BSP_EXPORT_TIMEOUT",
331
+ source["OTEL_BSP_EXPORT_TIMEOUT"],
332
+ oversizedTimers
333
+ );
282
334
  if (exportTimeoutMillis !== void 0) tuning.exportTimeoutMillis = exportTimeoutMillis;
283
335
  const maxExportBatchSize = readPositiveNumber(source["OTEL_BSP_MAX_EXPORT_BATCH_SIZE"]);
284
336
  if (maxExportBatchSize !== void 0) tuning.maxExportBatchSize = maxExportBatchSize;
@@ -290,9 +342,15 @@ function readTelemetryEnvironment(source = process.env) {
290
342
  metricsExporters: readExporterList(source["OTEL_METRICS_EXPORTER"]),
291
343
  logsExporters: readExporterList(source["OTEL_LOGS_EXPORTER"]),
292
344
  batchSpanProcessor: tuning,
345
+ oversizedTimers,
293
346
  resourceDetectors: detectors === void 0 || detectors.trim() === "" ? void 0 : readExporterList(detectors)
294
347
  };
295
348
  }
349
+ function readRatioSampler(source = process.env) {
350
+ const name = source["OTEL_TRACES_SAMPLER"];
351
+ const arg = source["OTEL_TRACES_SAMPLER_ARG"];
352
+ return name !== void 0 && RATIO_SAMPLERS.includes(name) ? { name, arg: arg?.trim() === "" ? void 0 : arg } : void 0;
353
+ }
296
354
 
297
355
  // src/sdk/export-failure.ts
298
356
  var WINDOW_MS = 6e4;
@@ -326,7 +384,12 @@ function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
326
384
  }
327
385
 
328
386
  // src/sdk/resource-detectors.ts
329
- var COMMAND_LINE_ATTRIBUTES = ["process.command_args", "process.command_line"];
387
+ var COMMAND_LINE_ATTRIBUTES = [
388
+ "process.command_args",
389
+ "process.command_line",
390
+ "process.command"
391
+ ];
392
+ var HOST_ID_ATTRIBUTES = ["host.id"];
330
393
  var NAMED = /* @__PURE__ */ new Map([
331
394
  ["process", ["process"]],
332
395
  ["host", ["host", "os"]],
@@ -358,8 +421,12 @@ function withoutAttributes(detector, names) {
358
421
  }
359
422
  };
360
423
  }
361
- function selectResourceDetectors(selection, detectors, keepCommandLine) {
362
- const available = keepCommandLine ? detectors : { ...detectors, process: withoutAttributes(detectors.process, COMMAND_LINE_ATTRIBUTES) };
424
+ function selectResourceDetectors(selection, detectors, keeps) {
425
+ const available = {
426
+ ...detectors,
427
+ process: keeps.keepCommandLine ? detectors.process : withoutAttributes(detectors.process, COMMAND_LINE_ATTRIBUTES),
428
+ host: keeps.keepHostId ? detectors.host : withoutAttributes(detectors.host, HOST_ID_ATTRIBUTES)
429
+ };
363
430
  if (selection?.includes("none") === true && !selection.includes("all")) {
364
431
  return [];
365
432
  }
@@ -371,6 +438,33 @@ function selectResourceDetectors(selection, detectors, keepCommandLine) {
371
438
  }
372
439
  return [...new Set(chosen)].map((name) => available[name]);
373
440
  }
441
+ var TRANSPORT = "@opentelemetry/winston-transport";
442
+ var BUNDLE = "@opentelemetry/auto-instrumentations-node";
443
+ var INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
444
+ var MESSAGE = `Log forwarding is on and winston is installed, but ${TRANSPORT} cannot be resolved from ${INSTRUMENTATION}, so winston records will not reach the logs pipeline. Install ${TRANSPORT} as a direct dependency of the application, or set instrumentations.sendLogs to false. Ignore this if the application does not use winston.`;
445
+ var resolveFrom = (id, from) => {
446
+ try {
447
+ return createRequire(from).resolve(id);
448
+ } catch {
449
+ return void 0;
450
+ }
451
+ };
452
+ function entryFile(argv = process.argv, cwd = process.cwd()) {
453
+ return argv[1] ?? join(cwd, "entry.js");
454
+ }
455
+ function transportMissing(entry, resolve) {
456
+ if (resolve("winston", entry) === void 0) return false;
457
+ const bundle = resolve(BUNDLE, entry);
458
+ if (bundle === void 0) return false;
459
+ const instrumentation = resolve(INSTRUMENTATION, bundle);
460
+ if (instrumentation === void 0) return false;
461
+ return resolve(TRANSPORT, instrumentation) === void 0;
462
+ }
463
+ function warnAboutMissingWinstonTransport(sendLogs, entry = entryFile(), resolve = resolveFrom) {
464
+ if (sendLogs && transportMissing(entry, resolve)) {
465
+ reportWarning({ code: "BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING", text: MESSAGE });
466
+ }
467
+ }
374
468
 
375
469
  // src/sdk/start.ts
376
470
  var RESTART_MESSAGE = "Telemetry cannot start again after it was shut down in the same process: the modules the first start instrumented stay patched against its tracer provider, so a second SDK would export nothing for them. Start telemetry once per process; in a test suite, start it once in a global setup.";
@@ -434,7 +528,10 @@ function buildSdk(packages, options, env) {
434
528
  process: resources.processDetector,
435
529
  serviceinstance: resources.serviceInstanceIdDetector
436
530
  },
437
- options.unsafe?.exportProcessCommandArgs === true
531
+ {
532
+ keepCommandLine: options.unsafe?.exportProcessCommandArgs === true,
533
+ keepHostId: options.unsafe?.exportHostId === true
534
+ }
438
535
  ),
439
536
  spanProcessors: [
440
537
  // Ordered before the batch processor, so each span is redacted in place before it is exported.
@@ -452,6 +549,9 @@ function buildSdk(packages, options, env) {
452
549
  async function boot(options, env) {
453
550
  warnAboutUnsafeOptions(options);
454
551
  warnAboutMissingServiceName(options, env);
552
+ warnAboutOversizedTimers(env);
553
+ warnAboutSamplerRatio(readRatioSampler());
554
+ warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
455
555
  const sdk = buildSdk(await loadPackages(), options, env);
456
556
  sdk.start();
457
557
  const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-telemetry",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "OpenTelemetry tracing for NestJS 11 and plain Node: starts the SDK before your app loads, redacts secrets from spans by default, and flushes on shutdown. Optional peers, zero cost when disabled.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -76,7 +76,8 @@
76
76
  "check:file-length": "node scripts/check-file-length.mjs",
77
77
  "clean": "rm -rf dist coverage",
78
78
  "check:socket-gate": "node scripts/check-socket-gate.mjs",
79
- "lint": "eslint src scripts test '*.config.ts' '*.config.mjs' '*.config.cjs' && pnpm check:socket-gate",
79
+ "check:spec-headers": "node scripts/check-spec-headers.mjs",
80
+ "lint": "eslint src scripts test '*.config.ts' '*.config.mjs' '*.config.cjs' && pnpm check:socket-gate && pnpm check:spec-headers && node --test scripts/check-spec-headers.test.mjs",
80
81
  "lint:fix": "eslint src scripts test '*.config.ts' '*.config.mjs' '*.config.cjs' --fix",
81
82
  "mutation": "stryker run",
82
83
  "mutation:full": "node -e \"require('node:fs').rmSync('reports/stryker-incremental.json',{force:true,recursive:true})\" && stryker run",
@@ -169,6 +170,7 @@
169
170
  "@opentelemetry/resources": "^3.1.1",
170
171
  "@opentelemetry/sdk-node": "^0.301.1",
171
172
  "@opentelemetry/sdk-trace": "^3.1.1",
173
+ "@opentelemetry/winston-transport": "0.35.0",
172
174
  "@stryker-mutator/core": "^9",
173
175
  "@stryker-mutator/jest-runner": "^9",
174
176
  "@stryker-mutator/typescript-checker": "^9",
@@ -192,14 +194,15 @@
192
194
  "mysql2": "3.24.6",
193
195
  "pino": "10.4.0",
194
196
  "prettier": "^3.8.3",
195
- "redis": "^5.12.2",
197
+ "redis": "^6.3.1",
196
198
  "reflect-metadata": "^0.2.2",
197
199
  "rxjs": "^7.8.0",
198
200
  "supertest": "^7.2.2",
199
201
  "ts-jest": "^29.4.9",
200
202
  "ts-node": "^10.9.2",
201
203
  "tsup": "^9.0.0",
202
- "typescript": "^5.9.3"
204
+ "typescript": "^5.9.3",
205
+ "winston": "3.19.0"
203
206
  },
204
207
  "keywords": [
205
208
  "nestjs",