We want to measure the time that a user waits between pushing a button and seeing their result. The examples for creating a trace span only work within a single page, and the button triggers a page load. How can I do this?
Ah, good question!
TL;DR: store the start time of the span, and then create the span on the new page.
Usually, you want to start a span, do some work, and then end the span. The whole span gets sent to your OpenTelemetry collector (and thence to Honeycomb) when you end it.
But when a page load happens, that span object is lost. Honeycomb never hears about it becausespan.end()
wasn’t called.
How can we deal with this?
Create the span only on the new page, where you can end it. But! Tell it the startTime explicitly, and give it a time that you pull from storage. Populate that storage when they push the button! This way you get a new span that started at button-push time, and you’re ready to end it.
In code, that looks like these two operations:
In the first page, when the button is pushed, store the time:
window.sessionStorage.setItem("when", Date.now());
And in the second page, retrieve the time and turn it back into a Date:
const whenString = window.sessionStorage.getItem("when"); const when = new Date(Number(whenString)); const span = opentelemetry.trace.getTracer("my app") .startSpan("get report", { startTime: when }); span.end();
That’s it. This is the simplest solution to a trace that crosses a page.
This does assume that it’s a single span by itself that you want to create. If we had an existing trace and wanted to continue it after a page load, we’d need to store the trace context in sessionStorage, too. Want to know how to do that, or anything else with observability? Ask Miss O11y!