@sherlock-labs/node 0.0.0-stage → 0.3.0-rc.1

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
@@ -1,3 +1,681 @@
1
- # Temporary Holding Version
1
+ # Sherlock Distribution of OpenTelemetry for Node.js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Sherlock Distribution of [OpenTelemetry JS](https://github.com/open-telemetry/opentelemetry-js) instruments your Node.js application, sends traces and metrics to Sherlock, and — unlike any other Node.js distribution — puts **trace-linked exemplars on your histograms**. Click a spike in a latency chart and land on the request that caused it: its trace, its spans, its logs.
4
+
5
+ This distribution comes with the following defaults:
6
+
7
+ - [W3C tracecontext and baggage propagation](https://www.w3.org/TR/trace-context).
8
+ - OTLP/HTTP exporters pointed at your Sherlock ingest endpoint, metrics on a 30 s interval with **delta** temporality.
9
+ - Many bundled [instrumentations](#default-instrumentation-packages), via `@opentelemetry/auto-instrumentations-node`.
10
+ - Exemplars on your own histograms through `recordWithExemplar`, and on the auto-instrumented HTTP server and client duration histograms for sampled requests.
11
+ - Upstream OpenTelemetry packages, unmodified. Direct dependencies are pinned to exact versions.
12
+
13
+ For the main differences from a plain OpenTelemetry JS setup, see [What this changes versus plain OpenTelemetry](#what-this-changes-versus-plain-opentelemetry).
14
+
15
+ ## Why exemplars matter here
16
+
17
+ An exemplar is a single sampled measurement attached to a histogram bucket, carrying the trace id, span id, and any high-cardinality attributes you attach (a request id, a customer id). It is the link from "p99 got worse at 14:20" to "here is one of the slow requests."
18
+
19
+ The OpenTelemetry spec has had exemplars for years. **The OpenTelemetry JS SDK cannot emit them** — the bridge between aggregation and the exporter was never built ([open-telemetry/opentelemetry-js#5147](https://github.com/open-telemetry/opentelemetry-js/issues/5147)). Java, Go, and .NET give you exemplars for free; Node.js gives you none.
20
+
21
+ This distribution builds that missing piece: per-bucket reservoirs, an exporter that carries the exemplars onto the right data points, and hooks that cover the HTTP histograms the SDK records on its own. You write ordinary OpenTelemetry code and get exemplars anyway.
22
+
23
+ ## Get started
24
+
25
+ Install the distribution:
26
+
27
+ ```sh
28
+ npm install @sherlock-labs/node
29
+ ```
30
+
31
+ It requires Node.js 22.15 or newer, the floor of OpenTelemetry JS 3.
32
+
33
+ Load `register` before your app's own code. How depends on the module system your entrypoint uses.
34
+
35
+ **ES modules** (`"type": "module"`, `.mjs`, or TypeScript run as ESM): preload it with `--import`:
36
+
37
+ ```sh
38
+ node --import @sherlock-labs/node/register src/server.js
39
+ ```
40
+
41
+ **CommonJS** (`require`, or TypeScript compiled to CommonJS): require it on the very first line of the entrypoint, or preload it with `--require`:
42
+
43
+ ```js
44
+ // index.js — line 1, always
45
+ require('@sherlock-labs/node/register');
46
+
47
+ const { startServer } = require('./server');
48
+
49
+ startServer();
50
+ ```
51
+
52
+ Then set three environment variables and run your app normally:
53
+
54
+ ```sh
55
+ export SHERLOCK_ACCESS_TOKEN=<your token>
56
+ export SHERLOCK_ENDPOINT=<your ingest endpoint>
57
+ export OTEL_SERVICE_NAME=checkout-api
58
+ node --import @sherlock-labs/node/register src/server.js # or: node index.js
59
+ ```
60
+
61
+ That is the whole zero-code path: traces and metrics flow to Sherlock, and the HTTP duration histograms arrive with exemplars. `register` starts the pipelines itself when it finds all three of those variables set — see [Who starts the pipelines](#who-starts-the-pipelines) for what happens when your code calls `start()` too.
62
+
63
+ > **Load order is not a style rule.** Instrumentation patches wrap a library at the moment that library loads. Anything loaded before `@sherlock-labs/node/register` is taken unpatched and is silently never traced.
64
+ >
65
+ > **In an ES module, a line-1 `import` is not early enough.** Node resolves an ES module's whole static import graph before it runs any of it, so `import '@sherlock-labs/node/register'` at the top of `server.js` arrives after `server.js`'s other imports have already loaded. The ESM build of `register` installs a loader hook ([import-in-the-middle](https://github.com/nodejs/import-in-the-middle)) so that a CommonJS library an ES module imports, such as `ioredis`, is patched too, and a loader hook only sees what loads after it. Hence `--import`. When `register` finds it was not preloaded, `start()` logs a warning that says so.
66
+ >
67
+ > Don't want anything patched at all? `register` is optional — see [Metrics only, no patching](#metrics-only-no-patching).
68
+
69
+ ### Starting from code
70
+
71
+ If your access token is not in the environment at process start — it comes from a secret manager, a config service, or an async loader — split startup in two. `register` still loads first and installs the patches (`--import` for ES modules, line 1 for CommonJS); `start()` turns the pipelines on once you have the token.
72
+
73
+ ```js
74
+ // node --import @sherlock-labs/node/register src/server.js
75
+ import { start } from '@sherlock-labs/node';
76
+ import { loadConfig } from './config.js';
77
+
78
+ const config = await loadConfig();
79
+
80
+ start({
81
+ accessToken: config.sherlockToken,
82
+ endpoint: config.sherlockEndpoint,
83
+ serviceName: 'checkout-api',
84
+ tracing: { sampleRatio: 0.25 },
85
+ metrics: { exportIntervalMillis: 30_000 },
86
+ });
87
+ ```
88
+
89
+ The patches installed by `register` record nothing until `start()` runs, so the gap costs you only the telemetry from before startup finished.
90
+
91
+ ### Who starts the pipelines
92
+
93
+ Two things can start telemetry, and only one of them can win:
94
+
95
+ - **`register`**, on its own, when `SHERLOCK_ACCESS_TOKEN`, `SHERLOCK_ENDPOINT` and `OTEL_SERVICE_NAME` are all in the environment. This is the zero-code path.
96
+ - **`start()`**, from your code, with options no environment variable can express.
97
+
98
+ **`start()` always wins, whenever it is called.** If the environment already had all three variables, `register` may well have started first — `await loadConfig()` resumes long after `register` runs. When your `start()` arrives, it takes the pipelines over: the auto-started providers are shut down and flushed, and everything comes back up with your options. You never silently lose a `sampleRatio`, an `exporter.host`, or your `resourceAttributes` to a race you cannot see. Two limits apply: a `start()` without a token leaves a running auto-start in place, and a second explicit `start()` in the same run is ignored.
99
+
100
+ The takeover costs one restart during startup. To skip it entirely on a service that always configures telemetry from code, turn the auto-start off:
101
+
102
+ ```sh
103
+ export SHERLOCK_AUTO_START=false
104
+ ```
105
+
106
+ `start()` never throws because of its own errors, or when the `logger` option or the console throws. A global diagnostic logger the app installs itself with `diag.setLogger` sits outside that guarantee, because OpenTelemetry calls it directly. A missing token, service name or endpoint, or a malformed endpoint, logs a warning and starts nothing; a running auto-start stays in place.
107
+
108
+ `start()` builds the trace and metric providers directly. It creates no logger provider, so no logs pipeline starts.
109
+
110
+ Shut down cleanly (flushes the last metric interval and the pending span batch):
111
+
112
+ ```js
113
+ import { stop } from '@sherlock-labs/node';
114
+
115
+ process.on('SIGTERM', async () => {
116
+ await stop();
117
+ process.exit(0);
118
+ });
119
+ ```
120
+
121
+ ### Metrics only, no patching
122
+
123
+ Auto-instrumentation works by monkey-patching modules as they load. If that is a line you do not want to cross, skip it entirely: **omit the `register` import**, turn tracing off, and pass no instrumentations. Nothing is patched, `http` and your database driver are untouched, and custom metrics with exemplars still work exactly as documented.
124
+
125
+ ```js
126
+ // No '@sherlock-labs/node/register' import anywhere in the process.
127
+ import { start, defineHistogram } from '@sherlock-labs/node';
128
+
129
+ start({
130
+ accessToken: process.env.SHERLOCK_ACCESS_TOKEN,
131
+ endpoint: process.env.SHERLOCK_ENDPOINT,
132
+ serviceName: 'inference-api',
133
+ tracing: false,
134
+ instrumentations: [],
135
+ });
136
+
137
+ const inference = defineHistogram('app.inference.duration', {
138
+ unit: 's',
139
+ boundaries: [0.25, 0.5, 1, 2, 5, 15, 60],
140
+ });
141
+ ```
142
+
143
+ In this mode you keep your own HTTP timing — the framework adapters above work fine without any patching, since they measure from inside your request pipeline. What you lose is the trace context: with no traces there is no trace id, no span id, and no `trace_flags`, so an exemplar carries only the attributes you pass it yourself. Turning tracing on later is a config change, not a rewrite.
144
+
145
+ ## Configuration
146
+
147
+ Everything is configurable by environment variable. Anything you pass to `start()` wins over the environment.
148
+
149
+ ### Environment variables
150
+
151
+ | Variable | Default | Description |
152
+ |---|---|---|
153
+ | `SHERLOCK_ACCESS_TOKEN` | — | Ingest token. Without it the distribution stays off and logs one line. |
154
+ | `SHERLOCK_ENDPOINT` | — | Your Sherlock ingest base URL. Required; without it the distribution stays off. `/v1/traces` and `/v1/metrics` are appended. |
155
+ | `OTEL_SERVICE_NAME` | — | Service name. Required; without it the distribution stays off. |
156
+ | `OTEL_RESOURCE_ATTRIBUTES` | — | Extra resource attributes, e.g. `deployment.environment=prod`. |
157
+ | `OTEL_TRACES_SAMPLER_ARG` | `1` | Share of new traces to sample, `0`–`1`. An invalid value is ignored with a warning. |
158
+ | `SHERLOCK_TRACES_ENABLED` | `true` | Start with tracing off by setting `false`. |
159
+ | `SHERLOCK_METRICS_ENABLED` | `true` | Start with metrics off by setting `false`. |
160
+ | `SHERLOCK_METRICS_EXPORT_INTERVAL` | `30000` | Metric export interval, in milliseconds. |
161
+ | `SHERLOCK_AUTO_START` | `true` | Set `false` to stop `register` starting the pipelines from the environment. |
162
+ | `SHERLOCK_IGNORE_PATHS` | — | Extra request paths to leave uninstrumented, comma-separated. |
163
+ | `SHERLOCK_FASTIFY_LIFECYCLE_SPANS` | `false` | Set `true` for a span per Fastify hook and route handler. See [Fastify](#fastify). |
164
+ | `OTEL_LOG_LEVEL` | `warn` | Verbosity of the SDK's own diagnostics. |
165
+
166
+ ### `start()` options
167
+
168
+ | Option | Type | Default | Description |
169
+ |---|---|---|---|
170
+ | `accessToken` | `string` | `SHERLOCK_ACCESS_TOKEN` | Ingest token. |
171
+ | `endpoint` | `string` | `SHERLOCK_ENDPOINT` | Your Sherlock ingest base URL. Required: there is no default. |
172
+ | `serviceName` | `string` | `OTEL_SERVICE_NAME` | Service name on every span and metric. |
173
+ | `resourceAttributes` | `Attributes` | `{}` | Merged into the resource; your values win. |
174
+ | `tracing` | `boolean \| object` | `true` | `false` disables traces entirely. |
175
+ | `tracing.sampleRatio` | `number` | `1.0` | Share of new traces to sample. Parent-based: a request is traced whole or not at all. A request that arrives with a remote parent gets the same ratio; its sampled flag does not decide. |
176
+ | `metrics` | `boolean \| object` | `true` | `false` disables metrics entirely. |
177
+ | `metrics.exportIntervalMillis` | `number` | `30000` | Export interval. |
178
+ | `metrics.httpDurationBoundaries` | `number[]` | `DEFAULT_DURATION_BOUNDARIES_S` (see below) | Bucket boundaries, in seconds, for every HTTP duration histogram. Sorted and de-duplicated for you; a list with a non-finite value is rejected with a warning. |
179
+ | `metrics.exemplarsPerBucket` | `number` | `5` | Reservoir size per histogram bucket per interval. Must be a positive integer — anything else is rejected with a warning, because a reservoir of zero disables exemplars in complete silence. |
180
+ | `instrumentations` | `{ enabled } \| { disabled } \| Instrumentation[]` | whole bundle | Which instrumentations run: `{ enabled: ["http", "pg"] }` keeps only those, `{ disabled: ["dns", "net"] }` keeps everything else, and an explicit `Instrumentation[]` is for an app that does not load `register` (`[]` means none). Outranks `OTEL_NODE_ENABLED_INSTRUMENTATIONS` and `OTEL_NODE_DISABLED_INSTRUMENTATIONS`. The package's own HTTP hooks survive all three forms — see [Default instrumentation packages](#default-instrumentation-packages). |
181
+ | `fastify.lifecycleSpans` | `boolean` | `false` | A span per Fastify hook and route handler. See [Fastify](#fastify). |
182
+ | `ignorePaths` | `string[]` | `[]` | Extra incoming request paths the HTTP instrumentation leaves alone, on top of `/healthz`, `/livez` and `/healthcheck`. The framework adapters use `ignoreRequest` instead. |
183
+ | `exporter.headers` | `Record<string, string>` | `{}` | Extra headers on every export request, merged with the auth header. |
184
+ | `exporter.host` | `string` | — | Overrides the `Host` header on export requests, for setups that route by host. |
185
+ | `logger` | `{ debug, info, warn, error }` | console | A pino-compatible logger for the SDK's own diagnostics. It receives each line as one formatted string. If it throws, that line goes to the console. |
186
+
187
+ The exporter transport is `node:http`, deliberately. A custom `Host` header survives it — `fetch` and `undici` treat `Host` as forbidden and drop it, which breaks any deployment that routes by host header.
188
+
189
+ Nothing the distribution sends is ever traced or metered by it. Upstream already suppresses spans around an export. The package also skips every HTTP request to the ingest host **and port**, whatever its path, which keeps export requests out of `http.client.request.duration`. Pointing `endpoint` at a collector on `localhost` or an in-cluster IP leaves other ports at that address instrumented as normal.
190
+
191
+ #### HTTP duration buckets
192
+
193
+ The default boundaries are `DEFAULT_DURATION_BOUNDARIES_S`, in **seconds**:
194
+
195
+ ```
196
+ 0.005 0.01 0.025 0.05 0.075 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.75 1 2.5 5 7.5 10
197
+ ```
198
+
199
+ - **The list** is the HTTP semantic-convention list with finer steps across 100–500 ms.
200
+ - **It applies as one list** to the auto-instrumented `http.server.request.duration` and `http.client.request.duration` histograms and to their exemplar reservoirs. An exemplar competes in the same bucket its count lands in.
201
+ - **The same list** is the default of a custom histogram in seconds, the default unit (see [Custom metrics](#custom-metrics-with-exemplars)).
202
+
203
+ ## Manual spans
204
+
205
+ The distribution re-exports the manual-span surface of `@opentelemetry/api` — `trace`, `context`, `SpanKind`, `SpanStatusCode`, and the `Span`, `SpanContext`, `Attributes` and `Tracer` types:
206
+
207
+ ```ts
208
+ import { trace, SpanStatusCode } from '@sherlock-labs/node';
209
+
210
+ const tracer = trace.getTracer('checkout');
211
+
212
+ export async function settle(order) {
213
+ return tracer.startActiveSpan('order.settle', async (span) => {
214
+ span.setAttribute('order.provider', order.provider);
215
+ try {
216
+ return await doSettlement(order);
217
+ } catch (err) {
218
+ span.setStatus({ code: SpanStatusCode.ERROR, message: String(err) });
219
+ throw err;
220
+ } finally {
221
+ span.end();
222
+ }
223
+ });
224
+ }
225
+ ```
226
+
227
+ Import the API from this package rather than from `@opentelemetry/api`. Your app then calls the exact API module the SDK registers its providers with. Separate copies of `@opentelemetry/api` share providers only when their versions are compatible; an incompatible copy gets no-op providers.
228
+
229
+ ## Custom metrics with exemplars
230
+
231
+ Define instruments anywhere, at module scope included. A definition resolves the real instrument on the first record after `start()`.
232
+
233
+ ```ts
234
+ import { defineMeter } from '@sherlock-labs/node';
235
+
236
+ const m = defineMeter('app.billing');
237
+
238
+ const settlementDuration = m.histogram('app.order.settlement.duration', {
239
+ description: 'time to settle one order',
240
+ });
241
+
242
+ const settlements = m.counter('app.order.settlements', { unit: '{order}' });
243
+
244
+ export async function settle(order) {
245
+ const startedAt = performance.now();
246
+ await doSettlement(order);
247
+ const elapsedSeconds = (performance.now() - startedAt) / 1000;
248
+
249
+ settlements.add(1, { provider: order.provider });
250
+ settlementDuration.recordWithExemplar(
251
+ elapsedSeconds,
252
+ { provider: order.provider }, // metric attributes (low cardinality)
253
+ { orderId: order.id }, // exemplar-only attributes (high cardinality)
254
+ );
255
+ }
256
+ ```
257
+
258
+ - **`m.counter(name, { unit?, description? })`** defines a counter. `add(value, attrs)` adds to it.
259
+ - **`m.histogram(name, { unit?, description?, boundaries? })`** defines a histogram. `record(value, attrs)` records the measurement only.
260
+ - **A histogram's unit defaults to `'s'`**: record durations in seconds. A histogram that measures something else declares its unit: `m.histogram('app.payload.size', { unit: 'By' })`.
261
+ - **This is more prescriptive than a raw OpenTelemetry histogram.** `meter.createHistogram(name)` gives an instrument no unit and millisecond-scale buckets. The SDK takes the default the [semantic conventions](https://opentelemetry.io/docs/specs/semconv/general/metrics/) set instead: "when instruments are measuring durations, seconds (i.e. `s`) SHOULD be used". The bucket list follows the [HTTP metrics](https://opentelemetry.io/docs/specs/semconv/http/http-metrics/) recommendation, with finer 100–500 ms steps.
262
+ - **`recordWithExemplar(value, attrs, exemplarAttrs)`** also samples an exemplar into the bucket the value falls in. `exemplarAttrs` is yours: pass the high-cardinality keys you want to click through to.
263
+ - **`m.gauge(name, { unit?, description? })`** defines a gauge. `record(value, attrs)` keeps the **last** value per attribute set. Gauges have no exemplars, so there is no `recordWithExemplar`.
264
+
265
+ ```ts
266
+ const queueDepth = m.gauge('app.queue.depth', { unit: '{job}' });
267
+
268
+ queueDepth.record(jobs.length, { queue: 'orders' });
269
+ ```
270
+
271
+ ### Histogram boundaries
272
+
273
+ The SDK follows the OpenTelemetry [semantic conventions](https://opentelemetry.io/docs/specs/semconv/general/metrics/): durations are in **seconds**. `boundaries` is optional, and the default depends on the unit:
274
+
275
+ - **Unit `'s'`, explicit or default** → `DEFAULT_DURATION_BOUNDARIES_S`: `0.005 … 10`, the list the [HTTP histograms](#http-duration-buckets) use.
276
+ - **Any other unit** → `DEFAULT_HISTOGRAM_BOUNDARIES`: `0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000`. This list has no unit. Its numbers are in the unit the histogram records, so it fits a millisecond histogram.
277
+ - **An explicit `boundaries` list** always wins: `m.histogram('app.batch.duration', { boundaries: [1, 5, 30, 120, 600] })`.
278
+ - **Extend a default** when you need more headroom: `boundaries: [...DEFAULT_DURATION_BOUNDARIES_S, 30, 60]`.
279
+ - **The histogram and the exemplar reservoir get the same list**, so an exemplar lands in the same bucket as its count. There is no second boundaries argument to get wrong.
280
+
281
+ ### Scope and the standalone functions
282
+
283
+ `defineMeter(name)` binds the instrumentation scope once for a file of instruments. The standalone functions take the scope per instrument:
284
+
285
+ - **`defineCounter(name, { unit?, description?, meterName? })`**, **`defineHistogram(name, { unit?, description?, meterName?, boundaries? })`** and **`defineGauge(name, { unit?, description?, meterName? })`** are the same three definitions with `meterName` on each.
286
+ - **`meterName`** is the instrumentation scope an instrument is exported under, `'app'` by default.
287
+ - **Both forms return the same objects**: `CounterDef` / `HistogramDef` / `GaugeDef`, with the same lazy resolution, the same behaviour before `start()` and after `stop()`, and the same exemplar path.
288
+
289
+ ```ts
290
+ import { defineHistogram } from '@sherlock-labs/node';
291
+
292
+ const settlementDuration = defineHistogram('app.order.settlement.duration', {
293
+ meterName: 'app.billing',
294
+ });
295
+ ```
296
+
297
+ ### What an exemplar carries
298
+
299
+ Whenever a span is active, `recordWithExemplar` attaches that span's trace id and span id to the exemplar, and adds a `trace_flags` attribute holding the W3C trace-flags byte as two hex digits. It does this at **any** sampling decision, and `trace_flags` is what tells the two apart:
300
+
301
+ ```jsonc
302
+ // A sampled context: the link normally opens a trace. 01 does not confirm the export.
303
+ {
304
+ "timeUnixNano": "1756400000000000000",
305
+ "asDouble": 0.42,
306
+ "traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
307
+ "spanId": "00f067aa0ba902b7",
308
+ "filteredAttributes": [
309
+ { "key": "trace_flags", "value": { "stringValue": "01" } },
310
+ { "key": "orderId", "value": { "stringValue": "o-1" } }
311
+ ]
312
+ }
313
+ ```
314
+
315
+ ```jsonc
316
+ // The same call in an UNSAMPLED context: same ids, and 00 says this span was
317
+ // normally not exported. The ids still match this request's log lines, and other
318
+ // spans on the same trace may still exist.
319
+ {
320
+ "timeUnixNano": "1756400000000000000",
321
+ "asDouble": 0.42,
322
+ "traceId": "0af7651916cd43dd8448eb211c80319c",
323
+ "spanId": "b7ad6b7169203331",
324
+ "filteredAttributes": [
325
+ { "key": "trace_flags", "value": { "stringValue": "00" } },
326
+ { "key": "orderId", "value": { "stringValue": "o-1" } }
327
+ ]
328
+ }
329
+ ```
330
+
331
+ **Custom-metric exemplars exist at any sampling**, with `trace_flags` recording whether the span was sampled. **Auto-instrumented HTTP exemplars exist only for sampled requests.** The difference comes from how the hooks work: they rebuild the metric's attribute set from the span, and an unsampled request gets a non-recording span with no attributes. With no attribute set there is no data point to match, so the hooks skip that exemplar. A custom exemplar has no such problem, because you hand the metric attributes over yourself.
332
+
333
+ > **Why `defineHistogram` and not `meter.createHistogram`?** The OpenTelemetry metrics API has **no late binding**. `metrics.getMeter(...).createHistogram(...)` called before a MeterProvider is registered returns a permanent no-op — it never upgrades, and it never errors. A module-scope instrument in an app that starts telemetry asynchronously silently records nothing, forever. `defineHistogram` stores a definition and resolves the real instrument lazily on the first record after `start()`. Records before `start()` (or after `stop()`) are dropped, not broken.
334
+
335
+ ## HTTP server metrics
336
+
337
+ The distribution ships framework adapters that emit application-level HTTP metrics with exemplars, alongside the auto-instrumented ones. Each is a separate subpath so you only pull in the one you use.
338
+
339
+ **Koa** — `@sherlock-labs/node/koa`:
340
+
341
+ ```ts
342
+ import Koa from 'koa';
343
+ import { applyMetricsMiddleware } from '@sherlock-labs/node/koa';
344
+
345
+ const app = new Koa();
346
+ app.use(applyMetricsMiddleware());
347
+ ```
348
+
349
+ **Express** — `@sherlock-labs/node/express`:
350
+
351
+ ```ts
352
+ import express from 'express';
353
+ import { applyMetricsMiddleware } from '@sherlock-labs/node/express';
354
+
355
+ const app = express();
356
+ app.use(applyMetricsMiddleware());
357
+ ```
358
+
359
+ **Fastify** — `@sherlock-labs/node/fastify`, a plugin. Register it before your routes, and await it:
360
+
361
+ ```ts
362
+ import Fastify from 'fastify';
363
+ import { metricsPlugin } from '@sherlock-labs/node/fastify';
364
+
365
+ const app = Fastify();
366
+ await app.register(metricsPlugin());
367
+ ```
368
+
369
+ It covers every route in the app, including those inside encapsulated plugins and replies a route takes over with `reply.hijack()` (SSE streams, proxies). Register it once: a second registration, also one inside a child plugin, does nothing and logs a warning. Fastify 5 is the version it is tested against.
370
+
371
+ A stream is recorded for its whole lifetime, so a route that streams pushes `app.http.server.duration` towards minutes. When the response decides it — one route answering JSON or SSE depending on the request — skip it with `ignoreResponse`, which runs once the response has ended:
372
+
373
+ ```ts
374
+ await app.register(
375
+ metricsPlugin({
376
+ ignoreResponse: (_request, reply) =>
377
+ String(reply.raw.getHeader('content-type') ?? '').startsWith('text/event-stream'),
378
+ }),
379
+ );
380
+
381
+ app.post('/events', (request, reply) => {
382
+ reply.hijack();
383
+ reply.raw.setHeader('content-type', 'text/event-stream');
384
+ reply.raw.writeHead(200);
385
+ // …
386
+ });
387
+ ```
388
+
389
+ Set the stream's headers with `setHeader`, as above. Node keeps the headers passed to `writeHead(200, { … })` only on the wire, so `getHeader` cannot see them later. If the handler can't change, mark the request from the handler instead and test that mark in `ignoreResponse`.
390
+
391
+ Every adapter records the same three instruments, tagged with route, method, and status code:
392
+
393
+ | Metric | Type | Unit | Attributes |
394
+ |---|---|---|---|
395
+ | `app.http.server.count` | counter | requests | `route`, `method`, `status_code`, `status` |
396
+ | `app.http.server.errors` | counter | requests (5xx) | `route`, `method`, `status_code`, `status` |
397
+ | `app.http.server.duration` | histogram | seconds | `route`, `method`, `status_code`, `status` |
398
+
399
+ `route` is the framework's own route template, not the resolved path — so `/users/:id` stays one series instead of one per user id. `status_code` is the numeric status. `status` is `ok` or `error`; `app.http.server.errors` only counts the `error` ones.
400
+
401
+ A request that closes before the app sent any response is recorded with `status_code` `499`, nginx's "client closed request", and `status` `ok`, by the Express and Fastify adapters. A burst of client timeouts then shows as 499s, not as slow 200s. A response whose headers already went out keeps its own status, so a stream the client ends after reading it stays a 200. The Koa adapter records when the middleware chain settles, so it never sees the client leave.
402
+
403
+ Every adapter skips the paths the HTTP instrumentation ignores: `/healthz`, `/livez`, `/healthcheck`, and any added with `start({ ignorePaths })` or `SHERLOCK_IGNORE_PATHS`.
404
+
405
+ ### These attribute keys are not the auto-instrumented ones
406
+
407
+ The adapter metrics and the auto-instrumented `http.server.request.duration` use **different attribute keys for the same ideas**:
408
+
409
+ | Idea | Adapter `app.http.server.*` | Auto `http.server.request.duration` |
410
+ |---|---|---|
411
+ | Route | `route` | `http.route` |
412
+ | Method | `method` | `http.request.method` |
413
+ | Status code | `status_code` | `http.response.status_code` |
414
+ | Failure | `status` (`ok` / `error`) | `error.type` |
415
+
416
+ One label expression cannot filter both families. A dashboard that mixes them needs one expression per family.
417
+
418
+ **Whether the auto-instrumented family carries a route template depends on which instrumentations are on.** `instrumentation-http` patches the HTTP server below the framework, so on its own it never learns the route: every request collapses into one series per method and status code, with no way to tell `/users/:id` from `/checkout`. The framework instrumentations — `instrumentation-express`, `instrumentation-koa`, `instrumentation-router`, and this package's own `fastify` — do learn it, and set `http.route` on the server span, which puts it on `http.server.request.duration` too. All four are in the bundle `register` installs, so an app that has not narrowed the instrumentation set usually does get `http.route` there.
419
+
420
+ The adapter family is the one that does not depend on that. It reads the route from the framework itself, so it carries a route template whichever instrumentations are enabled — including metrics-only mode, where nothing is patched at all. Use it whenever the question is about a specific endpoint.
421
+
422
+ ### Adapter options
423
+
424
+ | Option | Type | Description |
425
+ |---|---|---|
426
+ | `ignoreRequest` | `(req) => boolean` | Skip a request entirely, decided when it arrives. Use it for websockets, long polls, and SSE-only routes. |
427
+ | `routeName` | `(req) => string \| undefined` | Override how the route template is derived. |
428
+ | `recordExemplars` | `boolean` | Default `true`. |
429
+ | `ignoreResponse` | `(request, reply) => boolean` | Fastify only. Skip a request once its response has ended. |
430
+
431
+ The Fastify callbacks take Fastify's own `FastifyRequest` and `FastifyReply` types.
432
+
433
+ The adapters never throw into your request path — recording failures are caught and logged through the SDK's diagnostics.
434
+
435
+ ## Fastify
436
+
437
+ Fastify apps get route names with no code. `register` includes a small instrumentation of this package's own, named `fastify`, that hands each request's route template (`/users/:id`) to the HTTP server instrumentation. So the server span is named `GET /users/:id` instead of `GET`, and `http.route` is on the span, on `http.server.request.duration`, and on that histogram's exemplars.
438
+
439
+ - **It patches nothing.** Fastify announces every new instance on its `fastify.initialization` diagnostics channel, and the instrumentation adds one `onRequest` hook there. It works the same for ES modules and CommonJS, whatever the load order.
440
+ - **An app without Fastify pays nothing.** The channel never fires, so none of it runs, and the `fastify` package is never loaded.
441
+ - **A 404 gets no route**, so unknown URLs stay one series.
442
+ - **It covers instances created after the SDK loads.** A `Fastify()` created before `./register` (or before any `FastifyInstrumentation` exists) gets no route names, because Fastify announced it before anyone listened.
443
+ - **Fastify 5** is the version it is tested against.
444
+ - **Turn it off** like any other instrumentation: `instrumentations: { disabled: ['fastify'] }` or `OTEL_NODE_DISABLED_INSTRUMENTATIONS=fastify`. In an app without `register` that passes its own list, add `new FastifyInstrumentation()` from `@sherlock-labs/node/fastify` to it.
445
+
446
+ The auto-instrumented `http.server.request.duration` includes every streamed reply for its whole lifetime, and has no hook to leave one out. Health checks on a path other than the defaults need `ignorePaths`.
447
+
448
+ ### When to add the plugin too
449
+
450
+ The route names above already give `http.server.request.duration` a route and an exemplar. Add the [Fastify adapter](#http-server-metrics) when you also want:
451
+
452
+ - **metrics-only mode**, where nothing is patched and the auto-instrumented histogram does not exist;
453
+ - **an exemplar on every request**, sampled or not: the auto-instrumented histogram only gets one for sampled requests;
454
+ - **request and error counters** (`app.http.server.count`, `.errors`);
455
+ - **your own route names** through `routeName`, or **streamed replies left out** through `ignoreResponse`.
456
+
457
+ ### If your app records `http.server.request.duration` itself
458
+
459
+ Delete it, or rename it, before you add the SDK. With the SDK, instrumentation-http records a histogram with the same name, so a dashboard that does not filter on the instrumentation scope counts every request twice. The SDK's bucket view also matches that name in any scope, so your own histogram is re-bucketed onto the SDK's list, and it can receive the SDK's exemplars when its attributes match.
460
+
461
+ The two differ where most hand-written versions made a choice: the SDK's has no `http.route` on a 404 (yours may say `unmatched`), and it includes streamed replies. If you need those choices kept, use the plugin: `routeName: (request) => request.routeOptions?.url ?? 'unmatched'` and `ignoreResponse` reproduce them on the `app.http.server.*` metrics.
462
+
463
+ ### Lifecycle spans
464
+
465
+ Off by default. Turn them on to see where a request's time goes inside Fastify: one span per lifecycle hook and per route handler, directly under the request's server span.
466
+
467
+ ```ts
468
+ start({ /* … */ fastify: { lifecycleSpans: true } });
469
+ ```
470
+
471
+ or `SHERLOCK_FASTIFY_LIFECYCLE_SPANS=true`.
472
+
473
+ ```
474
+ GET /api/apps/:id 79.3 ms
475
+ onRequest - authenticate 0.0 ms
476
+ preHandler - loadSession 0.6 ms
477
+ get (ioredis) 0.5 ms
478
+ handler - /api/apps/:id 78.1 ms
479
+ pg.query:SELECT app 1.4 ms
480
+ GET (fetch) 44.0 ms
481
+ ```
482
+
483
+ - Covers all ten Fastify lifecycle hooks (`onRequest`, `preParsing`, `preValidation`, `preHandler`, `preSerialization`, `onSend`, `onResponse`, `onError`, `onTimeout`, `onRequestAbort`), whether added with `addHook` (in any plugin) or on a route, plus every route handler.
484
+ - A hook span is named after the function, so name your hook functions; an arrow function shows as `anonymous`.
485
+ - A callback hook is timed until it calls `done`, an async one until it settles. A throw, a rejection or `done(err)` marks the span as an error with the exception.
486
+ - A handler span ends when the handler returns, or, for a handler that returns nothing and replies later from a callback, when that reply goes out.
487
+ - Spans carry `fastify.type` (`hook` or `handler`), `fastify.hook`, and `http.route`.
488
+ - A thrown 4xx records the exception without marking the span as an error, the same as the server span.
489
+ - They hang from the request's server span. Without one, as under `app.inject()` or with the `http` instrumentation off, there are none.
490
+ - Turning it on applies to instances created afterwards: set it before you create the instance; `start()` warns when an instance already exists without it. Turning it off applies at once, to every instance. `start()` also warns when it is on but the `fastify` instrumentation is not enabled.
491
+ - Not covered: `setErrorHandler` and `setNotFoundHandler` (they go through neither `addHook` nor a route), and route hooks another plugin adds in its own `onRoute` hook. Fastify's own HEAD-route hook is left out on purpose.
492
+ - Off, nothing is wrapped at all. On, a request becomes one span plus one per hook and handler it runs through, at a few microseconds each.
493
+ - Don't combine it with `@fastify/otel`'s hook spans: both would wrap the same hooks.
494
+
495
+ ## Log correlation
496
+
497
+ Exemplars and log lines share one vocabulary: `trace_id`, `span_id` and `trace_flags`. The bundled pino instrumentation stamps those three on every log line your app writes inside a request, and every exemplar carries the same three — the two ids as the exemplar's own `traceId` / `spanId`, the flags as a `trace_flags` attribute.
498
+
499
+ So the path from a chart to the logs is one join on `trace_id`. Click the spike, open its exemplar, take the trace id, filter your logs by it. There is nothing to configure and no resolver to hand over.
500
+
501
+ `trace_flags` says what kind of link you hold:
502
+
503
+ | `trace_flags` | Meaning |
504
+ |---|---|
505
+ | `01` | The active span context is sampled, which normally means its span is exported. The flag does not confirm the export. |
506
+ | `00` | The active span context is not sampled, so its span is normally not exported. The ids still match the request's log lines, and other spans on the same trace may be exported, including in this process. |
507
+
508
+ Want more than the trace context on an exemplar — an order id, a customer id, your own per-request id? Pass them as the third argument of `recordWithExemplar`, and they arrive as the exemplar's filtered attributes. The distribution adds none of its own.
509
+
510
+ ## Turning telemetry off at runtime
511
+
512
+ `setTelemetryEnabled` flips either pipeline while the process runs, with no deploy and no restart:
513
+
514
+ ```ts
515
+ import { setTelemetryEnabled } from '@sherlock-labs/node';
516
+
517
+ setTelemetryEnabled({ traces: false }); // stop new traces
518
+ setTelemetryEnabled({ traces: true, metrics: true }); // back on
519
+ ```
520
+
521
+ - **Traces off** stops *new* traces, including requests that arrive with a sampled `traceparent`. Spans with a local parent keep their parent's decision, so a request already being traced finishes whole in this process.
522
+ - **Metrics off** records no new exemplars and discards each export attempt. A discarded export also clears the buffered exemplars. Instruments still record values in memory: a discarded delta collection is not carried forward, so the chart shows a gap, and up/down counters keep their cumulative totals. If metrics come back on before an export is discarded, the next export includes the values recorded while off.
523
+ - **Neither switch** can start a pipeline that `start()` left off with `tracing: false` or `metrics: false`.
524
+
525
+ The distribution does not decide *when* to flip. Wire it to whatever you already have — a feature flag poll, a config watcher, an admin endpoint:
526
+
527
+ ```ts
528
+ setInterval(async () => {
529
+ const flags = await flagStore.read(['traces', 'metrics']);
530
+ setTelemetryEnabled({ traces: flags.traces, metrics: flags.metrics });
531
+ }, 10_000);
532
+ ```
533
+
534
+ ## Default instrumentation packages
535
+
536
+ The bundled instrumentations come from [`@opentelemetry/auto-instrumentations-node`](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/metapackages/auto-instrumentations-node), pinned to an exact version. That covers `http`, `express`, `koa`, `mongodb`, `mongoose`, `ioredis`, `redis`, `pg`, `mysql2`, `kafkajs`, `graphql`, `aws-sdk`, `pino`, `winston`, `bunyan`, `undici`, `dns`, `net`, and more. `register` installs all of them, minus the two the metapackage excludes by default (`fs` and `host-metrics`), plus one of this package's own: `fastify`, which names Fastify routes (see [Fastify](#fastify)).
537
+
538
+ The `instrumentations` option narrows that set. In an app that does not load `register`, it supplies the set instead. It takes three forms.
539
+
540
+ **`{ enabled: [...] }` — keep only these.**
541
+
542
+ ```ts
543
+ start({
544
+ accessToken,
545
+ serviceName: 'checkout-api',
546
+ // dns and net stay off: per-socket spans are a lot of spans.
547
+ instrumentations: { enabled: ['http', 'express', 'pg', 'ioredis', 'undici', 'runtime-node', 'pino'] },
548
+ });
549
+ ```
550
+
551
+ **`{ disabled: [...] }` — keep everything else.**
552
+
553
+ ```ts
554
+ start({
555
+ accessToken,
556
+ serviceName: 'checkout-api',
557
+ instrumentations: { disabled: ['dns', 'net'] },
558
+ });
559
+ ```
560
+
561
+ A name is the package suffix, exactly as in `OTEL_NODE_ENABLED_INSTRUMENTATIONS`: `"http"` means `@opentelemetry/instrumentation-http`. So the accepted names are `amqplib`, `aws-lambda`, `aws-sdk`, `bunyan`, `cassandra-driver`, `connect`, `cucumber`, `dataloader`, `dns`, `express`, `generic-pool`, `graphql`, `grpc`, `hapi`, `http`, `ioredis`, `kafkajs`, `knex`, `koa`, `lru-memoizer`, `memcached`, `mongodb`, `mongoose`, `mysql`, `mysql2`, `nestjs-core`, `net`, `openai`, `oracledb`, `pg`, `pino`, `redis`, `restify`, `router`, `runtime-node`, `socket.io`, `tedious`, `undici` and `winston`. `"fastify"` is the exception: it is this package's own instrumentation, not an upstream package. A name the bundle does not hold logs a warning, so a typo is loud rather than silent. Both keys may be given together: `enabled` narrows the bundle and `disabled` then subtracts from what is left.
562
+
563
+ The option outranks `OTEL_NODE_ENABLED_INSTRUMENTATIONS` and `OTEL_NODE_DISABLED_INSTRUMENTATIONS`. `register` defers the selection to the first `start()`, so code that runs after line 1 can still choose. A selection turns off the instrumentations it excludes for the rest of the process: a later `start()` cannot bring them back. In an ES module app, an excluded one that already patched something the app imports keeps recording: with `{ disabled: ['http'] }`, outgoing calls still get client spans. When you pass no option, those two variables decide, with the meaning they have upstream — that is the zero-code path, and it still works.
564
+
565
+ **`Instrumentation[]` — your own list, for an app that does not load `register`.**
566
+
567
+ ```ts
568
+ // No '@sherlock-labs/node/register' import anywhere in the process.
569
+ import { start } from '@sherlock-labs/node';
570
+ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
571
+ import { KoaInstrumentation } from '@opentelemetry/instrumentation-koa';
572
+
573
+ start({
574
+ accessToken,
575
+ serviceName: 'checkout-api',
576
+ instrumentations: [new HttpInstrumentation(), new KoaInstrumentation()],
577
+ });
578
+ ```
579
+
580
+ - **Build the list before anything loads the libraries in it.** OpenTelemetry patches a library as it loads, so one loaded earlier is not instrumented. In CommonJS, build it at the top of the entry file; `start()` can come later.
581
+ - **ES module apps use `register` with `{ enabled }` or `{ disabled }`.** Static imports load before any `start()` call, and only `register` installs the loader hook that instruments what an ES module imports.
582
+ - **Don't combine a list with `register`.** Both would instrument the same libraries, and OpenTelemetry cannot swap one copy for the other once a library has loaded: depending on load order, HTTP spans go missing or client spans are recorded twice. With `register`, narrow the bundle instead.
583
+ - **No auto-instrumentation at all:** drop the `register` import and pass `instrumentations: []`.
584
+
585
+ The filter cannot add an instrumentation the bundle lacks or change one's options. That needs a list, so for now it means CommonJS without `register`.
586
+
587
+ **The package always owns the HTTP hooks.** Four things ride on the http instrumentation: the guard that keeps the distribution from tracing and metering its own export requests, the ignored paths (`/healthz`, `/livez`, `/healthcheck`, plus your `ignorePaths`), and the two hooks that put exemplars on `http.server.request.duration` and `http.client.request.duration`. They stay attached in all three forms. `register` builds the bundle with them already in its config, and an explicit list gets them merged into its own `HttpInstrumentation` at `start()`. Your own `requestHook` and `responseHook` are kept and run first; your own ignore hooks are kept too, and a request is ignored when either yours or ours says so. A list with no http instrumentation loses all four, and says so at debug level.
588
+
589
+ More packages live in the [OpenTelemetry Registry](https://opentelemetry.io/registry/?language=js).
590
+
591
+ ## Exact version pins
592
+
593
+ Every direct OpenTelemetry dependency is pinned exactly — no `^`, no `~`. The packages they depend on keep their own ranges. The exemplar machinery reaches into SDK internals in a few places, so an upgrade is a deliberate change with its own verification, not a background bump.
594
+
595
+ That includes `@opentelemetry/instrumentation-http`, which is a **direct** dependency here even though the auto-instrumentation bundle would pull it in anyway. The bundle depends on it by range, and a published package ships no lockfile, so a consumer installing after the next release would get a newer instrumentation under attribute lists this package transcribes by hand . If that version changes those attributes, the HTTP exemplars can stop attaching. The drift guard then logs a throttled warning after two consecutive exports miss, when `OTEL_LOG_LEVEL` lets warnings through. Any instrumentation whose attributes we mirror has to be pinned directly, for the same reason.
596
+
597
+ Because the pins are exact, `@sherlock-labs/node` can install its own copy of an OpenTelemetry package next to yours. For the trace API there is nothing to keep in step — import `trace` and `context` from this package (see [Manual spans](#manual-spans)) and the two share one copy. If you depend on other OpenTelemetry packages directly, keep them on the versions listed in `package.json`.
598
+
599
+ ## What this changes versus plain OpenTelemetry
600
+
601
+ These tables compare this distribution with plain OpenTelemetry JS at the versions this package pins, in their default configuration. The linked sections explain each behaviour.
602
+
603
+ ### Setup
604
+
605
+ | Plain OpenTelemetry JS | This distribution | Why it matters |
606
+ |---|---|---|
607
+ | `NodeSDK` configures trace, metric and log exporters from the environment and its defaults. | The package builds [trace and metric providers](#who-starts-the-pipelines) explicitly. It creates no logger provider. | With default settings and pino instrumentation that forwards logs, `NodeSDK` sends log records to `http://localhost:4318/v1/logs`. |
608
+ | ES module apps add the import-in-the-middle loader themselves (`--experimental-loader=@opentelemetry/instrumentation/hook.mjs`). Without it, a CommonJS library an ES module imports, such as `ioredis`, is never patched. | [The ESM build of `register` installs the loader](#get-started), in include mode: it wraps only the modules an instrumentation asks for. | `node --import @sherlock-labs/node/register` is the whole ESM setup. A `register` that was not preloaded is reported by `start()`. |
609
+ | `NodeSDK` exports OTLP to `localhost` and needs no token. | [`start()` needs an endpoint, an access token and a service name](#configuration). It exports OTLP/HTTP JSON. | Each Sherlock tenant has its own ingest endpoint, so there is no default. Both exporters send the token as a bearer header. |
610
+ | `NodeSDK` detects environment, process and host resource attributes. | Only the environment detector runs. [`resourceAttributes`](#start-options) adds the rest. | Process and host attributes appear only when the app sets them. |
611
+ | `NodeSDK` honours `OTEL_SDK_DISABLED`, `OTEL_PROPAGATORS` and the exporter-selection variables. | The package reads [its own variables](#environment-variables) and always propagates W3C tracecontext and baggage. | Those `NodeSDK` variables have no effect here. |
612
+ | A malformed programmatic endpoint throws from the exporter constructor. | [`start()` never throws on its own errors](#who-starts-the-pipelines). A malformed endpoint leaves telemetry off with a warning. | Telemetry must never take the process down. |
613
+ | SDK diagnostics reach a logger as console-style arguments. | The [`logger`](#start-options) option receives one formatted string. A logger that throws falls back to the console. | pino takes an optional object, a message and placeholder values; it does not join other extra arguments. |
614
+
615
+ ### Lifecycle
616
+
617
+ | Plain OpenTelemetry JS | This distribution | Why it matters |
618
+ |---|---|---|
619
+ | The upstream `register` import creates and starts a `NodeSDK`, with no way to take over later. | [`./register` starts from the environment](#who-starts-the-pipelines). A later explicit `start()` with a token replaces that start. | An app that loads its token later keeps the options the environment cannot express. |
620
+ | `getNodeAutoInstrumentations()` reads the instrumentation variables when it runs. | `./register` defers that selection to the first `start()`, where the [`instrumentations` option](#default-instrumentation-packages) outranks the variables. | Code that runs after line 1 can still choose the instrumentations. |
621
+ | `NodeSDK` has no reversible switch for trace sampling and metric export. | [`setTelemetryEnabled()`](#turning-telemetry-off-at-runtime) turns new traces and metric export off and on at runtime. | An incident can need telemetry off without a redeploy. |
622
+ | The upstream `register` import flushes on `SIGTERM` and on normal exit. | The app calls [`stop()`](#who-starts-the-pipelines) to flush. | Await `stop()` during shutdown for a final flush. Without it, telemetry not yet exported can be lost. |
623
+
624
+ ### Traces and HTTP
625
+
626
+ | Plain OpenTelemetry JS | This distribution | Why it matters |
627
+ |---|---|---|
628
+ | A remote parent's sampled flag decides whether this service records the trace. | Spans with a remote parent use the configured [ratio](#start-options) and [runtime switch](#turning-telemetry-off-at-runtime). Local children follow their parent. | The caller's sampled flag does not decide, and the runtime switch always wins. A caller-chosen trace id can still steer the ratio. |
629
+ | Upstream suppresses spans around an export, but the HTTP instrumentation still records export requests in `http.client.request.duration`. | [The HTTP hooks skip every request to the ingest host and port](#start-options). | Export requests add no HTTP duration metrics. Every request to that host and port is skipped, whatever its path; other ports stay instrumented. |
630
+ | HTTP instrumentation has no default path exclusions. | Incoming HTTP instrumentation skips `/healthz`, `/livez` and `/healthcheck`, plus [`ignorePaths`](#start-options). | Health probes produce no auto-HTTP server spans or duration metrics. The adapters use their own `ignoreRequest`. |
631
+ | The HTTP duration histograms have no exemplars. | They carry exemplars for [sampled requests](#what-an-exemplar-carries). | The hooks rebuild the metric key from span attributes, and an unsampled span has none. |
632
+ | The HTTP histograms use the semantic-convention buckets. | They use the [same list plus six boundaries between 100 and 500 ms](#http-duration-buckets). | The extra boundaries give finer resolution between 100 and 500 ms. |
633
+ | `http.route` comes from route metadata, which framework instrumentation usually supplies. | The [Koa and Express adapters](#http-server-metrics) add `app.http.server.*` metrics with the framework's route. | The per-route view holds in metrics-only mode too. |
634
+
635
+ ### Metrics
636
+
637
+ | Plain OpenTelemetry JS | This distribution | Why it matters |
638
+ |---|---|---|
639
+ | The OTLP metric exporter prefers cumulative temporality. | The exporter prefers delta. Up/down counters stay cumulative, as the delta preference defines. | A delta collection dropped while [metrics are off](#turning-telemetry-off-at-runtime) is not carried forward. Up/down counters keep their totals. |
640
+ | `NodeSDK` exports metrics every 60 seconds. | The default interval is [30 seconds](#environment-variables). | Metric exports run twice as often. |
641
+ | Instruments from the global metrics API before provider registration stay no-ops forever. | [`define*` definitions](#custom-metrics-with-exemplars) resolve the real instrument on the first record after `start()`. | The no-op never upgrades and never reports an error. |
642
+ | `meter.createHistogram()` without options has an empty unit and buckets from 0 to 10000. | [A histogram's unit defaults to `s`](#histogram-boundaries), and the default buckets follow the unit. | The semantic conventions recommend seconds for duration metrics. |
643
+ | The metrics SDK exports no exemplars. | Custom histograms record exemplars through [`recordWithExemplar`](#what-an-exemplar-carries). | An exemplar links a histogram point to a trace or to application attributes. |
644
+
645
+ ### Packaging
646
+
647
+ | Plain OpenTelemetry JS | This distribution | Why it matters |
648
+ |---|---|---|
649
+ | Apps import `@opentelemetry/api` themselves. Copies share providers only when their versions are compatible. | The app imports `trace` and `context` from this package ([Manual spans](#manual-spans)). | The app then calls the exact API module the SDK registers its providers with. |
650
+ | The auto-instrumentation bundle depends on its instrumentations by version range. | [Direct OpenTelemetry dependencies are pinned exactly](#exact-version-pins). Transitive ranges remain. | The HTTP exemplar hooks mirror instrumentation attribute lists, so every upgrade needs a check. |
651
+
652
+ ## Migrating from plain OpenTelemetry JS
653
+
654
+ If you already run the OpenTelemetry Node SDK, the change is small.
655
+
656
+ 1. Replace `@opentelemetry/auto-instrumentations-node/register` (or your `NodeSDK` bootstrap) with `@sherlock-labs/node/register`: `node --import @sherlock-labs/node/register` for ES modules, line 1 of the entrypoint for CommonJS. Drop any `--experimental-loader=@opentelemetry/instrumentation/hook.mjs`; `register` installs that hook itself.
657
+ 2. Delete your exporter and provider setup. Set `SHERLOCK_ACCESS_TOKEN`, `SHERLOCK_ENDPOINT` and `OTEL_SERVICE_NAME`, or call `start()` with them.
658
+ 3. Replace module-scope `meter.createHistogram(...)` / `createCounter(...)` / `createGauge(...)` calls with `defineHistogram` / `defineCounter` / `defineGauge`, or with `defineMeter(name).histogram(...)` / `.counter(...)` / `.gauge(...)` where `metrics.getMeter(name)` set the scope. Call sites keep the same shape: `record(value, attrs)`, `add(value, attrs)`.
659
+ 4. Where you want chart-to-trace links, switch `record` to `recordWithExemplar` and pass the high-cardinality attributes as the third argument.
660
+
661
+ Standard OpenTelemetry env vars (`OTEL_SERVICE_NAME`, `OTEL_RESOURCE_ATTRIBUTES`, `OTEL_TRACES_SAMPLER_ARG`, `OTEL_LOG_LEVEL`) keep working. Spans you create with `@opentelemetry/api` keep working untouched — the distribution changes how telemetry leaves the process, not how you produce it. Switch those imports to `@sherlock-labs/node` (see [Manual spans](#manual-spans)) and you can drop the direct dependency.
662
+
663
+ ## Troubleshooting
664
+
665
+ **Nothing arrives at all.** Check the startup log line. The distribution stays off and says so when the access token, the service name or the endpoint is missing, or when the endpoint is not a valid http(s) URL. Raise `OTEL_LOG_LEVEL=debug` to see export failures (401, timeouts) instead of silence.
666
+
667
+ **Traces arrive, metrics do not.** Something is using the OpenTelemetry metrics API before `start()`. Metrics have no late binding: a meter grabbed early is a permanent no-op. Move the instrument behind `defineHistogram` / `defineCounter` / `defineGauge`.
668
+
669
+ **Some libraries are traced and others are not.** The untraced ones loaded before `@sherlock-labs/node/register`. In an ES module app, start it with `node --import @sherlock-labs/node/register`; a line-1 `import` is too late for ESM (look for the `register ran inside the app's ES module graph` warning). In CommonJS, confirm it is the very first `require` in the entrypoint, including anything a bundler may hoist above it.
670
+
671
+ **An ES module app with a bundler.** A bundle that inlines your dependencies leaves nothing for the loader hook to wrap: the libraries are no longer separate modules. Keep instrumented libraries external (esbuild `external`, tsup `external`, webpack `externals`) so Node loads them from `node_modules`.
672
+
673
+ **Exemplars are missing on some series.** An exemplar attaches to a data point by an exact match on metric name plus attributes. If they disagree, the exemplar silently disappears — the wire format has no error for this. The distribution ships a drift guard that logs a throttled warning when exemplars for a watched metric match no data point; that warning is the signal to look at. On the auto-instrumented HTTP histograms, also check your sample ratio: those exemplars are recorded for sampled requests only — see [What an exemplar carries](#what-an-exemplar-carries).
674
+
675
+ **`instrumentation-express`'s own `request handler - …` spans never arrive.** `cls-rtracer` patches `res.removeListener` positionally — it pops the most recently registered wrapped listener for that event name, whatever function you pass — while `@opentelemetry/instrumentation-express` calls `removeListener('close', …)` once per layer that calls `next()`, including layers that never registered one. Together they strip every `close` listener registered after `cls-rtracer`, and `instrumentation-express` ends its spans from one. This has to be fixed upstream, or by replacing `cls-rtracer` with a plain `AsyncLocalStorage` middleware. The `app.http.server.*` adapter metrics are not affected: the Express adapter records on `finish` or `close`, whichever fires first, and nothing removes `finish` listeners.
676
+
677
+ **Exemplars are missing everywhere on a low-traffic service.** Reservoirs are per bucket per export interval and are cleared on export. A service that serves a handful of requests per interval still gets exemplars; one that serves none in an interval exports no data points, and therefore no exemplars.
678
+
679
+ ## License
680
+
681
+ The Sherlock Distribution of OpenTelemetry for Node.js is a distribution of [OpenTelemetry JS](https://github.com/open-telemetry/opentelemetry-js). It is licensed under the terms of the Apache Software License version 2.0. See [the license file](./LICENSE) for details.