Guides
Custom spans
Time your own functions and see them inside the trace of a request or a page load.
The SDK traces requests and page loads on its own. Wrap your own code in startSpan to see how long it takes inside those traces.
import { startSpan } from "@openperf/sdk/node";
const total = startSpan({ name: "sum order lines" }, () => {
return [19.9, 5, 12.5].reduce((sum, price) => sum + price, 0);
});startSpan runs the callback, returns its result and ends the span when the callback returns. In the browser, import it from @openperf/sdk/browser.
Options
Prop
Type
Time async work
When the callback returns a promise, the span ends when the promise settles, and startSpan returns that promise.
import { setTimeout } from "node:timers/promises";
import { startSpan } from "@openperf/sdk/node";
const report = await startSpan({ name: "build report", op: "report" }, async () => {
await setTimeout(200);
return { rows: 120 };
});Add attributes while it runs
The callback receives the span. Use setAttribute for values you only know during the work.
import { startSpan } from "@openperf/sdk/node";
startSpan({ name: "import contacts", attributes: { source: "csv" } }, (span) => {
const rows = ["ada", "grace"];
span.setAttribute("rows", rows.length);
});Nest spans
A span started inside the callback of another span becomes its child. A span started while a request or a page load is running becomes a child of that trace. Outside any trace, the span starts a trace of its own.
import { startSpan } from "@openperf/sdk/node";
startSpan({ name: "checkout" }, () => {
startSpan({ name: "validate cart" }, () => undefined);
startSpan({ name: "reserve stock" }, () => undefined);
});Errors
When the callback throws or its promise rejects, the span is marked as failed, the error is reported under Errors, and the same error is thrown on to your code. You do not need to call captureException for it.
Naming
- Name the action, not the instance:
charge card, notcharge card 4242. On the server, a span that starts a trace gives the trace its name, so a changing name gives every run a different trace name. Put the changing values inattributes. - Use
opfor the kind of work. For a span that starts a trace it is shown next to the name in Traces.
Limits
- In the browser, a span or a request becomes a child only when it starts in the synchronous part of the callback. After an
awaitit attaches to the open page load or navigation instead. On Node.js and Bun, nesting also works acrossawait. - In the browser, a running span keeps the page load or navigation trace open, for 30 seconds at most.
- Spans of a trace that is not sampled are not sent. See Sampling.
- Before
initruns, or when it has no DSN,startSpanonly runs the callback.