@softistx/telemetry 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +977 -2
  3. package/dist/attributes/attributes.d.ts +43 -0
  4. package/dist/attributes/attributes.d.ts.map +1 -0
  5. package/dist/context/current.d.ts +43 -0
  6. package/dist/context/current.d.ts.map +1 -0
  7. package/dist/export/console.d.ts +20 -0
  8. package/dist/export/console.d.ts.map +1 -0
  9. package/dist/export/exporter.d.ts +39 -0
  10. package/dist/export/exporter.d.ts.map +1 -0
  11. package/dist/export/file.d.ts +43 -0
  12. package/dist/export/file.d.ts.map +1 -0
  13. package/dist/export/json-lines.d.ts +17 -0
  14. package/dist/export/json-lines.d.ts.map +1 -0
  15. package/dist/export/memory.d.ts +30 -0
  16. package/dist/export/memory.d.ts.map +1 -0
  17. package/dist/export/pipeline.d.ts +71 -0
  18. package/dist/export/pipeline.d.ts.map +1 -0
  19. package/dist/export/rotation.d.ts +46 -0
  20. package/dist/export/rotation.d.ts.map +1 -0
  21. package/dist/index.d.ts +20 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +1162 -0
  24. package/dist/index.js.map +29 -0
  25. package/dist/logger/event.d.ts +15 -0
  26. package/dist/logger/event.d.ts.map +1 -0
  27. package/dist/logger/logger.d.ts +46 -0
  28. package/dist/logger/logger.d.ts.map +1 -0
  29. package/dist/logger/standard-schema.d.ts +32 -0
  30. package/dist/logger/standard-schema.d.ts.map +1 -0
  31. package/dist/model/error.d.ts +21 -0
  32. package/dist/model/error.d.ts.map +1 -0
  33. package/dist/model/signal.d.ts +90 -0
  34. package/dist/model/signal.d.ts.map +1 -0
  35. package/dist/span/begin.d.ts +17 -0
  36. package/dist/span/begin.d.ts.map +1 -0
  37. package/dist/span/handle.d.ts +40 -0
  38. package/dist/span/handle.d.ts.map +1 -0
  39. package/dist/span/scope.d.ts +71 -0
  40. package/dist/span/scope.d.ts.map +1 -0
  41. package/dist/span/span.d.ts +15 -0
  42. package/dist/span/span.d.ts.map +1 -0
  43. package/dist/span/sync.d.ts +5 -0
  44. package/dist/span/sync.d.ts.map +1 -0
  45. package/dist/telemetry/telemetry.d.ts +89 -0
  46. package/dist/telemetry/telemetry.d.ts.map +1 -0
  47. package/dist/trace/ids.d.ts +60 -0
  48. package/dist/trace/ids.d.ts.map +1 -0
  49. package/dist/trace/sampler.d.ts +31 -0
  50. package/dist/trace/sampler.d.ts.map +1 -0
  51. package/package.json +57 -5
package/README.md CHANGED
@@ -1,3 +1,978 @@
1
- # Temporary Holding Version
1
+ # @softistx/telemetry
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
+ Logs and traces for a TypeScript service, with no OpenTelemetry SDK.
4
+
5
+ ```sh
6
+ bun add @softistx/telemetry
7
+ ```
8
+
9
+ Zero runtime dependencies. Bun and Node; a browser gets everything but the
10
+ automatic context.
11
+
12
+ ## What it is
13
+
14
+ A span is a block you `await`, and the current one travels with your work —
15
+ through every `await`, every timer, every promise — in an `AsyncLocalStorage`.
16
+ Logs written inside it carry its `traceId` and `spanId` without being told. A
17
+ `traceparent` header is read on the way in and written on the way out, so the
18
+ trace continues across services. Signals are handed to a pipeline that never
19
+ blocks the caller and never throws at it, and exporters ship them: the console,
20
+ a file, [OTLP](https://www.npmjs.com/package/@softistx/telemetry-otlp), MongoDB.
21
+
22
+ It is the TypeScript counterpart of `stx-telemetry` on the JVM, and shares its
23
+ vocabulary exactly: the same severities, span kinds, statuses, `traceparent`
24
+ rules, sampling rule and attribute names. A trace started in one and continued
25
+ in the other is one trace.
26
+
27
+ ## Usage
28
+
29
+ The whole life of a service, in the order you write it. Each step links to the
30
+ section that explains it.
31
+
32
+ **1. Install one telemetry at startup**, before anything logs.
33
+ [The root](#the-root)
34
+
35
+ ```ts
36
+ // telemetry.ts
37
+ import { consoleExporter, createTelemetry } from '@softistx/telemetry';
38
+
39
+ export const telemetry = createTelemetry('checkout', {
40
+ version: '1.4.0',
41
+ environment: 'production',
42
+ exporters: [consoleExporter()],
43
+ }).install();
44
+ ```
45
+
46
+ **2. Give each part of the code a logger.** A logger is cheap and has no
47
+ state; create it at module level. [Logging](#logging)
48
+
49
+ ```ts
50
+ import { createLogger } from '@softistx/telemetry';
51
+
52
+ const log = createLogger('CheckoutService');
53
+
54
+ log.info('checkout started', { cartSize: 3 });
55
+ ```
56
+
57
+ **3. Declare the events that matter**, so a log line carries only the fields
58
+ you chose. [Declared event](#declared-event)
59
+
60
+ ```ts
61
+ import { event } from '@softistx/telemetry';
62
+ import { z } from 'zod';
63
+
64
+ const Charged = event('checkout.charged', z.object({ orderId: z.string(), amount: z.number() }));
65
+
66
+ log.info(Charged({ orderId: 'o-1', amount: 42 }));
67
+ ```
68
+
69
+ **4. Wrap units of work in spans.** Everything inside a span, logs included,
70
+ carries its `traceId`. [Spans](#spans)
71
+
72
+ ```ts
73
+ import { span } from '@softistx/telemetry';
74
+
75
+ export async function checkout(orderId: string) {
76
+ return span('checkout', { attributes: { orderId } }, async (scope) => {
77
+ const order = await span('order.load', () => orders.find(orderId));
78
+ scope.attribute('order.total', order.total);
79
+ await span('payment.charge', { kind: 'client' }, () => payments.charge(order));
80
+ log.info(Charged({ orderId, amount: order.total })); // carries the trace
81
+ return order;
82
+ });
83
+ }
84
+ ```
85
+
86
+ **5. Carry the trace across services.** Continue the caller's `traceparent` on
87
+ the way in and send the current one on the way out.
88
+ [Propagation](#propagation-and-traceparent)
89
+
90
+ ```ts
91
+ import { continuing, currentTraceparent } from '@softistx/telemetry';
92
+
93
+ // in: an HTTP handler
94
+ await continuing(request.headers.get('traceparent'), 'POST /checkout', { kind: 'server' }, () =>
95
+ checkout(orderId),
96
+ );
97
+
98
+ // out: an HTTP call made inside a span
99
+ await fetch('https://stock.internal/reserve', {
100
+ method: 'POST',
101
+ headers: { traceparent: currentTraceparent() ?? '' },
102
+ });
103
+ ```
104
+
105
+ With Hono and httpyz, the two integrations do both halves for you:
106
+ [`@softistx/telemetry-hono`](https://npm.softistx.com/-/web/detail/@softistx/telemetry-hono)
107
+ and [`@softistx/telemetry-httpyz`](https://npm.softistx.com/-/web/detail/@softistx/telemetry-httpyz).
108
+
109
+ **6. Put request-wide facts in scope once**, instead of passing them to every
110
+ log call. [Context](#context)
111
+
112
+ ```ts
113
+ import { withAttributes } from '@softistx/telemetry';
114
+
115
+ await withAttributes({ tenant: 'acme' }, () => checkout(orderId));
116
+ ```
117
+
118
+ **7. Ship the signals somewhere.** Swap the console for a collector, a file or
119
+ MongoDB. The code from steps 2 to 6 does not change. [Exporters](#exporters)
120
+
121
+ ```ts
122
+ import { otlpExporter } from '@softistx/telemetry-otlp';
123
+
124
+ createTelemetry('checkout', {
125
+ sampler: ratioSampler(0.1), // keep one trace in ten; logs are never sampled
126
+ exporters: [otlpExporter({ endpoint: 'http://localhost:4318' })],
127
+ }).install();
128
+ ```
129
+
130
+ **8. Close it on shutdown, and await it**, or the last batch is lost.
131
+ [The root](#the-root)
132
+
133
+ ```ts
134
+ process.on('SIGTERM', async () => {
135
+ await telemetry.close();
136
+ process.exit(0);
137
+ });
138
+ ```
139
+
140
+ **In a test**, give each suite its own telemetry and an exporter that keeps
141
+ what it receives, instead of installing one globally.
142
+ [Context](#context)
143
+
144
+ ```ts
145
+ import type { Exporter, Signal } from '@softistx/telemetry';
146
+ import { createTelemetry, withTelemetry } from '@softistx/telemetry';
147
+
148
+ const received: Signal[] = [];
149
+ const collect: Exporter = { export: (_resource, batch) => void received.push(...batch) };
150
+ const telemetry = createTelemetry('test', { exporters: [collect] });
151
+
152
+ await withTelemetry(telemetry, () => checkout('o-1'));
153
+ await telemetry.close(); // flushes: `received` now holds the spans and logs
154
+ ```
155
+
156
+ ## Concepts
157
+
158
+ Every word this library uses, once, with the smallest example that shows it.
159
+ The sections after this one go deeper; this is the glossary to come back to.
160
+
161
+ ### Telemetry
162
+
163
+ The root object: one per service. It knows **who** is speaking (the resource),
164
+ **how much** to keep (the sampler, the minimum severity) and **where** signals go
165
+ (the exporters). Everything else — spans, loggers — finds it through the context,
166
+ or falls back to the one `install()`ed.
167
+
168
+ ```ts
169
+ const telemetry = createTelemetry('checkout', {
170
+ exporters: [consoleExporter()],
171
+ }).install();
172
+
173
+ await telemetry.close(); // ships what is left; must be awaited
174
+ ```
175
+
176
+ ### Resource
177
+
178
+ What every signal from one telemetry is about: the service, its version, its
179
+ environment, and any attributes you add. It is stamped once, not repeated by
180
+ each call site.
181
+
182
+ ```ts
183
+ createTelemetry('checkout', {
184
+ version: '1.4.0',
185
+ environment: 'production',
186
+ attributes: { 'deployment.region': 'eu-west-1' },
187
+ });
188
+ // telemetry.resource
189
+ // → { service: 'checkout', version: '1.4.0', environment: 'production',
190
+ // attributes: { 'deployment.region': 'eu-west-1' } }
191
+ ```
192
+
193
+ ### Signal
194
+
195
+ The unit an exporter receives. There are two kinds, told apart by `type`: a
196
+ **log record** and a **span record**. Metrics would be a third kind; nothing
197
+ else would have to change.
198
+
199
+ ```ts
200
+ function describe(signal: Signal): string {
201
+ return signal.type === 'log'
202
+ ? `${signal.severity} ${signal.name}`
203
+ : `${signal.name} took ${signal.endedAt - signal.startedAt} ms`;
204
+ }
205
+ ```
206
+
207
+ ### Trace
208
+
209
+ All the work done for one request, across every service it touched. It has no
210
+ object of its own: it is every span that shares one **trace id**.
211
+
212
+ ```ts
213
+ await span('GET /orders/:id', { kind: 'server' }, async () => {
214
+ await span('load order', {}, async () => { /* … */ });
215
+ await span('price order', {}, async () => { /* … */ });
216
+ });
217
+ // three spans, one traceId: that is the trace
218
+ ```
219
+
220
+ ### Span
221
+
222
+ One timed piece of work inside a trace: a name, a start, an end, a status, and
223
+ the span it happened inside (its **parent**). A span is a block you `await`, and
224
+ the block's lifetime *is* the span's.
225
+
226
+ ```ts
227
+ const total = await span('price order', { attributes: { orderId } }, async (scope) => {
228
+ scope.attribute('items', order.items.length);
229
+ return computeTotal(order);
230
+ });
231
+ ```
232
+
233
+ A span with no parent is a **root span**. The block's return value comes back
234
+ out; a thrown error goes back out too, after being recorded.
235
+
236
+ ### Span scope
237
+
238
+ What the block receives: the handle on the span that is open. Through it you
239
+ name the span, add attributes and events, set or read the status, or record a
240
+ failure you caught and chose not to rethrow.
241
+
242
+ ```ts
243
+ await span('charge', {}, async (scope) => {
244
+ scope.name = `charge ${provider}`; // renamed once the provider is known
245
+ scope.event('gateway.called', { attempt: 1 });
246
+ try {
247
+ await gateway.charge(card);
248
+ } catch (failure) {
249
+ scope.fail(failure); // status → error, exception recorded
250
+ await queue.retryLater(card); // …and handled, not rethrown
251
+ }
252
+ });
253
+ ```
254
+
255
+ ### Span kind
256
+
257
+ What role the span played: `internal` (the default), `server` (it answered a
258
+ request), `client` (it made one), `producer` and `consumer` (it sent or received
259
+ a message). A backend draws the arrows between services from `server` and
260
+ `client`.
261
+
262
+ ```ts
263
+ await span('GET /orders/:id', { kind: 'server' }, handle);
264
+ await span('GET inventory', { kind: 'client' }, () => fetch(url));
265
+ ```
266
+
267
+ ### Span status
268
+
269
+ How the work ended: `ok`, `error`, or `cancelled`. A thrown error makes it
270
+ `error`; an `AbortError` or `TimeoutError` makes it `cancelled`, because a
271
+ shutdown or a timeout is not a bug somebody should be paged for.
272
+
273
+ ```ts
274
+ await span('import', {}, async () => {
275
+ throw new Error('bad row'); // status: 'error', rethrown
276
+ }).catch(() => {});
277
+
278
+ await span('poll', {}, async () => {
279
+ await fetch(url, { signal: AbortSignal.timeout(10) }); // status: 'cancelled'
280
+ }).catch(() => {});
281
+ ```
282
+
283
+ ### Span event
284
+
285
+ Something that happened at an instant during a span, with its own attributes —
286
+ a retry, a cache miss, a state change. Cheaper than a child span, and attached
287
+ to the work it describes.
288
+
289
+ ```ts
290
+ await span('charge', {}, async (scope) => {
291
+ scope.event('retry', { attempt: 2, reason: 'timeout' });
292
+ });
293
+ ```
294
+
295
+ ### Span context
296
+
297
+ A span's place in a trace, as it travels: the trace id, the span id, whether the
298
+ trace is **sampled**, and whether it arrived from another process (**remote**).
299
+ It is what a `traceparent` header carries, and what a log attaches.
300
+
301
+ ```ts
302
+ currentSpan();
303
+ // → { traceId: '4bf92f35…0e4736', spanId: '00f067aa0ba902b7', sampled: true, remote: false }
304
+ ```
305
+
306
+ Ids are lowercase hex — 32 characters for a trace, 16 for a span — and typed as
307
+ `TraceId` and `SpanId`, so the compiler refuses one where the other belongs.
308
+
309
+ ### Detached context
310
+
311
+ What a span carries when **no telemetry is installed**: all-zero ids, not
312
+ sampled. The block runs, nothing is emitted. It is what lets a library use
313
+ `span()` inside an application that has never heard of this package.
314
+
315
+ ```ts
316
+ await span('work', {}, async (scope) => {
317
+ isDetached(scope.context); // true when nothing is installed
318
+ });
319
+ ```
320
+
321
+ ### Propagation and `traceparent`
322
+
323
+ How a trace crosses a process boundary: the caller writes its span context into
324
+ a W3C `traceparent` header, and the callee **continues** the trace from it
325
+ instead of starting a new one.
326
+
327
+ ```ts
328
+ // the caller
329
+ await fetch(url, { headers: { traceparent: currentTraceparent() ?? '' } });
330
+
331
+ // the callee
332
+ await continuing(request.headers.get('traceparent'), 'GET /orders', async () => {
333
+ // same traceId as the caller; this span's parent is the caller's span
334
+ });
335
+ ```
336
+
337
+ `@softistx/telemetry-httpyz` and `@softistx/telemetry-hono` do both halves for you.
338
+
339
+ ### Context
340
+
341
+ Where the current span, the current telemetry and the inherited attributes
342
+ live, so that nothing has to be passed by hand. It is an `AsyncLocalStorage`:
343
+ it follows your work through every `await`, timer and promise, and two
344
+ concurrent requests never see each other's.
345
+
346
+ ```ts
347
+ await span('request', {}, async () => {
348
+ await Promise.all([a(), b()]); // both see 'request' as their current span
349
+ });
350
+ currentSpan(); // undefined: out here, nothing is open
351
+ ```
352
+
353
+ ### Attributes
354
+
355
+ Key–value pairs describing a signal, where a value is a **scalar or a list of
356
+ scalars** — what a backend can filter and group by. Names follow OpenTelemetry's
357
+ conventions where one exists (`http.route`, `db.system.name`).
358
+
359
+ ```ts
360
+ span('charge', { attributes: { orderId: 'o-1', amount: 4200, retried: false } }, block);
361
+ ```
362
+
363
+ ### Attribute inheritance
364
+
365
+ Attributes given to `span()` or `withAttributes()` are **inherited** by every log
366
+ and span inside the block. Those set with `scope.attribute()` belong to that one
367
+ span. When two names clash, the inner one wins.
368
+
369
+ ```ts
370
+ await withAttributes({ tenant: 'acme' }, async () => {
371
+ await span('charge', { attributes: { orderId: 'o-1' } }, async (scope) => {
372
+ scope.attribute('provider', 'stripe'); // this span only
373
+ log.info('charged'); // carries tenant and orderId
374
+ });
375
+ });
376
+ ```
377
+
378
+ ### Logger and source
379
+
380
+ A logger is named for the component that writes through it — its **source** —
381
+ and every record it produces carries that name. Loggers are cheap and can be
382
+ created at module level: they find the telemetry when they write, not when they
383
+ are made.
384
+
385
+ ```ts
386
+ const log = createLogger('CheckoutService');
387
+ log.info('order stored', { orderId });
388
+ ```
389
+
390
+ ### Severity
391
+
392
+ How much a log matters: `debug`, `info`, `warn`, `error`. There is no `trace`.
393
+ The telemetry's **minimum** is the floor: below it a log is never built.
394
+
395
+ ```ts
396
+ createTelemetry('checkout', { minimum: 'warn' });
397
+ log.info('ignored'); // below the floor: not built, not emitted
398
+ log.warn('kept');
399
+ ```
400
+
401
+ ### Log record
402
+
403
+ What a log call produces: when, how severe, a name, the source, attributes, the
404
+ span it was written in (if any) and the failure it is about (if any).
405
+
406
+ ```ts
407
+ log.error('charge failed', new Error('card refused'), { orderId: 'o-1' });
408
+ // → { type: 'log', severity: 'error', name: 'charge failed',
409
+ // source: 'CheckoutService', attributes: { orderId: 'o-1' },
410
+ // span: { traceId, spanId, … }, error: { type: 'Error', message: 'card refused', stackTrace } }
411
+ ```
412
+
413
+ ### Declared event
414
+
415
+ A log whose fields are **declared by a schema**, so only what the schema names
416
+ is written. It is how a log stops leaking the field someone adds to an object
417
+ next quarter.
418
+
419
+ ```ts
420
+ const Charged = event('checkout.charged', z.object({ orderId: z.string(), amount: z.number() }));
421
+
422
+ log.info(Charged({ orderId: 'o-1', amount: 4200, card: '4242…' }));
423
+ // → name 'checkout.charged', attributes { orderId: 'o-1', amount: 4200 } — no card
424
+ ```
425
+
426
+ Any [Standard Schema](https://standardschema.dev) works. A value the schema
427
+ refuses is still logged, marked `telemetry.event.invalid`, never thrown.
428
+
429
+ ### Error info
430
+
431
+ A failure flattened into something that can cross a wire: its type (the class
432
+ name), its message, and its stack as text. Logs and spans carry it the same way,
433
+ and OTLP turns it into `exception.type`, `exception.message` and
434
+ `exception.stacktrace`.
435
+
436
+ ```ts
437
+ class ChargeRefused extends Error {}
438
+ errorInfo(new ChargeRefused('insufficient funds'));
439
+ // → { type: 'ChargeRefused', message: 'insufficient funds', stackTrace: '…' }
440
+ ```
441
+
442
+ ### Sampler and sampling
443
+
444
+ The decision to **keep a trace or not**, taken once by the root span and carried
445
+ by every child and every `traceparent`. It is a function of the trace id, so two
446
+ services at the same ratio agree. Logs are never sampled.
447
+
448
+ ```ts
449
+ createTelemetry('checkout', { sampler: ratioSampler(0.1) }); // keep a tenth of traces
450
+
451
+ const custom: Sampler = { sample: (traceId) => traceId.endsWith('0') };
452
+ ```
453
+
454
+ ### Exporter
455
+
456
+ Where signals go: one object with `export(resource, batch)` and an optional
457
+ `close()`. It is called by one consumer at a time, in order, and a failure in it
458
+ never reaches the code that wrote the signal.
459
+
460
+ ```ts
461
+ const counting: Exporter = {
462
+ export(resource, batch) {
463
+ console.log(`${resource.service}: ${batch.length} signals`);
464
+ },
465
+ };
466
+ createTelemetry('checkout', { exporters: [counting, consoleExporter()] });
467
+ ```
468
+
469
+ Built in: `consoleExporter`, `jsonLinesExporter`, `fileExporter`. Elsewhere:
470
+ `otlpExporter` (`@softistx/telemetry-otlp`), `mongoExporter`
471
+ (`@softistx/telemetry-mongo`), `winstonExporter` (`@softistx/telemetry-logging`).
472
+
473
+ ### Pipeline and batch
474
+
475
+ Between the code that writes a signal and the exporters: a queue that **never
476
+ blocks and never throws** at the writer. Signals are grouped into a **batch**,
477
+ flushed when `batch` signals are waiting or `linger` ms after the first one, and
478
+ drained by `close()`.
479
+
480
+ ```ts
481
+ createTelemetry('checkout', {
482
+ batch: 512, // flush at this many
483
+ linger: 1_000, // …or this long after the first
484
+ drainTimeout: 10_000,
485
+ onExportError: (failure) => console.error('export failed', failure),
486
+ exporters: [otlpExporter({ endpoint })],
487
+ });
488
+ ```
489
+
490
+ ## The root
491
+
492
+ ```ts
493
+ import { createTelemetry, consoleExporter, ratioSampler } from '@softistx/telemetry';
494
+
495
+ const telemetry = createTelemetry('checkout', {
496
+ version: '1.4.0',
497
+ environment: 'production',
498
+ sampler: ratioSampler(0.1),
499
+ exporters: [consoleExporter()],
500
+ }).install();
501
+
502
+ process.on('SIGTERM', async () => {
503
+ await telemetry.close();
504
+ process.exit(0);
505
+ });
506
+ ```
507
+
508
+ `service` has no default: it is the key everything groups by, and a service
509
+ called `unknown` is a dashboard nobody can read. `install()` makes this the
510
+ telemetry a logger or a span finds when there is none in scope, and returns the
511
+ instance.
512
+
513
+ **`close()` must be awaited.** JavaScript cannot block, so unlike its JVM
514
+ counterpart this one returns a promise: a process that exits without waiting
515
+ loses its last batch, which is the batch that explains the shutdown. Handing the
516
+ promise to a listener that discards it is the same mistake in a smaller
517
+ disguise — the handler above awaits it before exiting. `await using` works too.
518
+
519
+ `drainTimeout` bounds **the whole close**, the exporters' own `close` included,
520
+ so neither a collector that stopped answering nor an exporter that will not let
521
+ go of its socket becomes the reason a process will not exit. A drain that runs
522
+ out of time is reported to `onExportError`, and is the one case where an
523
+ exporter's `close` may be called while an `export` is still in flight.
524
+
525
+ | option | default | |
526
+ | --- | --- | --- |
527
+ | `version`, `environment`, `attributes` | — | stamped on the resource, so every signal carries them |
528
+ | `sampler` | `alwaysSample` | asked once, for a root span |
529
+ | `minimum` | `'info'` | logs below this are never built. Spans are unaffected |
530
+ | `stackTraces` | `true` | whether a recorded failure carries its stack |
531
+ | `batch` | `512` | flush once this many signals are waiting |
532
+ | `linger` | `1000` ms | flush this long after the first signal of a batch |
533
+ | `drainTimeout` | `10000` ms | how long `close` waits for the backlog |
534
+ | `onExportError` | `console.error` | a failing exporter is reported here |
535
+ | `exporters` | `[]` | in order; a batch reaches them one after the other |
536
+
537
+ ## Spans
538
+
539
+ ```ts
540
+ import { span, continuing } from '@softistx/telemetry';
541
+
542
+ await span('charge', { attributes: { orderId } }, async (scope) => {
543
+ scope.event('gateway.called', { attempt });
544
+ await payments.charge(card);
545
+ });
546
+
547
+ // on the way in, continuing whatever the caller started
548
+ await continuing(request.headers.get('traceparent'), 'GET /orders', async (scope) => {
549
+ scope.name = `GET ${route}`; // routing knows the template last
550
+ scope.attribute('http.route', route);
551
+ });
552
+ ```
553
+
554
+ The block runs whether or not a telemetry is installed: a library that traces
555
+ must work inside an application that has never heard of this one. With none, the
556
+ scope carries a detached context and nothing is emitted.
557
+
558
+ **A span never swallows.** A failure marks it `error` — or `cancelled`, for an
559
+ `AbortError` or a `TimeoutError`, because a shutdown and a timeout are not
560
+ failures — records the exception, and rethrows. A span observes; it does not
561
+ handle.
562
+
563
+ Attributes given to `span()` are inherited by every log and span inside it;
564
+ `scope.attribute()` belongs to that span alone. Both appear on the span's own
565
+ record.
566
+
567
+ `continuing` takes a header from a stranger, so an unusable one is not an error:
568
+ it starts a fresh trace, exactly as `span` would.
569
+
570
+ **`continuing` against an ambient span: the header wins.** Inside a `span`, a
571
+ usable `traceparent` still makes the new span a child of the *caller's* span, in
572
+ the caller's trace; the ambient span is only the parent when the header is
573
+ absent or unusable.
574
+
575
+ ### A span that outlives its block: `startSpan`
576
+
577
+ A subscription, an `@defer` stream or a WebSocket operation ends long after the
578
+ function that started it returned. `startSpan` hands back a handle:
579
+
580
+ ```ts
581
+ import { startSpan } from '@softistx/telemetry';
582
+
583
+ const operation = startSpan('graphql.subscription', {
584
+ traceparent: request.headers.get('traceparent'), // optional; null is fine
585
+ attributes: { 'graphql.operation.name': name },
586
+ });
587
+
588
+ // `subscribe`, `send` and `signal` stand for your own GraphQL, transport and abort code
589
+ // code that should see the span as its parent runs through `run`
590
+ const source = operation.run(() => subscribe(schema, document));
591
+
592
+ signal.addEventListener('abort', () => operation.end());
593
+ for await (const item of source) send(item);
594
+ operation.end(); // idempotent: the first call wins
595
+ ```
596
+
597
+ Nothing is emitted until `end()`, and a handle that is never ended emits
598
+ nothing, so end it from every path that finishes the work. `end()` never throws
599
+ and, like `span`, a detached handle (no telemetry installed) is a no-op. The
600
+ handle is a `SpanScope`, so `attribute`, `event`, `fail` and `status` work on it;
601
+ `fail` keeps the **first** failure, so call it for the failure the span is about.
602
+ `run(fn)` makes the span current for `fn` (and everything `fn` starts), returns
603
+ what `fn` returns and lets what it throws through.
604
+
605
+ ### A span around a plain function: `spanSync`
606
+
607
+ ```ts
608
+ import { spanSync } from '@softistx/telemetry';
609
+
610
+ // `info` is a GraphQL resolver's info argument, `parent` the object being resolved
611
+ const resolve = (parent, args, ctx, info) =>
612
+ spanSync(`${info.parentType.name}.${info.fieldName}`, { attributes: { field: info.fieldName } }, () =>
613
+ parent[info.fieldName]);
614
+ ```
615
+
616
+ The result comes back **as it is**: a synchronous block stays synchronous, so a
617
+ per-field resolver does not become async. A block that returns a promise (any
618
+ thenable) keeps the span open until it settles; a throw or a rejection marks the
619
+ span `error` and is rethrown as it arrived.
620
+
621
+ ## Logging
622
+
623
+ ```ts
624
+ import { createLogger, event } from '@softistx/telemetry';
625
+ import { z } from 'zod';
626
+
627
+ const Charged = event('checkout.charged', z.object({ orderId: z.string(), amount: z.number() }));
628
+ const log = createLogger('CheckoutService');
629
+
630
+ log.info(Charged({ orderId, amount })); // a declared event
631
+ log.warn('charge refused', { orderId, code }); // ad hoc, for what has no type yet
632
+ log.debug(() => `state: ${expensive()}`); // built only if debug is on
633
+ log.error('charge failed', failure, { orderId });
634
+ ```
635
+
636
+ A line written inside a span carries that span's `traceId` and `spanId` without
637
+ being told, and the attributes the span and `withAttributes` put in scope.
638
+
639
+ **Declaring an event is the point.** Logging an object as it is logs the field
640
+ added next quarter — the card number included — and nobody finds out, because a
641
+ log that says too much still looks like a working log. The schema is the
642
+ declaration, and what it returns is what is emitted: an object schema's unknown
643
+ keys are gone. Any [Standard Schema](https://standardschema.dev) will do — Zod,
644
+ Valibot, ArkType — and none of them is a dependency here.
645
+
646
+ **Nothing on this path can fail.** No telemetry installed, a schema that refuses
647
+ the input, a schema that answers asynchronously, a lazy message that throws: the
648
+ line still comes out, marked, or is dropped in silence. `log.info` is a total,
649
+ synchronous function, callable from a constructor or from a `catch`.
650
+
651
+ The lazy form is `debug` and `info` only, and the failure form is `warn` and
652
+ `error` only — at those levels a message is always built, so a thunk would hide
653
+ only the cost of building it.
654
+
655
+ ## Context
656
+
657
+ ```ts
658
+ import { currentSpan, currentTraceparent, withAttributes, withTelemetry } from '@softistx/telemetry';
659
+
660
+ await withAttributes({ tenant: 'acme' }, async () => {
661
+ // every log and span in here carries tenant=acme
662
+ await fetch(url, { headers: { traceparent: currentTraceparent() ?? '' } });
663
+ });
664
+ ```
665
+
666
+ The current span lives in an `AsyncLocalStorage`, and that is the whole design.
667
+ It propagates through every `await`, every timer and every promise chain: into
668
+ everything started inside a span, out of nothing, and correct after any number
669
+ of suspensions. A module-level variable would look right in development and
670
+ start attributing one request's spans to another under concurrency — a bug with
671
+ no stack trace and no failing test, in the tool meant to make such bugs visible.
672
+
673
+ It is also readable **synchronously**, which is what lets `log.info()` stay a
674
+ plain function: a log written from a constructor, from a `catch` in ordinary
675
+ code or from a callback still has to come out.
676
+
677
+ `withTelemetry(telemetry, fn)` puts a different one in scope for the block.
678
+ Scope wins over the installed default, which is what lets two suites in one
679
+ process each collect their own signals.
680
+
681
+ ## Exporters
682
+
683
+ An exporter is one function:
684
+
685
+ ```ts
686
+ import type { Exporter } from '@softistx/telemetry';
687
+
688
+ const exporter: Exporter = {
689
+ export(resource, batch) { /* … */ },
690
+ async close() { /* optional */ },
691
+ };
692
+ ```
693
+
694
+ The pipeline guarantees it is called from **one consumer, never concurrently**,
695
+ so there is nothing to synchronise and a batch's order is the order things
696
+ happened in. It may take as long as it wants; nothing that writes a signal is
697
+ waiting on it. If it throws, the failure goes to `onExportError` and the next
698
+ exporter still receives the batch — a collector being down is not a reason for
699
+ a request to fail.
700
+
701
+ ### In tests: `memoryExporter`
702
+
703
+ ```ts
704
+ import { createTelemetry, memoryExporter, span, withTelemetry } from '@softistx/telemetry';
705
+
706
+ const memory = memoryExporter();
707
+ const telemetry = createTelemetry('checkout', { exporters: [memory] });
708
+
709
+ await withTelemetry(telemetry, () => span('charge', async () => {}));
710
+ await telemetry.flush(); // ship the backlog, without closing
711
+
712
+ expect(memory.spans.map((s) => s.name)).toEqual(['charge']);
713
+ memory.clear();
714
+ ```
715
+
716
+ `spans` and `logs` are live arrays in arrival order. Signals reach the exporter
717
+ through the pipeline, so `await telemetry.flush()` (or `close()`) before reading.
718
+
719
+ ### The ones built in
720
+
721
+ ```ts
722
+ import { consoleExporter, jsonLinesExporter, fileExporter } from '@softistx/telemetry';
723
+
724
+ consoleExporter() // one readable line per signal
725
+ jsonLinesExporter() // one JSON object per line, on stdout
726
+ fileExporter({ path: 'logs/telemetry.jsonl' }) // the same, appended, with rotation
727
+ ```
728
+
729
+ `fileExporter` **appends**: a restart continues the current file, and the period
730
+ is read from that file's modification time rather than from when the process
731
+ started, so a service that restarts hourly still rolls once a day. Rotation is
732
+ epoch-aligned — `every: 24h` rolls at UTC midnight, not 24 hours after a
733
+ restart — and an **empty file is never rolled**, so an idle service does not
734
+ accumulate a directory of empty archives. `close()` rolls nothing: a rolled file
735
+ is a finished period, and a shutdown is not one.
736
+
737
+ | option | default | |
738
+ | --- | --- | --- |
739
+ | `path` | — | the file. Its directory is created if it is missing |
740
+ | `maxSize` | `64 MiB` | roll at this size. `0` disables it |
741
+ | `every` | `24h` | roll when this period changes, in ms. `0` disables it |
742
+ | `keep` | `7` | how many rolled files to keep |
743
+ | `compress` | `false` | gzip a rolled file |
744
+
745
+ **This exporter owns its path.** It is the one stateful exporter here — it
746
+ remembers the file's size and age instead of asking the filesystem on every
747
+ batch — so give each path exactly one `fileExporter`. Concurrent batches are
748
+ serialised internally, and any failure throws away what it remembered, so an
749
+ external `logrotate`, a truncation or a full disk costs the batch it happened on
750
+ and nothing after it.
751
+
752
+ Neither line format carries the resource: a file belongs to one service, so
753
+ repeating its name on every line would be noise. An exporter that writes
754
+ somewhere shared — `@softistx/telemetry-mongo` — stamps it instead.
755
+
756
+ `@softistx/telemetry-otlp` and `@softistx/telemetry-mongo` are the others.
757
+
758
+ ## Trace identity
759
+
760
+ ```ts
761
+ import { randomTraceId, parseTraceparent, renderTraceparent } from '@softistx/telemetry';
762
+
763
+ const incoming = parseTraceparent(request.headers.get('traceparent'));
764
+ // → { traceId, spanId, sampled, remote: true }, or null
765
+
766
+ renderTraceparent({ traceId, spanId, sampled: true, remote: false });
767
+ // → '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'
768
+ ```
769
+
770
+ `parseTraceparent` **returns `null` and never throws.** A header a stranger
771
+ controls must not be able to fail a request: an unusable one simply starts a
772
+ fresh trace. It rejects fewer than four fields, a version that is not two hex
773
+ characters, the forbidden version `ff`, an id of the wrong length or all zeros
774
+ or not hex, and flags that are not hex. A later version is accepted and its
775
+ extra fields ignored. `tracestate` is not read, and nothing here writes one.
776
+
777
+ `TraceId` and `SpanId` are branded strings: the hex is the representation, so
778
+ there is nothing to convert before writing a header, and the compiler still
779
+ refuses a span id where a trace id belongs. `isValidTraceId` and
780
+ `isValidSpanId` are the guards that turn a `string` into one.
781
+
782
+ ## Sampling
783
+
784
+ ```ts
785
+ import { ratioSampler, alwaysSample, neverSample } from '@softistx/telemetry';
786
+
787
+ const sampler = ratioSampler(0.1); // keep a tenth of traces
788
+ ```
789
+
790
+ The sampler is asked **once, for the root span**, and the answer travels with
791
+ the trace — down through every child and out in the `traceparent`. A sampler
792
+ consulted per span produces traces missing their middles, and a gap in a trace
793
+ looks like work that never happened.
794
+
795
+ The decision is a function of the trace id, not a coin toss, and the rule is
796
+ OpenTelemetry's: two services at the same ratio make the **same** decision about
797
+ the same trace. Two services tossing independently at 10% keep a whole trace 1%
798
+ of the time.
799
+
800
+ **Logs are never sampled.** A log dropped because its trace was not kept is a
801
+ log missing at precisely the moment somebody is reading logs to find out what
802
+ happened. The `traceId` is attached either way, so an unsampled trace's logs
803
+ still group.
804
+
805
+ ## Attributes
806
+
807
+ An attribute is a **scalar, or a list of scalars** — that is what a backend can
808
+ index, filter and group by, and what OTLP accepts. Anything with structure is an
809
+ event type, not an attribute.
810
+
811
+ ```ts
812
+ import { attributesOf } from '@softistx/telemetry';
813
+
814
+ attributesOf({ orderId: 'o-1', amount: 4200, retried: false });
815
+ attributesOf({ orderId: 'o-1', code: undefined }); // → { orderId: 'o-1' }
816
+ ```
817
+
818
+ The coercion never refuses a value, because a log call must not fail: a
819
+ non-finite number, a `bigint` and a `Date` become text, an object becomes its
820
+ JSON, and a circular object still says something. `undefined` is dropped — one
821
+ absent field should not log `null` — while an explicit `null` is kept, because
822
+ somebody wrote it.
823
+
824
+ ## API
825
+
826
+ ### The root
827
+
828
+ | | |
829
+ | --- | --- |
830
+ | `createTelemetry(service, options?)` | builds one. See the option table above |
831
+ | `Telemetry` | `resource`, `sampler`, `minimum`, `stackTraces`, `emit(signal)`, `install()`, `flush()`, `close()` |
832
+ | `installedTelemetry()` | the installed default, if there is one |
833
+ | `uninstallTelemetry(telemetry?)` | for a test that wants the process back as it found it |
834
+ | `TELEMETRY_DEFAULTS` | the defaults, which are `stx-telemetry`'s |
835
+
836
+ ### Context
837
+
838
+ | | |
839
+ | --- | --- |
840
+ | `currentSpan()`, `currentTraceparent()`, `currentAttributes()` | what is open right here |
841
+ | `withTelemetry(telemetry, fn)` | a different telemetry for the block; scope beats the installed default |
842
+ | `withAttributes(record, fn)` | attributes inherited by every log and span inside |
843
+ | `currentContext()`, `runWithContext(context, fn)`, `resolveTelemetry()` | the lower level, for an integration |
844
+ | `TelemetryContext` | `{ telemetry, span?, attributes }` |
845
+
846
+ ### Exporting
847
+
848
+ | | |
849
+ | --- | --- |
850
+ | `Exporter` | `{ export(resource, batch), close?() }` |
851
+ | `consoleExporter(options?)` | one readable line per signal; `write` and `stackTraces` |
852
+ | `memoryExporter()` | keeps `spans` and `logs` for a test; `clear()`, `flush()` |
853
+ | `jsonLinesExporter(options?)` | one JSON object per line; `write` |
854
+ | `fileExporter(options)` | the same, appended to a file, with rotation |
855
+ | `DEFAULT_MAX_SIZE`, `DEFAULT_ROTATION_PERIOD` | 64 MiB and a UTC day |
856
+ | `rotationDue`, `rolledName`, `rolledOf`, `prunable`, `RotationPolicy` | the rotation decisions, for an exporter that writes its own files |
857
+ | `PipelineOptions` | what a `Telemetry` configures its queue with |
858
+
859
+ ### Spans
860
+
861
+ | | |
862
+ | --- | --- |
863
+ | `span(name, options?, block)` | opens one. `options` is `{ attributes?, kind? }`, kind `internal` by default |
864
+ | `continuing(traceparent, name, options?, block)` | the same, continuing an inbound trace. Kind `server` by default |
865
+ | `startSpan(name, options?)` | a `SpanHandle`: a span that outlives its block. `options` adds `traceparent?: string \| null` (continues that trace, kind `server`). Emits on `end()` only |
866
+ | `SpanHandle` | a `SpanScope` plus idempotent `end()` and `run(fn)` (runs `fn` with the span current) |
867
+ | `spanSync(name, options?, block)` | `span` for a synchronous block: the result stays as it is; a thenable result ends the span on settle |
868
+ | `SpanScope` | `context`, `traceId`, `spanId`, writable `name` and `status`, `traceparent()`, `attribute()`, `attributes()`, `event()` |
869
+ | `SpanOptions`, `SpanBlock` | |
870
+
871
+ ### Logging
872
+
873
+ | | |
874
+ | --- | --- |
875
+ | `createLogger(source)` | `source` becomes the OTLP instrumentation scope |
876
+ | `Logger` | `enabled(severity)`, `debug`, `info`, `warn`, `error` |
877
+ | `event(name, schema?)` | declares an event type; the result is called with its fields |
878
+ | `TelemetryEvent`, `isTelemetryEvent(value)`, `INVALID_EVENT_ATTRIBUTE` | |
879
+ | `errorInfo(failure, stackTraces?)`, `isAbort(failure)` | how a thrown value is flattened, and what counts as cancelled |
880
+
881
+ ### Trace identity
882
+
883
+ | | |
884
+ | --- | --- |
885
+ | `TraceId`, `SpanId` | branded 32- and 16-character lowercase hex strings |
886
+ | `SpanContext` | `{ traceId, spanId, sampled, remote }` — a span's place in a trace, as it travels |
887
+ | `randomTraceId()`, `randomSpanId()` | from `crypto.getRandomValues`, never `Math.random()` |
888
+ | `isValidTraceId(hex)`, `isValidSpanId(hex)` | type guards: right length, lowercase hex, not all zeros |
889
+ | `renderTraceparent(context)` | the header value, version `00` |
890
+ | `parseTraceparent(header)` | a `SpanContext` with `remote: true`, or `null` |
891
+ | `INVALID_TRACE_ID`, `INVALID_SPAN_ID` | all zeros |
892
+ | `DETACHED_SPAN_CONTEXT`, `isDetached(context)` | what a span carries when no telemetry is installed |
893
+
894
+ ### Sampling
895
+
896
+ | | |
897
+ | --- | --- |
898
+ | `Sampler` | `{ sample(traceId): boolean }` |
899
+ | `alwaysSample`, `neverSample` | the constants |
900
+ | `ratioSampler(ratio)` | keeps `ratio` of traces, by trace id. Throws `RangeError` outside `0..1` |
901
+
902
+ ### Attributes
903
+
904
+ | | |
905
+ | --- | --- |
906
+ | `AttributeScalar`, `AttributeValue`, `Attributes` | a scalar, a scalar or list of them, and a read-only record of those |
907
+ | `attributesOf(record)` | coerces a record of anything; drops `undefined` |
908
+ | `coerceAttribute(value)` | one value, the same way |
909
+ | `mergeAttributes(left, right)` | the right-hand side wins; neither argument is modified |
910
+ | `isEmptyAttributes(attributes)`, `EMPTY_ATTRIBUTES` | |
911
+
912
+ ### The signal model
913
+
914
+ | | |
915
+ | --- | --- |
916
+ | `Severity` | `'debug' \| 'info' \| 'warn' \| 'error'`. There is no `trace` level |
917
+ | `SEVERITY_NUMBER`, `SEVERITIES`, `meetsSeverity(severity, minimum)` | OTLP's numbers, ascending, and the floor test |
918
+ | `SpanKind`, `SPAN_KIND_NUMBER` | `internal` 1, `server` 2, `client` 3, `producer` 4, `consumer` 5 |
919
+ | `SpanStatus` | `'ok' \| 'error' \| 'cancelled'` |
920
+ | `Resource` | `{ service, version?, environment?, attributes }` |
921
+ | `LogRecord`, `SpanRecord`, `SpanEvent`, `ErrorInfo` | the records an exporter receives |
922
+ | `Signal` | `LogRecord \| SpanRecord`, discriminated on `type` |
923
+ | `signalAt(signal)`, `signalSpan(signal)` | when it happened, and which span it belongs to, whichever kind it is |
924
+
925
+ ## Traps
926
+
927
+ - **A `startSpan` handle that is never ended is never emitted.** Nothing flushes
928
+ it for you: end it when the stream finishes, errors or is aborted. `end()` is
929
+ idempotent, so ending from several of those paths is safe.
930
+ - **`fail` keeps the first failure.** A later `fail` (or a later throw seen by
931
+ `span`) does not replace it; the span reports the failure nearest the cause.
932
+ - **A usable `traceparent` beats the ambient span**, in `continuing` and in
933
+ `startSpan`. Pass `null` to inherit from the ambient span.
934
+ - **There is no `trace` severity.** Detail below `debug` belongs on a span as an
935
+ attribute, attached to the work it describes, rather than on a line somebody
936
+ has to correlate by hand.
937
+ - **Instants are epoch milliseconds**, which is the precision a JavaScript wall
938
+ clock has. OTLP wants nanoseconds, and the exporter multiplies; do not read a
939
+ sub-millisecond duration out of a span.
940
+ - **A nested list is not an attribute.** `['a', ['b']]` is flattened into text
941
+ rather than dropped — the value survives, but it stops being something a
942
+ backend can group by. Put structure in an event type.
943
+ - **`ratioSampler` throws on a bad ratio**, at construction. That is the one
944
+ place in this library that refuses an argument, and it is deliberate: it is
945
+ not on the path that writes a signal.
946
+ - **`exception.type` is the class name, not `error.name`.**
947
+ `class ChargeRefused extends Error {}` is recorded as `ChargeRefused`, because
948
+ `name` is inherited unless a subclass assigns it and the type is what a
949
+ dashboard groups by. An assigned `name` still wins.
950
+ - **A detached scope's `traceparent()` is `00-0…0-0…0-00`**, which this
951
+ library's own parser rejects. That happens only when nothing is installed, and
952
+ `isDetached(scope.context)` is the guard before injecting a header.
953
+ - **A rolled file is named for the instant it was rolled**, not for the period
954
+ it covers: `telemetry-20260915-000100.jsonl` holds the 14th. `keep` orders
955
+ archives by the stamp and collision number it parses out of the name, not by
956
+ the name as text — inside one second, `-9` is newer than `-12` as text, and
957
+ the unsuffixed name is the oldest of the three.
958
+ - **A log is never sampled, a span is.** A span of an unsampled trace is not
959
+ emitted at all — the block still runs — while its logs come out as usual,
960
+ carrying the `traceId`. Do not read "no span" as "nothing happened".
961
+ - **`log.warn(message, x)` reads `x` as a failure unless it is a plain object.**
962
+ An `Error`, a string, an array or a class instance is the failure; `{ code:
963
+ 51 }` is attributes. Pass both explicitly when it matters.
964
+ - **`close()` has to be awaited**, and a `process.exit()` before it resolves
965
+ loses the last batch. Nothing can block the event loop to save you from that.
966
+ - **The queue is unbounded.** An application that outruns its collector grows an
967
+ array, which a heap profile shows, rather than dropping the evidence of what
968
+ it was doing. A bounded queue would answer back-pressure by losing signals or
969
+ by blocking the application, and neither is an answer.
970
+ - **`node:async_hooks` is how the context travels**, and it is imported
971
+ statically. A bundler that shims the builtin to an empty module gets a
972
+ fallback: everything works, but the context stops propagating across `await`,
973
+ so pass the span explicitly there. A bundler that refuses to resolve the
974
+ builtin at all cannot load this package — alias it to an empty module.
975
+
976
+ ## License
977
+
978
+ [MIT](LICENSE)