Tracing and diagnostics channels
Prerequisite: node-asynclocalstorage. Objective: Connect spans without secret fields. Local baseline: Node.js 22.16.0 on Linux, ESM. Each example is independent: save as main.mjs in a disposable directory and run node main.mjs. The author harness uses a five-second timeout. Static snippets are not ByteMind interactive execution.
How it works
Create or obtain a channel, subscribe a listener and publish small structured records. Unsubscribe when the consumer is finished. Channel callbacks run synchronously, so expensive instrumentation can affect application latency. A trace model records parent/span identifiers and bounded attributes. OpenTelemetry adds standard context propagation, span lifecycle, sampling and exporters; the fixture does not install or export through OpenTelemetry. Do not confuse a channel event with a complete distributed trace.
Publish and unsubscribe a diagnostic listener
import {channel} from 'node:diagnostics_channel';import assert from 'node:assert/strict';const events=channel('bytemind.catalog.fixture');const received=[];const handler=message=>received.push(message.event);events.subscribe(handler);try{events.publish({event:'lookup',count:1});}finally{events.unsubscribe(handler);}events.publish({event:'ignored'});assert.deepEqual(received,['lookup']);console.log(received.join(','));Expected output:
lookupThe listener receives the synchronous publication only while subscribed.
Connect synthetic spans to a parent
const spans=[{id:'s1',parent:null,name:'request'},{id:'s2',parent:'s1',name:'db.lookup'},{id:'s3',parent:'s1',name:'serialize'}];const root=spans.find(s=>s.parent===null);console.log(root.name);console.log(spans.filter(s=>s.parent===root.id).map(s=>s.name).join(','));Expected output:
requestdb.lookup,serializeThis models a span tree only; no external propagation, SDK or sampling is exercised.
Common mistakes
Do not include credentials in span attributes or make an observer perform unbounded synchronous work. Missing telemetry does not establish that a business operation never happened.
Practice
Add a child span for a cache lookup with a safe operation name and a parent id; show which relationship is needed to reconstruct the tree.
Reference candidate: node-tracing-and-diagnostics-channels-lookup (route unverified). Documentation: https://nodejs.org/download/release/v22.16.0/docs/api/diagnostics_channel.html. Exact-version documentation not retrieved in this batch; local fixture behavior tested.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tracing and diagnostics channels — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
What does diagnostics_channel publish establish?
Why unsubscribe a temporary diagnostic listener?
Which span field connects a child to its parent?