# Sending Logs: Flutter

`tailcove_flutter` sends logs and Dart and Flutter errors from your Flutter app. It works on iOS, Android, macOS,
Windows and Linux; on the web it sends but cannot keep unsent lines across reloads.

## The app key

A mobile app cannot keep a secret, so it does not use the source's ingest token. It uses an **app key**, which is
public by design: it only works for the **app ids** you allow (your iOS bundle id and Android package name, such as
`com.acme.shop`, or `com.acme.*`), and it has a rate limit of its own, so a copied key cannot use up your source's
quota. Generate it and list your app ids under **Mobile apps** in your source's **Settings** tab. See
[React Native](https://tailcove.dev/docs/sending-logs/react-native#the-app-key) for the details, which are the same.

## Install

```bash
flutter pub add tailcove_flutter
```

## Start the client

Wrap your `runApp` call. `Tailcove.runApp` sets up Flutter, starts the client and hooks Flutter's error handlers, then
runs your app:

```dart
import 'package:flutter/widgets.dart';
import 'package:tailcove_flutter/tailcove_flutter.dart';

void main() {
  Tailcove.runApp(
    const TailcoveOptions(
      appKey: '<your app key>',
      appId: 'com.acme.shop',
      release: '2.4.0',
      environment: 'production',
    ),
    () => runApp(const MyApp()),
  );
}
```

Then log from anywhere:

```dart
Tailcove.instance.info('Checkout opened', {'items': 3});
Tailcove.instance.error('Payment failed', {'provider': 'stripe'});
```

Level methods: `debug`, `info`, `notice`, `warning`, `error`, `critical`, `alert`, `emergency`, or
`log(TailcoveLevel.info, message, context)`. If you set up Flutter yourself, call `Tailcove.init(options)` after
`WidgetsFlutterBinding.ensureInitialized()` instead.

`appId` must be one of the app ids allowed for the key. To read it from the device, use `package_info_plus`
(`PackageInfo.fromPlatform()` then `packageName`) before starting the client.

## Errors

Two kinds of error are reported automatically, each as an `error` line with the exception (class, message, location
and stack) and the last 20 log calls before it as breadcrumbs, grouped into [issues](https://tailcove.dev/docs/issues):

- **Flutter errors**, through `FlutterError.onError`: build, layout and paint failures, with the library and what
  Flutter was doing (`library`, `while`).
- **Uncaught Dart errors**, through `PlatformDispatcher.instance.onError`: async errors nothing caught.

The handlers that were set before keep running, so the red error screen and console output in debug builds stay as
they were.

```dart
try {
  await placeOrder();
} catch (error, stack) {
  Tailcove.instance.captureException(error, stackTrace: stack, context: {'orderId': orderId});
}
```

Add route changes to the breadcrumb trail with the navigator observer:

```dart
// On your MaterialApp, CupertinoApp or WidgetsApp:
navigatorObservers: [TailcoveNavigatorObserver()],
```

In an obfuscated release build (`--obfuscate`), stack frames are not readable until they are symbolized with the
build's symbols file; Tailcove does not do that yet. Native crashes in the iOS or Android host code are outside Dart:
add the Sentry Flutter SDK with your source's DSN for those ([Sentry SDKs](https://tailcove.dev/docs/sending-logs/sentry)).

## Users and context

```dart
Tailcove.instance.setUser(user.id);            // only the id is sent
Tailcove.instance.setContext({'plan': 'pro'}); // on every following line
Tailcove.instance.setUser(null);               // on sign-out
```

Every line also carries `app.id` and `app.version`, `os.name` and `os.version`, the Dart version, `environment`, and a
`session_id` that is new on each launch. The `host` is the OS name (`ios`, `android`, ...).

## Secrets stay in the app

Since 0.2.0 passwords, tokens and API keys are masked on the device, before a line is queued, so they never cross the network. That covers the message, every string in the context, and the errors the client reports for you, stack included.

- A context field whose name says it holds a secret, such as `password`, `db_password`, `apiKey`, `x-api-key`, `client_secret`, `Authorization` or `cookies`, has its whole value replaced with `[redacted]`, nested objects included. `null`, `true` and `false` stay, so `has_password: true` still reads fine.
- In the message and in every other string, the value after a secret name becomes `[redacted]`: `password=hunter2`, `?token=abc123`, `"api_key": "..."`, `Authorization: Bearer ...`. A colon in plain prose doesn't count, so `password: too short` stays as written.
- Credentials you can tell by their shape become `[key]` wherever they appear: JWTs, AWS access key ids, Stripe secret keys, GitHub, Slack and Google API tokens, and private key blocks.

Names that only look similar, like `max_tokens`, `token_count` or `password_changed_at`, aren't touched. The rules are the ones Tailcove uses for [recommended masking](https://tailcove.dev/docs/transform-rules) on the server, so a line reads the same whichever side masked it, and masking twice changes nothing.

Add your own field names with `secretKeys`. Names are compared whole, ignoring case, `-`, `_`, `.` and spaces, so `customer_ssn` also covers `customerSsn` and `Customer-SSN`. Set `maskSecrets` to false only if you mask everything yourself.

`beforeSend` gets each line after masking. Change it and return it, or return `null` to drop it:

```dart
TailcoveOptions(
  appKey: '<your app key>',
  appId: 'com.acme.shop',
  secretKeys: ['customer_ssn'],
  beforeSend: (line) {
    if (line['level'] == 'debug') return null;
    (line['context'] as Map<String, Object?>).remove('cart');
    return line;
  },
)
```

If `beforeSend` throws, the line still goes out, masked, and the error goes to `onError`. A dropped line isn't kept as a breadcrumb either.

## How delivery works

Lines wait in a queue and go out in batches: once `batchSize` lines are waiting (default `50`), `flushInterval` after
the first one (default 5 seconds), or when the app goes to the background. A line leaves the queue only once Tailcove
has accepted it. When the device is offline, or Tailcove answers `429` or `5xx`, the batch stays queued and is tried
again with backoff, honouring `Retry-After`. A batch refused for good is dropped and reported to `onError`.

The queue is kept in a file in the app's support directory, so lines written offline or just before the app is killed
go out on the next launch. Set `persistQueue: false` to keep it in memory only, or pass your own `storage`. At most
`maxQueueSize` lines are kept (default `1000`). Nothing the client does throws into your app.

`await Tailcove.instance.flush()` sends now; `await Tailcove.instance.close()` sends, saves and lets go of the
handlers.

## Limits

The same as for React Native: 600 lines a minute and 200 MB a day per source on the app key by default, `429` with
`Retry-After` above it, and every line counts toward your plan's monthly GB.
