Early accessBy invitation, and the SDKs aren't published yet.Ask for an invitation
Skip to Content
Docs

Flutter

Structured logs from your Flutter app on iOS and Android, over the native Lyrelog SDKs.

iOS and Android apps, over the native SDKs

The Flutter SDK is the Dart package lyrelog, a plugin for iOS 16 and Android 7.0 (API 24) or later, built with Flutter 3.50. It is a thin Dart layer over the native SDKs, the Swift SDK on iOS and the Android SDK on Android, so the queue on disk, native crashes, sending in the background, sessions, consent and verified events work as they do there. On top, it reports Dart errors nobody caught and names screens from your navigator.

Internal preview: this package isn't published yet. Until it is, flutter pub add lyrelog finds nothing: it isn't on pub.dev, and the repository is private and has no release yet.

Install

flutter pub add lyrelog

Or in pubspec.yaml:

dependencies:
  lyrelog: ^0.1.0

iOS setup

  • The plugin is a Swift package, so your app builds it with Swift Package Manager, which Flutter uses by default. There is no CocoaPods version.
  • Set the app's minimum to iOS 16: in Xcode, the Runner target, General, Minimum Deployments (IPHONEOS_DEPLOYMENT_TARGET = 16.0). Flutter's default is lower, and the build stops with a message saying so.

Android setup

  • Flutter's defaults work: compileSdk 36 and Kotlin 2.2 or newer. minSdk can stay at 24.

The library adds the INTERNET permission to your app's manifest.

Start

Start once, as early as possible: in main, before runApp. A second call while it runs is ignored. start calls WidgetsFlutterBinding.ensureInitialized() itself, so it can come first, and nothing needs to wait for it: what you log after start reaches the native SDK after it. Events logged before start are ignored, but setUser and setConsent called before start are kept and applied when it runs.

import 'package:flutter/widgets.dart';
import 'package:lyrelog/lyrelog.dart';

void main() {
  Lyrelog.start(const LyrelogConfiguration(
    apiKey: 'lyr_ing_...', // ingest-only: it can append events, never read them
  ));
  runApp(const MyApp());
}

Events go to https://ingest.lyrelog.com. Pass endpoint only to send them somewhere else. It is the base URL (a pasted .../v1/events:batch path is stripped) and must be https; plain http works only for localhost, 127.0.0.1 or ::1, and on the Android emulator for 10.0.2.2 (see In development and tests). With any other endpoint nothing is sent and the events stay on the device.

Log events

One function per level: trace, debug, info, notice, warning, error, critical, or log(level, message, ...) with a LogLevel.

Lyrelog.info('checkout_done', attrs: {'items': 3, 'latency_ms': ms});
Lyrelog.error('payment_declined', category: 'checkout',
    attrs: {'code': 51}, payload: {'response': raw});

Attributes are a Map<String, Object?>: strings, numbers, booleans, null, lists and nested maps up to 4 levels. A DateTime is sent as ISO 8601 text, a Duration as milliseconds, an enum as its name, and anything else as its toString(). The payload is any value of those kinds, for the detail you only read when you open one event.

Loggers for each area

A logger stamps its category on every event, like a log tag. It has every level, plus log and captureError. It is cheap to make and keep, and logs into whatever SDK is running when it is called.

final sync = Lyrelog.logger('sync');
sync.warning('sync_conflict', attrs: {'records': 2});

Users

Lyrelog.setUser(account.id); // attached to every following event
Lyrelog.setUser(null);       // on sign-out

await Lyrelog.sessionId() gives the current session id, for example to show in a support screen.

The user id isn't saved between launches: call setUser again on each launch, once you know who the person is.

Screens

Say where the person is. Lyrelog logs screen_viewed (area navigation) with the screen before and the seconds spent on it, and tags every following event with a screen attribute.

Add LyrelogNavigatorObserver to your app's navigator, and every page route that comes to the top is a screen, named by its route name:

MaterialApp(
  navigatorObservers: [LyrelogNavigatorObserver()],
  routes: {
    '/': (_) => const HomePage(),
    '/settings': (_) => const SettingsPage(),
  },
)

It works with any Navigator, so also with a router that takes observers (with go_router, GoRouter(observers: [LyrelogNavigatorObserver()], ...)). Going back to a page logs it again, since it is the screen once more. Dialogs, bottom sheets and menus don't change the screen, and routes without a name are skipped. Change either:

LyrelogNavigatorObserver(
  nameExtractor: (settings) => settings.name?.replaceFirst('/', ''), // null or '' skips the route
  routeFilter: (route) => route is PageRoute,                         // which routes are screens
)

Or call it yourself:

Lyrelog.screen('Settings');

The event carries screen, previous_screen and seconds_on_previous. Calling screen again with the same name logs nothing. screen takes extra attrs for the screen_viewed event. Turn the tagging off with attachScreen: false.

Errors you catch

try {
  await store.purchase(product);
} catch (e, s) {
  Lyrelog.captureError(e, stackTrace: s, category: 'store');
}

It sends the exception event every SDK sends: level error, the attributes error_type (the runtime type) and error_message (its toString()), and a payload with the description and up to 60 frames of the stack. Without a stackTrace, the frames are an Error's own stack, if it has one. attrs adds your own; level changes the level. Each logger has captureError too.

Errors and crashes

Dart errors nobody catches

start reports them on its own (captureErrors, on by default), as exception events with handled: false and a mechanism that says where Flutter handed them over:

mechanismFromThe payload also has
flutter_errorFlutterError.onError: errors while building, laying out or painting widgets, and in gesture callbackslibrary (widgets library) and context (building MyWidget)
platform_dispatcherPlatformDispatcher.instance.onError: errors in async code, timers and futures nobody awaited

The handlers that were there before keep running, after Lyrelog's, and PlatformDispatcher.onError answers what the earlier one answered (without one, Flutter still prints the error). If you set handlers of your own, set them before start, or call captureError from them.

At most 10 of these are sent a minute, and the same error (its type, message and top frame) only once every 10 seconds, so a layout error that repeats on every frame sends one event. Errors that Flutter marks as silent, which it doesn't report in release builds either (an image that failed to load, for example), are left out.

A Dart error doesn't end a Flutter app, so these are exception events, never app_crashed.

If your app runs in a zone of its own, report the zone's errors the same way:

runZonedGuarded(() => runApp(const MyApp()), (error, stack) {
  Lyrelog.captureError(error, stackTrace: stack, handled: false, mechanism: 'zone');
});

Native crashes

Crashes of the app itself come from the native SDKs (captureNativeCrashes, on by default). They are sent on the next launch, at the time they happened, in the diagnostics area:

PlatformEventsFrom
iOSapp_crashed (critical), app_hung (error), cpu_overuse, disk_write_overuse, slow_launch (warnings)MetricKit, as on the Swift page
Androidapp_crashed (critical) with handled: false and mechanism: uncaught_exceptionUncaught JVM exceptions, as on the Android page

On Android, native (C or C++) crashes and ANRs aren't reported.

Obfuscated builds

With flutter build --obfuscate --split-debug-info=<dir>, type names in error_type and the frames are obfuscated. Keep the symbols the build writes and run flutter symbolize with them on the frames to read them.

Environments and platform

The native SDK picks the environment when it starts:

  • iOS: development for a debug build, any build on the simulator, or a build with an embedded provisioning profile (development and ad hoc signing); testflight for a TestFlight build; production otherwise. Then StoreKit's answer, as on the Swift page.
  • Android: development when the app is debuggable (every debug build), production otherwise.

Your own flutter run builds send development, while the dashboard opens on production: pick development in the top bar to see them.

The platform is the OS, ios or android, so one project holds both and the dashboard can filter by each. Override either in the configuration:

LyrelogConfiguration(
  apiKey: key,
  environment: isInternalTester ? 'internal' : null, // null = detected
  platform: null,
)

Any name works: lowercase letters, digits, - and _, up to 32. Other text is turned into a valid name (Staging EU becomes staging-eu).

Lyrelog.start(LyrelogConfiguration(apiKey: key, consent: Consent.pending));
// later, when the person chooses:
Lyrelog.setConsent(Consent.granted); // sends, including what was kept while pending
Lyrelog.setConsent(Consent.denied);  // deletes everything and stops recording

Consent.pending keeps events on the device without sending them. Nothing is uploaded unless consent is granted, including what an earlier launch left. Starting with Consent.denied deletes anything still queued from an earlier launch and the install id, and records nothing. A setConsent before start wins over the configuration's consent.

Consent isn't saved between launches: store the person's choice yourself and pass it to start each time.

A complete app

Start with the stored consent, set the person when they sign in and name screens from the navigator:

import 'package:flutter/material.dart';
import 'package:lyrelog/lyrelog.dart';
import 'package:shared_preferences/shared_preferences.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final prefs = await SharedPreferences.getInstance();
  final consent = switch (prefs.getString('diagnostics')) {
    'granted' => Consent.granted,
    'denied' => Consent.denied,
    _ => Consent.pending,
  };
  Lyrelog.start(LyrelogConfiguration(apiKey: 'lyr_ing_...', consent: consent));
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) => MaterialApp(
        navigatorObservers: [LyrelogNavigatorObserver()],
        routes: {
          '/': (_) => const HomePage(),
          '/sign-in': (_) => SignInPage(onSignedIn: signedIn),
        },
      );
}

void signedIn(Account account) {
  Lyrelog.setUser(account.id);
  Lyrelog.info('signed_in', category: 'auth');
}

Future<void> choose(bool allowed) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString('diagnostics', allowed ? 'granted' : 'denied');
  Lyrelog.setConsent(allowed ? Consent.granted : Consent.denied);
}

Flush and stop

Going to the background already sends: on iOS inside a background task, on Android when the app's Activity stops. So you rarely need to.

await Lyrelog.flush(); // write everything to disk and send, waiting up to 5 seconds
await Lyrelog.stop();  // send what's queued (up to 2 seconds), then stop

flush returns true when it finished in time (timeout: changes the wait), and respects a Retry-After the server asked for: it doesn't send sooner. After stop, start can be called again.

In development and tests

In widget and unit tests, don't call Lyrelog.start: anything logged before start is ignored, so the rest of your code runs unchanged. On a platform the plugin doesn't support (web, desktop), every call does nothing and never throws.

mirrorToConsole: true also prints every event to the native log while you work: Xcode's console on iOS, logcat (tag Lyrelog) on Android.

Debug builds send environment development. To send to an endpoint running on your computer:

  • iOS simulator: use http://127.0.0.1 and its port. The simulator shares your computer's network, and no App Transport Security exception is needed for it.
  • Android emulator: use http://10.0.2.2 and its port (10.0.2.2 is your computer, as the emulator sees it), in the debug build only:
    • Allow plain http to 10.0.2.2. Android blocks it unless the app allows it: add a network security config to the debug build (android/app/src/debug) that permits cleartext for that one address.
    • On Android 17, an app targeting API 37 also needs ACCESS_LOCAL_NETWORK to reach a private address like 10.0.2.2; without it the connection just times out. Declare the permission in the debug manifest (android/app/src/debug/AndroidManifest.xml) and grant it: adb shell pm grant <your.app> android.permission.ACCESS_LOCAL_NETWORK.

Keep the key out of your sources with --dart-define-from-file, for example flutter run --dart-define-from-file=lyrelog.local.json and String.fromEnvironment('LYRELOG_KEY'), with that file ignored by git.

This is only for local development. The hosted ingest is a public https address and needs none of this.

Verified events

A verified event is one that can't have been sent by someone who copied the public ingest key out of an app or a web page. What that proves, and what it doesn't, is on Verified events.

The native SDKs verify the app on real devices (attest, on by default), and nothing changes in your Dart code. Set up each platform the app ships on:

  • iOS, with Apple's App Attest (verified_by is app_attest):
    • Add the App Attest capability to the Runner target in Xcode (Signing & Capabilities), the entitlement com.apple.developer.devicecheck.appattest-environment. Set it to production for App Store and TestFlight builds; without it Apple uses the development environment.
    • Add your App ID, the Team ID, a dot and the bundle id (ABCDE12345.com.example.app), in Project settings, under Verified events from your Apple apps.
  • Android, with Key Attestation (verified_by is key_attestation): in Project settings, under Verified events from your Android apps, add your package and the SHA-256 fingerprint of each certificate that signs builds that send events: Play's app signing key (Play Console, Test and release, App integrity) and, for builds you sign yourself, the one ./gradlew signingReport shows (run it in your app's android folder).

To turn it off on both:

Lyrelog.start(const LyrelogConfiguration(apiKey: 'lyr_ing_...', attest: false));

Sending never waits for it: until the app has a token, and whenever anything fails, events are sent unverified. Until a platform is set up in the project, the SDK stops trying for that launch.

  • The iOS simulator and Android emulators never verify.
  • A device the server refuses (a rooted phone, an unlocked bootloader, a certificate the project doesn't list) sends unverified events; Android tries again a day later.
  • Denying consent deletes the attested key's record on both platforms.

Before making the project accept only verified events from ios or android, check in the explorer that your real users' events arrive verified: events from older versions, simulators, emulators and refused devices would be held back with a 425. Never put a server key (lyr_srv_...) in an app: anything shipped in an app can be read.

To check, open the explorer: an opened event says it under Context, in its Sender line: Verified, App Attest, Verified, Key Attestation or Not verified, public key.

Configuration

OptionDefaultMeaning
apiKeyrequiredThe project's ingest key
endpointhttps://ingest.lyrelog.comThe base URL; a pasted /v1/... path is stripped. https only, http only for localhost and the Android emulator's 10.0.2.2
consentConsent.grantedpending, granted or denied
minimumLevelLogLevel.debugEvents below it are dropped before they reach the device's queue
flushInterval15 sHow often the uploader runs in the foreground
maxBatchBytes512 KiBA batch closes at whichever limit comes first (kept within 4 MiB)
maxBatchEvents500At most 2,000
maxDiskBytes20 MBCap on the queue on disk, oldest first
maxEventAge7 daysOlder queued events are dropped
sessionTimeout30 minIdle time that starts a new session
environmentdetectedAny valid name, or null
platformthe OSAny valid name, or null
redactedKeysnull: defaultRedactedKeysKey names to redact; your list replaces the defaults, an empty list turns it off
captureErrorstrueReport Dart errors nobody caught
captureNativeCrashestrueiOS: MetricKit crashes, hangs and overuse reports. Android: uncaught JVM exceptions. Sent on the next launch
attachScreentrueTag events with the current screen
attesttrueVerify events with App Attest or Key Attestation once the project is set up
mirrorToConsolefalseAlso print every event to the native log (Xcode's console, logcat)
pauseUploadsInLowPowerModetrueiOS only: periodic uploads pause; going to the background still sends

Delivery and limits

Delivery is the native SDK's, the same as in a Swift or Kotlin app:

iOSAndroid
Never blocksA call hands the event to the native SDK and returns; one background writer puts it on disk and never waits on the network.The same.
Survives kills and offlineA queue in Library/Caches, capped at 20 MB and 7 days. The system may purge Caches when the device is short of space, and the waiting events go with it.A queue in noBackupFilesDir/lyrelog, capped at 20 MB and 7 days, never in a backup, so a restored phone doesn't resend another device's events.
When it sendsEvery 15 s in the foreground (paused in Low Power Mode), and when the app goes to the background, inside a background task.Every 15 s while the app's Activity is started, and when it goes to the background. In the background nothing runs on a timer: what's left goes on the next launch or the next time the app comes to the front.
BatchesUp to 500 events or 512 KiB per request, gzipped. An event over 1 MiB once encoded is dropped and counted.The same.
Retries1 s doubling to 5 min, with full jitter, honoring Retry-After. Any other 4xx drops the batch, a 3xx (a redirect, never followed) drops it, and a revoked key (401, 403) stops sending until the next launch and keeps the events. A batch the server keeps failing while others go through goes to the back, then is dropped.The same.
Monthly quotaWhen a Free organization has used its month's events, the server answers 429. Events stay in the queue on disk and go out once the server takes them again, within the 20 MB and 7 day caps. One warning in the unified log (subsystem com.lyrelog.sdk).The same, the warning in logcat (tag Lyrelog).
Drops are visibleEvents lost to the caps become one lyrelog_events_dropped warning (area lyrelog) with the count.The same.
Its own problemsA wrong endpoint, a refused key or rejected lines go once per launch to the unified log, subsystem com.lyrelog.sdk, at debug level.The same in logcat, tag Lyrelog, at debug level.
ContextApp id, version, build, OS, device model (iPhone18,1), locale, platform ios, session id (new after 30 min idle) and install id. sdk is lyrelog-flutter/0.1.0 lyrelog-swift/0.1.0.App id (the package name), version name, version code, the Android version, the device (Google Pixel 9), locale, platform android, session id and install id. sdk is lyrelog-flutter/0.1.0 lyrelog-android/0.1.0.
SecretsValues under keys whose name is or ends with authorization, cookie, password, token, secret, apikey and the rest of the shared list become "[redacted]", at any depth, before anything is cut.The same.
LimitsLong strings cut on a character boundary, extra attributes counted in lyrelog_dropped_attrs, payloads over 64 KiB summarized as {"lyrelog_truncated": true, "bytes": N, "preview": "..."}.The same.

Change the redaction list with redactedKeys: your list replaces the defaults, and an empty list turns redaction off. To add to it:

Lyrelog.start(const LyrelogConfiguration(
  apiKey: 'lyr_ing_...',
  redactedKeys: [...LyrelogConfiguration.defaultRedactedKeys, 'pin'],
));

App Store privacy and Play data safety

The Swift SDK's privacy manifest (PrivacyInfo.xcprivacy) ships inside the app, and Xcode merges it into the app's privacy report, as on the Swift page.

For the App Store privacy label, declare what your app sends through Lyrelog:

  • Diagnostics: Crash Data, Performance Data, Other Diagnostic Data (App Functionality).
  • Identifiers > Device ID: the install id, a random UUID that isn't the advertising id, isn't backed up and is deleted on a denial (App Functionality). Not linked to the person unless you also call setUser.
  • Identifiers > User ID, linked to the person: only if you call setUser.
  • Usage Data > Product Interaction: if you log screens (screen_viewed) or taps.

For the Play Console's data safety form:

  • App info and performance: Crash logs, Diagnostics (App functionality, and Analytics if you use it that way). Collected, not shared.
  • Device or other IDs: the install id, as above.
  • App activity > App interactions: if you log screens or taps.

On both, anything else your attrs or payload carry (emails, purchases...) goes under its own category. Data is encrypted in transit (https). The server adds the country of the sending address; the address itself isn't stored.