Use SDK plugins to track open spans and access them by name from different parts of your codebase.
When starting custom spans, a reference to the object representing that span is returned and can be used to set further attributes or end the measurement.
const span = BugsnagPerformance.startSpan("login")
However, sometimes you may wish to end the span in a separate component, requiring an awkward passing of the object between scopes. The @bugsnag/plugin-named-spans
plugin keeps track of all open spans and allows you to obtain a reference to them using just their name from anywhere in your codebase.
const span: Span | null = BugsnagPerformance.getSpanControls(new NamedSpanQuery('login'))
if (span) {
span.setAttribute('user.id', 12345)
span.end()
}
Install the @bugsnag/plugin-named-spans
package:
yarn add @bugsnag/plugin-named-spans
# or
npm install --save @bugsnag/plugin-named-spans
To enable the plugin, include it in the configuration options when starting the SDK:
import { BugsnagNamedSpansPlugin } from '@bugsnag/plugin-named-spans'
BugsnagPerformance.start({
apiKey: 'YOUR_API_KEY',
plugins: [new BugsnagNamedSpansPlugin()]
})
The plugin maintains a map of open spans that can be queried via BugsnagPerformance.getSpanControls()
. The NamedSpanQuery
class allows you to specify the name of the span you want to retrieve.
import { NamedSpanQuery } from '@bugsnag/plugin-named-spans'
const span: Span | null = BugsnagPerformance.getSpanControls(new NamedSpanQuery('login'))
if (span) {
span.setAttribute('user.id', 12345)
span.end()
}
If the span does not exist; has already ended; or is no longer valid, it will return null
. If multiple spans with the same name are open, only the most recent one will be returned.
To avoid memory leaks caused by spans not being ended, spans older than 10 minutes are removed from tracked memory to allow them to be deallocated.