Skip to content

Instantly share code, notes, and snippets.

@Lms24
Created March 10, 2023 15:14
Show Gist options
  • Save Lms24/b36a8f310410240863aa6e50dc19ab3d to your computer and use it in GitHub Desktop.
Save Lms24/b36a8f310410240863aa6e50dc19ab3d to your computer and use it in GitHub Desktop.
SvelteKit Sentry Routing instrumentation PoC
export function svelteKitRoutingInstrumentation<T extends Transaction>(
customStartTransaction: (context: TransactionContext) => T | undefined,
startTransactionOnPageLoad?: boolean,
startTransactionOnLocationChange?: boolean
): void {
if (!browser) {
return;
}
function createPageloadTxn(): Transaction | undefined {
if (!startTransactionOnPageLoad) {
return undefined;
}
const ctx: TransactionContext = {
name: 'initial pageload',
op: 'pageload',
description: window.location.pathname
};
if (customStartTransaction) {
return customStartTransaction(ctx);
}
return undefined;
}
const pageloadTxn = createPageloadTxn();
let routingSpan: Span | undefined = undefined;
// getCurrentHub().getScope()?.setSpan(pageloadTxn);
const pageUnsub = page.subscribe((page) => {
if (!page) {
return;
}
console.log({ page });
const routeId = page.route?.id;
if (pageloadTxn && !pageloadTxn.endTimestamp && routeId) {
pageloadTxn.setName(routeId, 'route');
console.log('UPDATED PAGELOAD TXN NAME');
}
if (routingSpan && !routingSpan.endTimestamp) {
routingSpan.finish();
routingSpan = undefined;
}
});
const navUnsubscribe = navigating.subscribe((navigation) => {
if (!navigation) {
// This happens e.g. on the initial pageload
return;
}
if (!startTransactionOnLocationChange) {
return;
}
let activeTxn = getCurrentHub().getScope()?.getTransaction();
if (!activeTxn) {
activeTxn = customStartTransaction({
name: navigation.to?.route.id || 'unknown',
op: 'navigation',
metadata: { source: 'route' }
});
}
if (activeTxn) {
if (routingSpan) {
routingSpan.finish();
}
routingSpan = activeTxn.startChild({
description: `${navigation.from?.route.id} -> ${navigation.to?.route.id}`,
op: 'ui.sveltekit.routing',
tags: {
'routing.instrumentation': '@sentry/sveltekit'
}
});
}
});
window.addEventListener('unload', () => {
if (routingSpan) {
routingSpan.finish();
}
if (pageloadTxn) {
pageloadTxn.finish();
}
const activeTxn = getCurrentHub().getScope()?.getTransaction();
if (activeTxn) {
activeTxn.finish();
}
if (pageUnsub) {
pageUnsub();
}
navUnsubscribe();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment