Skip to main content

traceCallback

method TracingChannel.prototype.traceCallback
unstable
Jump to headingTracingChannel.prototype.traceCallback<Fn extends (
this: any,
...args: any[],
) => any
>
(
fn: Fn,
position?: number,
context?: ContextType,
thisArg?: any,
...args: Parameters<Fn>,
): void

Trace a callback-receiving function call. This will always produce a start event and end event around the synchronous portion of the function execution, and will produce a asyncStart event and asyncEnd event around the callback execution. It may also produce an error event if the given function throws an error or the returned promise rejects. This will run the given function using channel.runStores(context, ...) on the start channel which ensures all events should have any bound stores set to match this trace context.

The position will be -1 by default to indicate the final argument should be used as the callback.

import diagnostics_channel from 'node:diagnostics_channel';

const channels = diagnostics_channel.tracingChannel('my-channel');

channels.traceCallback((arg1, callback) => {
  // Do something
  callback(null, 'result');
}, 1, {
  some: 'thing',
}, thisArg, arg1, callback);

The callback will also be run with channel.runStores(context, ...) which enables context loss recovery in some cases.

To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions which are added after the trace begins will not receive future events from that trace, only future traces will be seen.

import diagnostics_channel from 'node:diagnostics_channel';
import { AsyncLocalStorage } from 'node:async_hooks';

const channels = diagnostics_channel.tracingChannel('my-channel');
const myStore = new AsyncLocalStorage();

// The start channel sets the initial store data to something
// and stores that store data value on the trace context object
channels.start.bindStore(myStore, (data) => {
  const span = new Span(data);
  data.span = span;
  return span;
});

// Then asyncStart can restore from that data it stored previously
channels.asyncStart.bindStore(myStore, (data) => {
  return data.span;
});

Type Parameters Jump to heading

Jump to headingFn extends (
this: any,
...args: any[],
) => any

Parameters Jump to heading

callback using function to wrap a trace around

optional
Jump to headingposition: number

Zero-indexed argument position of expected callback

optional
Jump to headingcontext: ContextType

Shared object to correlate trace events through

optional
Jump to headingthisArg: any

The receiver to be used for the function call

Jump to heading<span>...args</span>: Parameters<Fn>

Return Type Jump to heading

void

The return value of the given function

Back to top