Skip to content

feat(browser): Add option to ignore mark and measure spans #16443

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 3, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
integrations: [
Sentry.browserTracingIntegration({
ignoreMeasureSpans: ['measure-ignore', /mark-i/],
idleTimeout: 9000,
}),
],
tracesSampleRate: 1,
});

performance.mark('mark-pass');
performance.mark('mark-ignore');
performance.measure('measure-pass');
performance.measure('measure-ignore');
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { Route } from '@playwright/test';
import { expect } from '@playwright/test';
import { sentryTest } from '../../../../utils/fixtures';
import { envelopeRequestParser, shouldSkipTracingTest, waitForTransactionRequest } from '../../../../utils/helpers';

sentryTest(
'should ignore mark and measure spans that match `ignoreMeasureSpans`',
async ({ getLocalTestUrl, page }) => {
if (shouldSkipTracingTest()) {
sentryTest.skip();
}

await page.route('**/path/to/script.js', (route: Route) =>
route.fulfill({ path: `${__dirname}/assets/script.js` }),
);

const url = await getLocalTestUrl({ testDir: __dirname });

const transactionRequestPromise = waitForTransactionRequest(
page,
evt => evt.type === 'transaction' && evt.contexts?.trace?.op === 'pageload',
);

await page.goto(url);

const transactionEvent = envelopeRequestParser(await transactionRequestPromise);
const markAndMeasureSpans = transactionEvent.spans?.filter(({ op }) => op && ['mark', 'measure'].includes(op));

expect(markAndMeasureSpans?.length).toBe(3);
expect(markAndMeasureSpans).toEqual(
expect.arrayContaining([
expect.objectContaining({
description: 'mark-pass',
op: 'mark',
}),
expect.objectContaining({
description: 'measure-pass',
op: 'measure',
}),
expect.objectContaining({
description: 'sentry-tracing-init',
op: 'mark',
}),
]),
);
},
);
16 changes: 15 additions & 1 deletion packages/browser-utils/src/metrics/browserMetrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
setMeasurement,
spanToJSON,
stringMatchesSomePattern,
} from '@sentry/core';
import { WINDOW } from '../types';
import { trackClsAsStandaloneSpan } from './cls';
Expand Down Expand Up @@ -307,6 +308,14 @@ interface AddPerformanceEntriesOptions {
* Default: []
*/
ignoreResourceSpans: Array<'resouce.script' | 'resource.css' | 'resource.img' | 'resource.other' | string>;

/**
* Performance spans created from `performance.mark(...)` or `performance.measure(...)`
* with `name`s matching strings in the array will not be emitted.
*
* Default: []
*/
ignoreMeasureSpans: Array<string | RegExp>;
}

/** Add performance related spans to a transaction */
Expand Down Expand Up @@ -346,7 +355,7 @@ export function addPerformanceEntries(span: Span, options: AddPerformanceEntries
case 'mark':
case 'paint':
case 'measure': {
_addMeasureSpans(span, entry, startTime, duration, timeOrigin);
_addMeasureSpans(span, entry, startTime, duration, timeOrigin, options.ignoreMeasureSpans);

// capture web vitals
const firstHidden = getVisibilityWatcher();
Expand Down Expand Up @@ -440,7 +449,12 @@ export function _addMeasureSpans(
startTime: number,
duration: number,
timeOrigin: number,
ignoreMeasureSpans: AddPerformanceEntriesOptions['ignoreMeasureSpans'],
): void {
if (['mark', 'measure'].includes(entry.entryType) && stringMatchesSomePattern(entry.name, ignoreMeasureSpans)) {
return;
}

const navEntry = getNavigationEntry(false);
const requestTime = msToSec(navEntry ? navEntry.requestStart : 0);
// Because performance.measure accepts arbitrary timestamps it can produce
Expand Down
76 changes: 73 additions & 3 deletions packages/browser-utils/test/browser/browserMetrics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ import {
spanToJSON,
} from '@sentry/core';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { _addMeasureSpans, _addNavigationSpans, _addResourceSpans } from '../../src/metrics/browserMetrics';
import {
_addMeasureSpans,
_addNavigationSpans,
_addResourceSpans,
addPerformanceEntries,
} from '../../src/metrics/browserMetrics';
import { WINDOW } from '../../src/types';
import { getDefaultClientOptions, TestClient } from '../utils/TestClient';

Expand Down Expand Up @@ -76,7 +81,7 @@ describe('_addMeasureSpans', () => {
const startTime = 23;
const duration = 356;

_addMeasureSpans(span, entry, startTime, duration, timeOrigin);
_addMeasureSpans(span, entry, startTime, duration, timeOrigin, []);

expect(spans).toHaveLength(1);
expect(spanToJSON(spans[0]!)).toEqual(
Expand Down Expand Up @@ -112,10 +117,75 @@ describe('_addMeasureSpans', () => {
const startTime = 23;
const duration = -50;

_addMeasureSpans(span, entry, startTime, duration, timeOrigin);
_addMeasureSpans(span, entry, startTime, duration, timeOrigin, []);

expect(spans).toHaveLength(0);
});

it('ignores performance spans that match ignoreMeasureSpans', () => {
const pageloadSpan = new SentrySpan({ op: 'pageload', name: '/', sampled: true });
const spans: Span[] = [];

getClient()?.on('spanEnd', span => {
spans.push(span);
});

const entries: PerformanceEntry[] = [
{
entryType: 'measure',
name: 'measure-pass',
duration: 10,
startTime: 12,
toJSON: () => ({}),
},
{
entryType: 'measure',
name: 'measure-ignore',
duration: 10,
startTime: 12,
toJSON: () => ({}),
},
{
entryType: 'mark',
name: 'mark-pass',
duration: 0,
startTime: 12,
toJSON: () => ({}),
},
{
entryType: 'mark',
name: 'mark-ignore',
duration: 0,
startTime: 12,
toJSON: () => ({}),
},
{
entryType: 'paint',
name: 'mark-ignore',
duration: 0,
startTime: 12,
toJSON: () => ({}),
},
];

const timeOrigin = 100;
const startTime = 23;
const duration = 356;

entries.forEach(e => {
_addMeasureSpans(pageloadSpan, e, startTime, duration, timeOrigin, ['measure-i', /mark-ign/]);
});

expect(spans).toHaveLength(3);
expect(spans.map(spanToJSON)).toEqual(
expect.arrayContaining([
expect.objectContaining({ description: 'measure-pass', op: 'measure' }),
expect.objectContaining({ description: 'mark-pass', op: 'mark' }),
// name matches but type is not (mark|measure) => should not be ignored
expect.objectContaining({ description: 'mark-ignore', op: 'paint' }),
]),
);
});
});

describe('_addResourceSpans', () => {
Expand Down
25 changes: 23 additions & 2 deletions packages/browser/src/tracing/browserTracingIntegration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,22 @@ export interface BrowserTracingOptions {
*
* Default: []
*/
ignoreResourceSpans: Array<string>;
ignoreResourceSpans: Array<'resouce.script' | 'resource.css' | 'resource.img' | 'resource.other' | string>;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice type addition 👍

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, realized we only made this addition in browsermetrics.ts rather than the user-facing option. Luckily not breaking :D


/**
* Spans created from
* [`performance.mark(...)`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark)
* and
* [`performance.measure(...)`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/measure)
* calls will not be emitted if their names match strings in this array.
*
* This is useful, if you come across `mark` or `measure` spans in your Sentry traces
* that you want to ignore. For example, sometimes, browser extensions or libraries
* emit these entries on their own, which might not be relevant to your application.
*
* Default: [] - By default, all `mark` and `measure` entries are sent as spans.
*/
ignoreMeasureSpans: Array<string | RegExp>;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As this not only applies to the measure spans...should we call this ignorePerformanceAPISpans or ignoreWebPerformanceSpans? 🤔

No hard opinion on that though as my proposed name might be too wide in its description.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had exactly the same feeling. Let's make a decision fast, as I agree the name doesn't really include mark spans.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And this is how we could extend this if people need granular options:

ignorePerformanceAPISpans: {
  mark:
  measure:
  ...
}

Copy link
Member Author

@Lms24 Lms24 Jun 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed the option to ignorePerformanceApiSpans in ae2cfb0. Thanks for bringing this up!


/**
* Link the currently started trace to a previous trace (e.g. a prior pageload, navigation or
Expand Down Expand Up @@ -234,6 +249,7 @@ const DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {
enableLongAnimationFrame: true,
enableInp: true,
ignoreResourceSpans: [],
ignoreMeasureSpans: [],
linkPreviousTrace: 'in-memory',
consistentTraceSampling: false,
_experiments: {},
Expand Down Expand Up @@ -277,6 +293,7 @@ export const browserTracingIntegration = ((_options: Partial<BrowserTracingOptio
shouldCreateSpanForRequest,
enableHTTPTimings,
ignoreResourceSpans,
ignoreMeasureSpans,
instrumentPageLoad,
instrumentNavigation,
linkPreviousTrace,
Expand Down Expand Up @@ -319,7 +336,11 @@ export const browserTracingIntegration = ((_options: Partial<BrowserTracingOptio
// This will generally always be defined here, because it is set in `setup()` of the integration
// but technically, it is optional, so we guard here to be extra safe
_collectWebVitals?.();
addPerformanceEntries(span, { recordClsOnPageloadSpan: !enableStandaloneClsSpans, ignoreResourceSpans });
addPerformanceEntries(span, {
recordClsOnPageloadSpan: !enableStandaloneClsSpans,
ignoreResourceSpans,
ignoreMeasureSpans,
});
setActiveIdleSpan(client, undefined);

// A trace should stay consistent over the entire timespan of one route - even after the pageload/navigation ended.
Expand Down
Loading