Browser instrumentation
The browser half of Belemetry is one dependency-free ES module, bit-belemetry.js. It starts from
the configuration <BelemetryScript /> writes into the page, before Blazor boots, so it sees
the initial load, the web vitals and the earliest errors - on interactive and static SSR pages alike. Every
section below has a live trigger and, under it, the records it produced, read back from this site's own OTLP
receiver.
Page views
Feature PageViews. The script records the initial load and every client-side navigation -
history.pushState, replaceState, popstate and Blazor's enhanced
navigation - as a log record with the event name browser.page_view, carrying
url.full, url.path, page.title, page.referrer and
browser.navigation.type:
| Type | When |
|---|---|
initial | The document load |
push / replace | history.pushState / replaceState - a Blazor link click, NavigationManager.NavigateTo, an enhanced navigation |
pop | The browser's back and forward buttons within the app (popstate) |
hash | A change of the fragment alone - recorded only with TrackHashChanges (off by default) |
manual | TrackPageView from C# or JavaScript |
restore | The page came back from the back/forward cache (a pageshow with persisted): no navigation event fires, but to the user it is a new visit |
With TrackPageVisitTime (off by default) the time spent on each page is recorded too, as a
browser.page_visit_time event carrying page.visit.duration (milliseconds) - emitted
for the previous page when the next page view starts, and for the current one when it is hidden. The next
visit starts when the page is shown again, so time in a background tab or in the back/forward cache is
counted nowhere and nothing is counted twice. Application Insights shows it as the
PageVisitTime event, the shape its own JavaScript SDK uses.
For views the URL does not show - a dialog, a wizard step, a tab - call IBelemetry.TrackPageView.
In this demo the .NET side runs in WebAssembly, so that record goes through the .NET pipeline and shows up
with the source wasm.
No page views yet - navigate away and back, or press the button.
Interactions
Feature Interactions. A capture-phase listener records every click (or the events in
InteractionEvents) on a link, a button, a submit input or any element carrying
data-bit-belemetry-name, as a browser.user_interaction event with
target.element, target.id, target.name and target.xpath.
The name comes from data-bit-belemetry-name, then aria-label, then name.
The element's text is recorded only with CaptureInteractionText, because text can be personal
data, and input values are never read. Anything under data-bit-belemetry-ignore is skipped.
Three clicks on one element within a second also record one browser.rage_click event
(TrackRageClicks, on by default) - the frustration signal of a user who expected something to
happen; press Pay three times quickly.
Recorded
Not recorded
No interactions yet - press the buttons above. Every other button on this page is recorded too.
Web vitals
Feature Performance. The five Core Web Vitals and their companions are measured from the
Performance Timeline and recorded as browser.web_vital events with web_vital.name,
web_vital.value, web_vital.delta, web_vital.rating
(good, needs-improvement or poor, on the official thresholds),
web_vital.id and web_vital.navigation_type:
| Vital | Measures | Reported |
|---|---|---|
TTFB | Time to first byte of the document | At start, once the response has begun |
FCP | First contentful paint | When it happens |
LCP | Largest contentful paint | At the first click or key press, or when the page is hidden |
CLS | Cumulative layout shift (largest session window) | When the page is hidden |
INP | Interaction to next paint | When the page is hidden |
CLS and INP keep changing for as long as the page is open, so they are reported when it is hidden - switch to
another tab and back after pressing the button. A shift that follows your input within 500 ms does not count
(the spec's hadRecentInput), so the spacer this button inserts is excluded; the shift when it is
removed 1.5 s later is the one CLS records.
A page restored from the back/forward cache is a new visit to the user, but the browser keeps its old
timeline. So, as Google's web-vitals library does, a restore starts a new generation of vitals
under new ids: FCP and LCP measured from the restore to the next painted frame, CLS and INP counted from zero,
and web_vital.navigation_type = back-forward-cache (otherwise it is the navigation's own type:
navigate, reload, back-forward or prerender). To try it, go
to another site in this tab and press Back: when the browser restores this page from its cache, the page view
feed above shows a view of type restore, and new vitals follow.
This paragraph moves down while a spacer is inserted above it, then jumps back.
No web vitals yet - TTFB and FCP arrive first; switch tabs and come back for CLS and INP.
Document load, resources and long tasks
Also feature Performance. DocumentLoad (on by default) records the initial load as
an internal documentLoad span with the navigation-timing milestones as events
(domInteractive, domContentLoadedEventEnd, loadEventEnd, ...).
ResourceTiming (off by default) adds a resourceFetch span per script, stylesheet and
image with url.full, http.response.body.size and network.protocol.name -
a lot of records, so turn it on deliberately. LongTasks (off by default, on in this demo) records
every main-thread task over 50 ms as a longtask span.
No documentLoad or longtask spans yet - press the button, or reload the page.
fetch and XHR with trace context
Feature Dependencies. Every fetch and XMLHttpRequest becomes a client
span named after its method, with http.request.method, url.full,
server.address, server.port, http.response.status_code and, for a
failure or a 4xx/5xx answer, error.type and an error status. For targets matched by
PropagateTraceContextTo (same-origin by default) the script adds a W3C traceparent
header, so the browser span and the server's request span join one trace.
- Failures. A 4xx or 5xx answer sets
error.typeto the status code; a request that never got an answer sets it to the error's name -TypeErrorfor a network failure offetch,NetworkErrororTimeoutErrorfor an XHR - and all of them get an error status. - Aborted requests are not failures. A request the app cancelled itself - a superseded
search, a navigation away - keeps
error.type = AbortErrorbut no error status, so it does not count against the dependency's success rate. - Unknown methods. A method outside the HTTP conventions' list (a typo, a custom verb) is
recorded as
http.request.method = _OTHERwith the original inhttp.request.method_original, and the span is namedHTTP- so a stray method cannot multiply the span names a backend groups by.
The echo endpoint below answers with the traceparent it received: its trace id is the trace id
of the browser span in the feed. URLs in IgnoreUrls (the Blazor framework routes by default, plus
the exporters' own endpoints) are never recorded, and neither is a request that already carries a
traceparent - in WebAssembly that is .NET's HttpClient when it traces itself, which
takes the HttpActivityPropagationSupport switch the WebAssembly SDK turns off by default (this demo
turns it on; see .NET instrumentation).
No dependency spans yet - press one of the buttons above.
Errors
Feature Errors. Uncaught errors (window.onerror) and unhandled promise rejections
become log records with severity ERROR, the event name exception, and
exception.type, exception.message and exception.stacktrace - scrubbed by
the privacy rules first. Messages matching IgnoreErrorMessages are dropped;
the default list has the harmless ResizeObserver loop warning every browser raises and the
empty Script error. of a cross-origin script (no message, no stack, nothing to act on).
Handled .NET exceptions go through IBelemetry.TrackException.
An error thrown in a loop - a timer, a render loop, a retry - would fill the queue, evict every other record
and cost the backend one record per occurrence from every client. So an error identical to one just recorded
(same scope, type, message and first stack lines) is suppressed for Errors.DuplicateWindow (5 s),
and at most Errors.MaxPerMinute (100) errors a minute leave the page, with a burst of as many;
what is held back is counted as error_limit by getStats(). The .NET pipeline of a
WebAssembly or Hybrid app applies the same two rules to its own error logs and TrackException
calls; the server pipeline serves every user at once and is not capped. Zero switches a rule off. Very long
messages and stack traces are cut at MaxValueLength - see Privacy.
No errors yet - press one of the buttons above.
Console capture
With CaptureConsole (off by default, on in this demo) the script wraps the console methods named
in ConsoleLevels (error and warn by default) and records each call as a
log record. console.error belongs to the Errors feature, the other levels to
Logs. The original method always runs first, so the developer tools look the same as before.
No console records yet - press one of the buttons above.
Custom events
Feature Events. A custom event is a log record whose event name is the name you give it, with
your attributes. From C# call IBelemetry.TrackEvent; from JavaScript call
BitBelemetry.trackEvent on the global the module sets. Both carry session.id (and the
user ids with UserTracking), so a backend can join them with everything else the session did.
No custom events yet - press one of the buttons above.
Diagnostics
BitBelemetry.getStats() says what the script dropped since the page loaded and why
(not_consented, error_limit, queue_full, sampled_out, ...)
and what became of its requests (delivered, rejected, kept for a later
retry, dropped, withdrawn by a consent revoke) - the first thing to look at when
telemetry does not arrive. queued is
what waits for the next export, and pending what is held until a consent decision. On the .NET
side the same counts are metrics on the Bit.Belemetry meter, once it is added to
Metrics.Meters (this demo does - see .NET instrumentation).
The script exports in batches: every Browser.FlushInterval (5 s; 2 s in this demo), as soon as
MaxBatchSize (100) records are queued, and whenever the page is hidden. At most
MaxQueueSize (1024) records wait; past it the oldest go first (queue_full).
Browser.Debug writes the script's own diagnostics to console.debug. The
Troubleshooting page puts all of this together.
The JavaScript API
_content/Bit.Belemetry/bit-belemetry.js is an ES module, and it also sets
window.BitBelemetry, so plain scripts, static SSR pages and pages without Blazor can use it. In a
Blazor app the .NET API covers the same ground; these are for everything else. Every call is safe before
start and never throws into the page.
| Export | What it does |
|---|---|
start(config) | Starts the script with a browser configuration (shape on the Semantic conventions page). Idempotent: a second call only updates the consent defaults and the transport. <BelemetryScript /> and <BelemetryInitializer /> call it for you |
setConsent(features) | Records the decision, a bit mask of BitBelemetry.Features: persists it, purges what was revoked, installs or removes instrumentations |
getConsent() / isConsentDecided() | The effective grant (narrowed to the configured features and by Global Privacy Control), and whether the user has decided |
setUser(id) | The authenticated user.id, or null to clear it; kept only with UserTracking |
trackEvent(name, attributes?) | A custom event (feature Events) |
trackPageView(name?, url?, attributes?) | A manual page view, of type manual |
trackException(type, message, stack?, attributes?) | A handled error (feature Errors) |
addProcessor(fn) | Runs fn(record) on every record as it is exported; change it in place, or return false to drop it. Returns the function that removes it - see Processors |
setAttributes(attributes) | Attributes added to every record from now on; a null value removes one key, setAttributes(null) all of them |
flush() | A promise that resolves when everything queued has been handed to the transport |
getContext() | { consent, decided, sessionId, pseudoId, userId } |
getStats() | What was dropped and why, what became of the requests, and what is queued and pending - the Diagnostics card above |
Features | The feature bits and groups, the same numbers as BelemetryFeatures |
API
Every option of the script lives on options.Browser:
BelemetryBrowserOptions
Class
The browser script (bit-belemetry.js): what it instruments and how it ships records.
| Name | Type and default | Description |
|---|---|---|
Enabled |
bool= true |
Whether the browser script runs at all. Defaults to true. |
Transport |
BelemetryBrowserTransport= BelemetryBrowserTransport.Auto |
How browser records leave the page. Defaults to BelemetryBrowserTransport.Auto. |
TrackHashChanges |
bool= false |
Whether URL changes made only to the fragment (#...) count as page views. Defaults to false. |
TrackPageVisitTime |
bool= false |
Whether the time spent on each page is recorded, as a browser.page_visit_time event carrying page.visit.duration (milliseconds) when the next page view starts or the page is hidden (Application Insights shows it as the PageVisitTime event). Defaults to false. |
InteractionEvents |
List<string>= ["click"] |
The DOM events recorded as interactions. Defaults to click. |
CaptureInteractionText |
bool= false |
Whether the visible text of the clicked element is recorded (truncated to BelemetryBrowserOptions.MaxInteractionTextLength). Defaults to false because text can contain personal data; prefer data-bit-belemetry-name. Input values are never read. |
MaxInteractionTextLength |
int= 64 |
The maximum length of recorded element text. Defaults to 64. |
TrackRageClicks |
bool= true |
Whether three clicks on one element within a second also emit a browser.rage_click event (feature BelemetryFeatures.Interactions) - the frustration signal of a user who expected something to happen. Once per burst; the clicks themselves are still recorded. Defaults to true. |
WebVitals |
bool= true |
Whether web vitals (LCP, INP, CLS, FCP, TTFB) are recorded. Defaults to true. |
DocumentLoad |
bool= true |
Whether the initial document load is recorded as a span with navigation-timing events. Defaults to true. |
ResourceTiming |
bool= false |
Whether every resource fetched by the page (scripts, styles, images) is recorded as a span. Defaults to false. |
LongTasks |
bool= false |
Whether main-thread tasks longer than 50 ms are recorded. Defaults to false. |
Fetch |
bool= true |
Whether fetch calls are recorded as dependency spans. Defaults to true. |
Xhr |
bool= true |
Whether XMLHttpRequest calls are recorded as dependency spans. Defaults to true. |
PropagateTraceContextTo |
List<string>= ["same-origin"] |
Where a W3C traceparent header is added to fetch/XHR calls, so the browser span and the server span join one trace: same-origin, *, or regular expressions matched against the absolute URL. Defaults to same-origin. Cross-origin targets must allow the header (CORS). |
IgnoreUrls |
List<string>= ["/_framework/", "/_blazor", "/_content/"] |
Regular expressions of URLs never recorded as dependencies. Defaults to the Blazor framework routes. |
IgnoreErrorMessages |
List<string>= ["ResizeObserver loop", "^Script error\.?$"] |
Regular expressions of JS error messages never recorded. Defaults to the benign ResizeObserver loop warnings and to Script error. - what the browser reports, with no stack or location, for an error in a cross-origin script loaded without CORS: nothing in it can be acted on. |
CaptureConsole |
bool= false |
Whether console calls are recorded as logs. Defaults to false. |
ConsoleLevels |
List<string>= ["error", "warn"] |
The console levels recorded when BelemetryBrowserOptions.CaptureConsole is on. Defaults to error and warn. |
SessionInactivityTimeout |
TimeSpan= 00:30:00 |
How long without activity ends a session. Defaults to 30 minutes. |
SessionMaxDuration |
TimeSpan= 1.00:00:00 |
The maximum length of a session. Defaults to 24 hours. |
SessionSampleRatio |
double= 1 |
The fraction of sessions whose browser telemetry is recorded (decided once per session). Defaults to 1.0. |
MaxQueueSize |
int= 1024 |
The maximum number of records the script holds; the oldest are dropped past it. Defaults to 1024. |
MaxBatchSize |
int= 100 |
The maximum number of records per request. Defaults to 100. |
FlushInterval |
TimeSpan= 00:00:05 |
How often the script exports. Defaults to 5 seconds (it also exports when the page is hidden). |
MaxRelayedPerMinute |
int= 3000 |
On Blazor Server with the BelemetryBrowserTransport.Relay transport, the most records one circuit may relay per minute on average (at least 1); the excess is dropped. The page is untrusted there and the queue it relays into serves every user. On top of it a circuit may send a burst of BelemetryBrowserOptions.MaxQueueSize plus BelemetryConsentOptions.PendingLimit records - a full queue and what a consent decision releases. Defaults to 3000. |
Debug |
bool= false |
Whether the script writes its own diagnostics to console.debug. Defaults to false. |
The error limits, on options.Errors - applied by the script, and by the .NET pipeline of WebAssembly and Hybrid apps:
BelemetryErrorOptions
Class
Protection against error floods: an error thrown in a loop (a timer, a render loop, a retry) would otherwise fill the queue, evict every other record and cost the backend a record per occurrence from every client. Applied by the browser script to its errors, and by the .NET pipeline of WebAssembly and Hybrid apps to theirs (the server pipeline serves every user at once and is not capped).
| Name | Type and default | Description |
|---|---|---|
DuplicateWindow |
TimeSpan= 00:00:05 |
How long an error identical to one just recorded - same scope, type, message and first stack frame - is suppressed. A loop that keeps throwing it is then recorded once per window. Defaults to 5 seconds; zero or less records every occurrence. |
MaxPerMinute |
int= 100 |
The most error records per minute (on average, with a burst of as many); the excess is dropped. Defaults to 100; zero or less is unlimited. |
Manual telemetry from C#:
IBelemetry
Interface
Manual telemetry from C#: custom events, page views and handled exceptions, the authenticated user, and flushing. Everything else (logs, traces, metrics, browser instrumentation) is collected automatically.
| Name | Type and default | Description |
|---|---|---|
TrackEvent(string name, IReadOnlyDictionary<string, object>? attributes = null) |
void |
Records a custom event (feature BelemetryFeatures.Events). |
TrackPageView(string? name = null, string? url = null, IReadOnlyDictionary<string, object>? attributes = null) |
void |
Records a page view (feature BelemetryFeatures.PageViews). Navigation is already tracked automatically; use this for virtual pages such as dialogs or wizard steps. |
TrackException(Exception exception, IReadOnlyDictionary<string, object>? attributes = null) |
void |
Records a handled exception (feature BelemetryFeatures.Errors). |
SetUserAsync(string? userId) |
ValueTask |
Sets (or with null clears) the authenticated user id sent as user.id. Only kept while BelemetryFeatures.UserTracking is granted. |
FlushAsync(CancellationToken cancellationToken = null) |
ValueTask |
Exports everything queued now - e.g. before a Hybrid app is suspended. |