Mobile: Flutter, Dart, and the native SDKs

Four packages, because they answer to different constraints.

Package Depends on Use it when
sentrinel http only Any Dart: Flutter, a CLI, a server-side job
sentrinel_flutter flutter, path_provider, sentrinel A Flutter app
sentrinel_swift Foundation only (SPM) A native iOS / macOS app
sentrinel_kotlin Kotlin stdlib only (Gradle) A native Android / JVM app

The core deliberately takes no Flutter dependency β€” adding one would stop it working outside Flutter, which is where a good part of its use is. Everything needing the framework lives in the integration package instead. The native SDKs follow the same rule: no third-party runtime dependency, just Foundation and the Kotlin stdlib respectively.

What each one covers today:

Flutter / Dart Swift Kotlin
Crashes and errors, release health βœ… βœ… βœ…
Native signal crashes (SEGV, Swift traps) ❌ βœ… ❌ needs JNI
HTTP requests, traces, traceparent βœ… ❌ ❌
Product events, custom metrics, beforeSend βœ… ❌ ❌
Frames, app start, navigation βœ… ❌ ❌

None of these are on pub.dev, CocoaPods or Maven Central. They install from the public repo, Zaga-ltd/sentinel_packages.


Install

Flutter β€” the integration package, which pulls the core in with it:

dependencies:
  sentrinel_flutter:
    git:
      url: https://github.com/Zaga-ltd/sentinel_packages
      path: sentrinel_flutter_integration

Dart without Flutter (CLI, server):

dependencies:
  sentrinel:
    git:
      url: https://github.com/Zaga-ltd/sentinel_packages.git
      path: sentrinel_flutter

Swift β€” Swift Package Manager reads the Package.swift at the repo root, which declares the Sentrinel library. In Xcode: File β†’ Add Package Dependencies…, paste the URL, add Sentrinel to your app target. Or:

.package(url: "https://github.com/Zaga-ltd/sentinel_packages.git", branch: "main"),
// in your target:
.product(name: "Sentrinel", package: "sentinel_packages"),

Kotlin β€” through JitPack, which builds the sentrinel_kotlin directory (the repo's root jitpack.yml says how):

// settings.gradle.kts β†’ dependencyResolutionManagement.repositories
maven("https://jitpack.io")

// app/build.gradle.kts
implementation("com.github.Zaga-ltd.sentinel_packages:sentrinel_kotlin:main-SNAPSHOT")

Pin a commit or tag instead of main-SNAPSHOT for a release build. Without JitPack, clone the repo and includeBuild("../sentinel_packages/sentrinel_kotlin") in settings.gradle.kts, then depend on dev.sentrinel:sentrinel_kotlin:0.2.0.


Flutter: the whole setup

void main() => SentrinelFlutter.run(
      options: SentrinelOptions(
        serverUrl: 'https://api.sentrinel.dev',
        appName: 'mobile-app',
        env: 'prod',
        release: '1.4.2',
        apiKey: const String.fromEnvironment('SENTRINEL_API_KEY'),
        // Your own backends. Only these receive traceparent and the
        // x-sentrinel-consumer / x-sentrinel-device headers.
        tracePropagationTargets: ['api.example.com'],
      ),
      app: () => runApp(const MyApp()),
    );

That single call starts a guarded zone, finds a storage directory that survives a restart, installs both error handlers, ends the session and flushes whenever the app is backgrounded, reports phone vs tablet, and tracks frames and app start. Calling it again reconfigures without stacking handlers.

runApp goes inside the app callback rather than after the call. Asynchronous errors are only caught within the zone, so calling runApp outside it silently misses most of them.

Then name the user, and add the navigator observer:

Sentrinel.identify(user.id);   // after sign-in β€” see "Who your traffic belongs to"

MaterialApp(navigatorObservers: [SentrinelNavigatorObserver()])

Values worth getting right

release β€” crash-free rate is per release. Without it every build is unknown and a regression is invisible, which is the entire point of the page.

The key should be a mobile key (API Keys β†’ Generate β†’ Mobile app). It ships inside your bundle, which is public, so it is issued to send only what a phone sends β€” a leaked one cannot post a session replay, reach the database collector, or read anything. A server key works too, but exposes more if it leaks.

env β€” must match the environment the API key was issued for. Ingest checks env against the key and answers 403 on a mismatch, which the SDK reports once at startup and then goes quiet. A wrong value looks exactly like "monitoring is fine, we just have no traffic."

appName and module β€” the app is the whole project, not the phone. Use the same appName as your backend, a mobile key issued for that app, and module: 'mobile'. The phone's requests, errors and spans then land beside the backend's, and a tap can be followed into the server work it caused as one trace.

tracePropagationTargets β€” empty by default: no trace ids and no user or install ids go to hosts you did not list. A String is a host (api.example.com matches it and its subdomains; *.example.com only subdomains; a value with :// is a URL prefix), a RegExp is matched against the full URL. On web, same-origin calls always qualify.


What gets captured

Errors and crashes

Source Mechanism Reported as
Async errors escaping to the zone runZonedGuarded unhandled error; session errored
Flutter build/layout/paint errors FlutterError.onError unhandled error; session errored (silent ones skipped)
Errors reaching the engine PlatformDispatcher.onError unhandled error; session errored
Errors on isolates you spawn Isolate.spawn(onError:) unhandled error; session errored β€” one line needed
captureError(e, s, fatal: true) your call crash; written to disk; session crashed
Uncaught ObjC exceptions, signals, Swift traps (native iOS) sentrinel_swift crash
Uncaught Kotlin/Java exceptions (native Android) sentrinel_kotlin crash

A Flutter app keeps running after an unhandled Dart error β€” an overflow, a failed image load and a throwing build method show an error widget; an unawaited future's error ends that future. So these are reported as unhandled errors, sent within about a second, and they mark the session errored, not crashed. Counting them as crashes made the crash-free rate meaningless.

A fatal error is the app saying it is about to die. It is written to disk before captureError returns and also sent immediately; the disk copy is removed once the server acknowledges it, so it is never delivered twice. If the process dies first, the next launch sends it β€” and a replay that meets a dead network is kept and retried, not deleted because it was read. Where there is no disk (Flutter web, persistCrashes: false) a fatal error goes straight to the network.

Isolates need one extra argument

Isolate.spawn does not inherit the spawning isolate's error listeners. A worker started the ordinary way prints its stack to stderr and reports nothing β€” from the dashboard a failed background job looks identical to one that never ran. Pass the port:

import 'dart:isolate';
import 'package:sentrinel/sentrinel.dart';

await Isolate.spawn(parseLargePayload, bytes, onError: isolateErrorPort);

isolateErrorPort is a top-level getter, null on web and before init. Isolate.spawn accepts a null onError, so it is safe to pass unconditionally.

Every report carries the OS and version, locale, core count, the install id (device.id), the session id, the screen, and the last 25 breadcrumbs. The Issues page renders all of it: the mechanism that caught it, whether it was handled, the device, and the trail as an expandable list.

Breadcrumbs fill themselves from HTTP requests and navigation. Add your own for taps and business events:

Sentrinel.addBreadcrumb('tapped pay', category: 'ui', data: {'amount': 42});

Release health and the lifecycle

One session per foreground stretch, which is the denominator crash-free rate needs. See GUIDE.md for how to read the page.

Status Meaning
ok Running, or ended cleanly
errored Survived, but reported an error
crashed A fatal error was written before the process died
abnormal Ended without a clean shutdown and without a crash report β€” force-quit, OOM kill, flat battery

A session only gets worse. abnormal is kept apart from crashed deliberately: counting a user swiping the app away against your release would make the number worthless.

Backgrounding ends the session. When the app goes to hidden, paused or detached, the Flutter package ends the session with its duration and flushes; back within 30 seconds it is the same session, after that a new one. The OS kills backgrounded apps without notice β€” ending the session first is what keeps those kills from reading as abnormal. From plain Dart, call Sentrinel.onBackground() / onForeground() yourself. The Swift SDK does the same on iOS automatically; on Android, wire Sentrinel.onBackground() to ProcessLifecycleOwner (see the Kotlin README).

Performance

Both arrive as structured logs with category: performance, so they are searchable and available in the field explorer.

Requests, and the trace that joins them

SentrinelHttpClient records every call. For your propagation targets it sends traceparent, so the backend plugin continues the same trace rather than starting a new one β€” a tap and the server work it caused land on one timeline.

final client = Sentrinel.httpClient();
await client.get(Uri.parse('https://api.example.com/orders'));

Using Dio? Route it through the same client with the Dio team's dio_compatibility_layer β€” no Sentrinel-specific adapter needed:

final dio = Dio()..httpClientAdapter = ConversionLayerAdapter(Sentrinel.httpClient());

Client spans are sent in batches (one post per flush, not one per span), with at most four posts in flight.


What a recorded call carries

Field Where it comes from
route The path with ids collapsed β€” /orders/{id}, /files/{uuid}.jpg
host The host that was called
consumerIdentifier The signed-in user, or guest:<install id>
attributes.device.id The install id
traceId The same trace the backend continues, via traceparent

route is computed by the server's own rules β€” the SDK carries a port of the API's normaliseRoutePath, tested against the API's cases: UUIDs become {uuid}, numbers {id}, 16+ hex characters {hash}, dates {date}, and opaque tokens {id} only when they carry a digit or mixed case. Rollups, consumer rows and HTTP errors all group by it, so one route is one endpoint row. Words like call-histories or facade are never collapsed.

URLs lose their secrets. Span attributes and transport-error messages carry the URL without query string, fragment or userinfo β€” that is where tokens, emails and one-time codes live. The request row keeps the path.

Log lines carry consumerIdentifier too, so "everything this user did" finds them without joining through a request that may already have expired.

Filtering: beforeSend

Sentrinel.init(
  // …
  beforeSend: (kind, record) {  // kind: request Β· error Β· log Β· span Β· event
    if (kind == 'log' && record['category'] == 'debug') return null;  // drop
    return record;                                                    // or rewrite
  },
);

It runs before a crash report is written to disk, so what it removes is never stored. A hook that throws drops the record rather than sending it unfiltered.


Who your traffic belongs to

The Consumers page answers "which of my users is this happening to". It is driven by one value.

Every install has a stable id, Sentrinel.deviceId (the same as anonymousId), minted once and written to disk. Until someone signs in, the install's traffic is filed under guest:<deviceId> β€” each install its own consumer. You do not need to invent guest ids. Then:

// After sign-in, at launch when a saved session is restored, and after the
// profile changes. Requests, logs, errors and events are filed under them.
Sentrinel.identify(user.id, properties: {'plan': user.plan});

// On sign-out β€” back to guest:<deviceId>.
Sentrinel.identify(null);

The wrapped HTTP client sends x-sentrinel-consumer and x-sentrinel-device to your propagation targets, so the backend SDKs file server-side errors under the same person and install. The Swift and Kotlin SDKs expose the same two headers (Sentrinel.identityHeaders) for your own networking code.

consumerIdentifier at init and setConsumer(…) pin a value β€” a tenant, a kiosk, an API client β€” until identify replaces it. Prefer identify. The old pattern, consumerIdentifier: 'mobile_android', filed every signed-out user on a platform as a single consumer.

On web there is no filesystem, so the install id lasts one page load. Use the browser SDK when web analytics matter; it has real storage.

The device

Every events batch carries os, osVersion, deviceType and deviceModel, and every post a User-Agent like sentrinel.dart/0.3.0 (Android 14; Mobile) β€” the server used to read Dart/3.x (dart:io) and file every phone under "desktop". dart:io knows the OS (and the iOS version); feed the rest from device_info_plus:

final info = await DeviceInfoPlugin().androidInfo;
Sentrinel.setDeviceInfo(model: info.model, osVersion: info.version.release);

Product events and funnels

Errors tell you what broke. Events tell you what people did.

Sentrinel.screen('Cart');
Sentrinel.track('checkout_started', properties: {'cart_value': 42, 'tier': 'pro'});

// When they sign in:
Sentrinel.identify('user_42');

Sentrinel.track('purchase_completed', properties: {'revenue': 129.0});

These feed the Product pages β€” funnels, retention, top screens β€” and are deliberately not logs. A log line is written for a human to read while debugging; an event is a row in a funnel, counted and grouped.

Call Kind Use it for
track(name, properties:) track A funnel step, a feature used, a purchase
screen(name) screen The mobile pageview
identify(userId) identify Attaching a real person β€” and attributing their requests, logs and errors to them
setConsumer(id) β€” Pinning something that is not the signed-in user: a tenant, a kiosk

identify() sends both ids in the same payload, so the server can stitch what someone did before signing in to their account β€” which is exactly what makes a signup funnel measurable.

Keep properties small

The server caps them at 50 keys and 4KB per event, and a batch at 500 events. Properties are dimensions you group by β€” tier, cart_value, plan β€” not a payload. Anything larger is a log. Values JSON cannot hold are converted, not fatal: a DateTime is sent as ISO-8601, NaN as null, an enum by name.


Custom metrics

The numbers only your app knows β€” videos started, seconds buffered, items added to a cart. Same idea as the backend counting tokens, and the same storage.

Sentrinel.count('video.started', 1, {'quality': 'hd'});
Sentrinel.gauge('cart.items', cart.length);
Sentrinel.histogram('video.time_to_first_frame', ms, {'cdn': 'edge-1'}, 'ms');
Kind Means Read back as
count A running total β€” sales, retries, starts Sum over the window
gauge A level that moves both ways β€” queue depth, cache size The last reading
histogram A distribution β€” durations, sizes p50 / p95 / p99

Increments fold in memory and leave as one row per (name, labels) per flush, not one row per call. That is what makes count() safe inside a build method or a scroll listener.

Labels are the dimensions you group by, so they are bounded on purpose: at most 2,000 distinct series and 512 samples per histogram window, with the samples reservoir-sampled past that. Put a user id in a label and you will hit the series cap immediately β€” that is a log, not a metric.

Needs a mobile (or server) API key, and a ClickHouse telemetry store. A deployment on Postgres refuses custom metrics with a 501 rather than discarding them quietly.


Native apps: Swift and Kotlin

Both report crashes, handled errors and sessions in the same shapes as the Flutter SDK, so native and Dart crashes share the same Issues and Release health pages. Both have the same identity model: a persisted install id, guest:<install id> until identify(user.id), device.id on every error.

// Swift β€” in application(_:didFinishLaunchingWithOptions:)
Sentrinel.start(options: .init(
    serverUrl: URL(string: "https://api.sentrinel.dev")!,
    appName: "shop",
    env: "prod",
    apiKey: "<a Mobile key>",
    module: "ios",
    release: "1.4.2"
))
Sentrinel.identify(user.id)
// Kotlin β€” in Application.onCreate()
Sentrinel.start(
    Sentrinel.Options(
        serverUrl = "https://api.sentrinel.dev",
        appName = "shop",
        env = "prod",
        apiKey = BuildConfig.SENTRINEL_API_KEY,
        module = "android",
        release = BuildConfig.VERSION_NAME,
    ),
    storageDirectory = filesDir,   // required on Android for crashes to survive
)
Sentrinel.identify(user.id)

Neither sends traces, product events or custom metrics yet. See their READMEs in the public repo for everything else.


Not covered


Seeing it without building an app

API=https://api.sentrinel.dev KEY=snt_mobile_… APP=mobile-app \
  bun run examples/mobile-telemetry.ts

Sends the same shapes the SDK does β€” two releases where one is measurably worse, crashes with breadcrumbs and device context, and frame/app-start records.

See also


Troubleshooting

TROUBLESHOOTING.md has a mobile section covering the usual causes: a missing storagePath, guard() without the Flutter handlers, a missing release, and sessions that all report as abnormal. Two newer ones: