Skip to main content

monoscope_flutter 0.3.1 copy "monoscope_flutter: ^0.3.1" to clipboard
monoscope_flutter: ^0.3.1 copied to clipboard

Monoscope SDK for Flutter: OpenTelemetry tracing, error and crash reporting, and session replay.

Monoscope Flutter SDK #

The Monoscope Flutter SDK adds session replay, OpenTelemetry tracing, and error and crash reporting to Flutter apps.

Used together with the Monoscope server SDKs, you get end-to-end observability — a tap in the app connected to the backend services, APIs and databases it reaches.

  • Replay user sessions to see exactly what happened on screen.
  • Trace requests from the app, through your backend, into your database.
  • Capture errors with stack traces and breadcrumbs.
  • Track navigation across every route change.

Platform support #

Platform Tracing Replay Dart errors Native crashes Global HTTP
Android ✅ ✅ ✅ ✅ JVM exceptions ✅
iOS ✅ ✅ ✅ ✅ signals + NSException ✅
macOS ✅ ✅ ✅ ✅ signals + NSException ✅
Windows / Linux ✅ ✅ ✅ — ✅
Web ✅ ✅ ✅ — — (use MonoscopeClient)

Everything degrades gracefully: where the native side is absent the SDK reports no native crashes rather than failing to start.


Installation #

flutter pub add monoscope_flutter

Quick start #

import 'package:flutter/material.dart';
import 'package:monoscope_flutter/monoscope_flutter.dart';

Future<void> main() async {
  await Monoscope.start(
    const MonoscopeConfig(apiKey: 'YOUR_API_KEY'),
  );

  runApp(const MonoscopeWidget(child: MyApp()));
}

Your API key is in your Monoscope project settings.

MonoscopeWidget is what enables session replay: it provides the boundary that frames are captured from, reports tap positions, and flushes the recording before the OS suspends the app. Tracing and error reporting work without it.

To record route changes, add the navigator observer:

MaterialApp(
  navigatorObservers: [MonoscopeNavigatorObserver()],
  home: const HomeScreen(),
)

Then identify the user, at any point after startup:

Monoscope.instance?.setUser(
  const MonoscopeUser(id: 'user-123', email: 'user@example.com'),
);

Set debug: true to log what the SDK sends, and call Monoscope.instance?.test() to verify the setup:

final ok = await Monoscope.instance!.test(); // true when the span was exported

Configuration #

MonoscopeConfig accepts:

Name Type Description
apiKey String Required — your Monoscope API key.
serviceName String? Reported as service.name. Defaults to flutter.
exporterEndpoint String OTLP/HTTP traces endpoint. Defaults to Monoscope's collector — see Choosing an ingest endpoint.
replayEventsBaseUrl String Base URL for replay uploads. Defaults to https://app.monoscope.tech.
resourceAttributes Map<String, String> Extra OpenTelemetry resource attributes.
user MonoscopeUser? User identity for the session.
tenant MonoscopeTenant? Tenant/organization identity.
debug bool Log SDK diagnostics. Default false.
enabled bool Start collecting immediately. Default true.
sampleRate double Trace sampling rate, 0–1. Default 1.
replaySampleRate double Replay sampling rate, 0–1, decided once per session. Default 1.
captureReplay bool Record session replay. Default true.
captureErrors bool Install Flutter's error hooks. Default true.
captureNavigation bool Record route changes. Default true.
captureLogs bool Mirror debugPrint into the replay console. Default true.
captureMetrics bool Collect frame timings and startup time as OTel metrics. Default true.
captureSlowFrames bool Emit a span per frame over 16.7 ms. Default false — high volume.
captureFrozenFrames bool Emit a span per frame over 700 ms. Default true.
captureNativeCrashes bool Install native handlers for crashes that kill the process. Default true.
instrumentGlobalHttp bool Trace all outbound dart:io HTTP by overriding HttpClient. Default true.
metricsExporterEndpoint String? OTLP metrics endpoint. Defaults to exporterEndpoint with /v1/traces → /v1/metrics.
metricsExportInterval Duration How often metrics are exported. Default 60 seconds.
maskAllText bool Redact every text run, not just text fields. Default false.
maskAllImages bool Redact every image. Default false.
replayFrameInterval Duration Target interval between frames. Default 1 second.
replayImageQuality int JPEG quality, 1–100. Default 60.
replayMaxWidth int Frames are captured no wider than this, in pixels. Default 480.
sessionTimeout Duration Inactivity window after which the session id rotates. Default 30 minutes.

API #

Monoscope.start(config) #

Initializes the SDK. Call it once, as early in main as possible. Calling it again returns the running instance.

Monoscope.instance #

The running instance, or null before start. Null-safe throughout, so integration points can report without ordering rules.

setUser(user) / setTenant(tenant) #

Associates a user or tenant with the session. Applies to spans and to replay recordings, and can be called at any time.

Monoscope.instance?.setUser(
  const MonoscopeUser(
    id: 'user-123',
    email: 'user@example.com',
    fullName: 'Ada Lovelace',
    roles: ['admin'],
  ),
);

startSpan(name, fn) / startSpanAsync(name, fn) #

Runs fn inside a span, recording its duration and any exception. Spans started within fn nest underneath it.

await Monoscope.instance?.startSpanAsync('checkout', (span) async {
  span.setAttribute(Attribute.fromInt('cart.items', 3));
  await submitOrder();
});

recordEvent(name, attributes:) #

Records a custom event as a zero-duration span.

Monoscope.instance?.recordEvent(
  'subscription.upgraded',
  attributes: {'plan': 'pro'},
);

captureException(error, stackTrace:, extra:) #

Reports an error the app caught itself. Uncaught errors are reported automatically.

try {
  await risky();
} catch (e, s) {
  Monoscope.instance?.captureException(e, stackTrace: s);
}

addBreadcrumb(crumb) #

Adds to the trail of recent activity attached to subsequent errors. Taps, navigations, HTTP requests and errors add breadcrumbs on their own.

Monoscope.instance?.addBreadcrumb(
  Breadcrumb(type: 'custom', message: 'Applied coupon'),
);

flush() #

Sends everything buffered. Called automatically when the app is suspended.

enable() / disable() #

Turns collection on and off at runtime — for example, behind a consent prompt.

replay.captureFrameNow() #

Captures a replay frame immediately instead of waiting for the next tick. Useful just before an action that navigates away.


Traced HTTP requests #

Outbound HTTP is traced automatically. HttpClient() in dart:io is a factory that consults HttpOverrides, and package:http's IOClient, Dio and raw dart:io all construct their client through it. The SDK installs one override, so a whole app's requests are traced without touching any call site:

// Traced, with no Monoscope types anywhere near it.
final response = await http.get(Uri.parse('https://api.example.com/me'));

Each request becomes a client span carrying a W3C traceparent header, so a Monoscope-instrumented backend joins the same trace — a slow screen can be followed from the tap through the API into the database.

The override chains to any HttpOverrides the app already installed, so proxies, certificate pinning and offline fixtures keep working. Set instrumentGlobalHttp: false to opt out.

A request is only ever traced once. MonoscopeClient wraps IOClient, which builds its HttpClient through the override, so both layers see the same request — the client claims it and the override stands down, rather than producing two nested spans and doubling every latency figure.

For Flutter Web, which has no dart:io, or when you want a single traced client rather than app-wide tracing, use MonoscopeClient:

final client = MonoscopeClient(http.Client());
final response = await client.get(Uri.parse('https://api.example.com/me'));

Query strings are stripped from span attributes and breadcrumbs, since they routinely carry tokens. Monoscope's own ingest endpoints are never traced — an upload that produced a span, whose export produced another upload, would loop without bound.


Choosing an ingest endpoint #

The default, https://otel.monoscopehq.com/v1/traces, is the same collector the browser SDK uses.

Monoscope also exposes an OTLP route on the API host itself, https://api.monoscope.tech/v1/traces, intended for SDKs exporting without a collector in between. Unlike the collector — which accepts every payload with 200 and routes asynchronously — this route validates the API key on the request, so a wrong key fails immediately instead of silently discarding data:

const MonoscopeConfig(
  apiKey: 'YOUR_API_KEY',
  exporterEndpoint: 'https://api.monoscope.tech/v1/traces',
)

If traces do not appear in your project, try this endpoint. Turning on debug: true also surfaces the OpenTelemetry exporter's own diagnostics, including rejected batches, which are otherwise silent.

Metrics have no equivalent route on the API host, so they always go to the collector.


What gets traced automatically #

Once started, the SDK records these without any further wiring:

Span When monoscope.kind
screen One per screen, for its whole lifetime screen
app.start SDK init to the first rendered frame app_start
navigation Every route change navigation
HTTP <METHOD> Every outbound dart:io request http
exception Uncaught and reported errors error
frozen_frame A frame over 700 ms frozen_frame
slow_frame A frame over 16.7 ms (opt-in) slow_frame

One trace per screen #

The screen span is a long-lived root, and anything without a parent is adopted by it. So a trace is "everything that happened on one screen" rather than a single isolated event:

screen · /checkout
├─ app.start · 412ms
├─ HTTP GET /cart
├─ checkout                     ← your own startSpan
│  └─ checkout.completed
├─ exception · StateError
└─ navigation · /checkout → /receipt

Without a root, every error, request and navigation would begin its own trace, and the trace list would be a page of one-span traces. This is the counterpart to the browser SDK's pageview span.

A navigation closes the current screen trace and opens the next, so traces stay bounded to one screen instead of growing for the whole session. A screen the user never leaves is rolled after 30 minutes, because the batch processor only exports a span once it ends. Backgrounding the app also closes the trace, so it ships rather than waiting for the process to be killed.

Spans you create with startSpan keep their real parent — the adoption only applies to spans that would otherwise be orphans. Every span carries screen.id and screen.route alongside session.id and tab.id.


Performance metrics #

The browser SDK reports Core Web Vitals. Those measurements have no meaning in Flutter — there is no layout shift and no largest contentful paint — but the question they answer does: is the app responsive? On mobile that is answered by frame timings and startup time, the same signals Android Vitals and Xcode Organizer report.

Exported as OpenTelemetry metrics, aggregated in memory and shipped every metricsExportInterval:

Metric Type Meaning
app.frame.build.duration histogram (ms) Time building each frame on the UI thread.
app.frame.raster.duration histogram (ms) Time rasterizing each frame on the raster thread.
app.frame.count counter Frames rendered.
app.frame.slow.count counter Frames over 16.7 ms — one frame at 60 Hz.
app.frame.frozen.count counter Frames over 700 ms, long enough to read as a hang.
app.time_to_first_frame histogram (ms) SDK startup to first rendered frame.

Record your own alongside them:

Monoscope.instance?.metrics.recordHistogram('checkout.duration', 240.0);
Monoscope.instance?.metrics.incrementCounter('cart.items.added');

Session replay #

Flutter draws to a canvas rather than a DOM, so replay works by capturing frames.

Once per interval the SDK rasterizes the subtree under MonoscopeWidget, redacts sensitive regions, JPEG-encodes it in a background isolate, and emits it as an rrweb event. The first frame is a full snapshot — a minimal document holding one image — and every frame after it is an incremental mutation swapping that image. Monoscope's replay player is stock rrweb, so recordings play back with no special handling.

What this means in practice:

  • Encoding is off the UI isolate. Rasterizing and encoding never block your frames.
  • Identical frames cost nothing. An idle screen uploads no data.
  • Frames are captured small. Rasterizing happens directly at replayMaxWidth rather than downscaling afterwards.
  • Taps, navigations and logs are recorded as their native rrweb equivalents, so the player draws click indicators, timeline markers and a console panel.

Privacy #

Text fields (EditableText, and so TextField and TextFormField) are redacted by default — a filled rectangle is painted over their bounds before the frame is encoded, so what a user typed never leaves the device. Static labels stay visible, since an entirely grey recording is not worth having.

Widen redaction when a screen warrants it:

const MonoscopeConfig(
  apiKey: 'YOUR_API_KEY',
  maskAllText: true,   // every text run
  maskAllImages: true, // every image
)

Cost control #

  • replaySampleRate records a fraction of sessions. The decision is made once per session, so a recorded session is recorded in full.
  • replayFrameInterval trades fidelity for bandwidth.
  • replayImageQuality and replayMaxWidth set the size of each frame.

Error and crash reporting #

Two hooks cover Dart errors: FlutterError.onError for synchronous framework failures, and PlatformDispatcher.onError for uncaught asynchronous errors. Both are installed by start, and both chain to whatever the app already had, so adding Monoscope does not change whether an app crashes or how it reports failures.

Errors arrive as spans with error.message, error.name, error.stack and a breadcrumbs attribute, matching the browser SDK's schema so web and mobile errors group together. Each error also puts a tick on the replay timeline, so the frames leading up to a failure are one click away.

Native crashes #

Some crashes kill the process before Dart can react, so FlutterError.onError never sees them. Those are captured by native handlers and reported on the next launch — a crash cannot be reported from inside itself, because the process is dying and the network stack is unusable.

Platform Captured
Android Uncaught JVM/Kotlin exceptions — thrown on the platform thread, in a plugin, or in the host Activity.
iOS / macOS Fatal POSIX signals (SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE, SIGTRAP) and uncaught NSExceptions.

They arrive as spans with error.type: native_crash, plus error.source, error.platform and crash.timestamp — the crash happened in an earlier process, so the span's own timestamp is startup time rather than crash time.

Every handler chains to whatever was installed before it, so the OS still writes its own crash report, any other crash reporter still sees the crash, and the process still dies. Swallowing a fatal crash would turn it into a hang, which is worse for the user than the crash.

Verify the whole path end to end:

// Kills the process; the crash is reported on the next launch.
await Monoscope.instance?.crashNativelyForTesting();

Not captured: a SIGSEGV inside Android NDK code. Catching those needs a signal handler compiled with the NDK, which would force an NDK toolchain on every consumer of this package — too high a price for a Dart app, so it is deliberately out of scope. The equivalent signals are caught on Apple platforms, where handlers cost nothing extra.


Sessions #

A session id is generated on first launch and reused while the app is active. After sessionTimeout of inactivity it rotates, and the id is persisted so a quick backgrounding — or a process the OS killed and restarted — continues the same session rather than starting a new one.

Every span carries session.id and tab.id, where tab.id identifies one app launch. Replay uploads carry the same ids, which is what links a trace to the recording it happened in.


Example #

example/ is a small app exercising the whole SDK — traced work, a traced HTTP request, navigation, a masked text field, and buttons that throw both caught and uncaught errors.

cd example
flutter run --dart-define=MONOSCOPE_API_KEY=your_key

Development #

flutter analyze
flutter test

Because replay depends on events that a stock rrweb player must be able to rebuild, there is a check that plays a real recording back through that player. It writes a recording from a widget test, then replays it in jsdom:

flutter test test/rrweb_fixture_test.dart --dart-define=OUT=/tmp/rec.json
cd ../monoscope/web-components && node ../../monoscope-flutter/tool/verify_rrweb.mjs /tmp/rec.json

The script runs from web-components because it borrows that project's @rrweb/replay and jsdom. It samples the session at several points along the timeline — the way someone scrubbing a recording would — and asserts that an image is on screen at each, and that the screen actually changes. A replay that rebuilds once and then freezes passes a single end-state check but fails this one.

To see what was actually recorded, decode the frames to image files:

python3 tool/extract_frames.py session.json out/

Event counts and HTTP status codes cannot tell you whether a replay shows the app. Looking at the frames can, and it is the only check that catches a recording which uploads perfectly and plays back blank.

On a device #

The example app can drive itself, so the SDK can be verified on a real device or emulator without anyone tapping through it. E2E=telemetry sends one of every signal; E2E=crash does that and then crashes natively, so the next launch should report the crash:

cd example
flutter build apk --debug   --dart-define=MONOSCOPE_API_KEY=your_key   --dart-define=E2E=crash --dart-define=MARKER=run-1
adb install -r build/app/outputs/flutter-apk/app-debug.apk
adb shell am start -n com.example.monoscope_flutter_example/.MainActivity
adb logcat | grep -E '\[e2e\]|\[Monoscope\]'

Launch it a second time and the log should contain reported native crash from a previous run, which exercises the entire native crash path: handler installed, record written during a fatal crash, record read and reported after a restart.

Against a real project #

test/live_e2e_test.dart sends real telemetry to real ingest. It is skipped unless a key is supplied, so the normal suite stays offline:

flutter test test/live_e2e_test.dart   --dart-define=MONOSCOPE_API_KEY=your_key --dart-define=MARKER=run-1

Then confirm arrival with the CLI:

monoscope traces search --service monoscope-flutter-e2e --since 30m

License #

MIT

0
likes
150
points
69
downloads

Documentation

Documentation
API reference

Publisher

unverified uploader

Weekly Downloads

Monoscope SDK for Flutter: OpenTelemetry tracing, error and crash reporting, and session replay.

Homepage
Repository (GitHub)
View/report issues

Topics

#opentelemetry #observability #monitoring #session-replay #tracing

License

MIT (license)

Dependencies

fixnum, flutter, http, image, logging, meta, opentelemetry, shared_preferences, uuid

More

Packages that depend on monoscope_flutter

Packages that implement monoscope_flutter