# Diagnostics & troubleshooting

> Beekon's on-device log buffer, the errors it throws, and the common ways background location goes wrong, with fixes.

Source: https://docs.getbeekon.com/guide/diagnostics/

Background location is hard to debug: the events that matter happen after the app is backgrounded, while it’s terminated, or on someone else’s phone. This page covers the on-device log buffer, what Beekon throws and what it reports as a state, and a list of symptoms with fixes.

## The log surface

Beekon keeps an **on-device log buffer** that you can read, export and follow live, so you can see what the SDK did while the app was in the background. Logging never sends anything off the device.

| Method                | What it does                                                                               |
| --------------------- | ------------------------------------------------------------------------------------------ |
| `setLogLevel(level)`  | Sets the lowest level that is recorded. Entries below it are discarded.                    |
| `log(level, message)` | Writes your own entry into the SDK’s log, with category `app`.                             |
| `getLog(from, to)`    | Reads stored entries in a time range, oldest first.                                        |
| `exportLog()`         | Writes the buffer to an NDJSON file and returns its path, ready to attach to a bug report. |
| `clearLog()`          | Deletes all stored entries.                                                                |
| `logs` (stream)       | Each entry as it is recorded. `onLog` in React Native.                                     |

A `LogEntry` is `{ id, timestamp, level, category, message }`. `category` names the subsystem (`location`, `sync`, …), or `app` for entries you write. The levels, most to least severe, are `error`, `warn`, `info`, `debug` and `verbose`; `off` records nothing.

* Android

  ```kotlin
  Beekon.setLogLevel(LogLevel.Debug)
  Beekon.log(LogLevel.Info, "user tapped 'start trip'")


  lifecycleScope.launch {
    Beekon.logs.collect { e ->
      Log.d("beekon", "[${e.level}] ${e.category}: ${e.message}")
    }
  }


  val entries = Beekon.getLog(from = hourAgo, to = Instant.now())
  val ndjsonPath = Beekon.exportLog()
  ```

* iOS

  ```swift
  Beekon.shared.setLogLevel(.debug)
  Beekon.shared.log(.info, "user tapped 'start trip'")


  Task {
    for await e in await Beekon.shared.logs {
      print("[\(e.level)] \(e.category): \(e.message)")
    }
  }


  let entries = try await Beekon.shared.getLog(from: hourAgo, to: Date())
  let ndjsonPath = try await Beekon.shared.exportLog()
  ```

* Flutter

  ```dart
  await Beekon.instance.setLogLevel(LogLevel.debug);
  await Beekon.instance.log(LogLevel.info, "user tapped 'start trip'");


  Beekon.instance.logs.listen((e) {
    print('[${e.level}] ${e.category}: ${e.message}');
  });


  final entries = await Beekon.instance.getLog(
    from: DateTime.now().subtract(const Duration(hours: 1)),
    to: DateTime.now(),
  );
  final ndjsonPath = await Beekon.instance.exportLog();
  ```

* React Native

  ```ts
  await Beekon.setLogLevel('debug');
  await Beekon.log('info', "user tapped 'start trip'");


  Beekon.onLog((e) => console.log(`[${e.level}] ${e.category}: ${e.message}`));


  const entries = await Beekon.getLog(
    new Date(Date.now() - 3_600_000),
    new Date(),
  );
  const ndjsonPath = await Beekon.exportLog();
  ```

Tip

For a useful bug report, set the level to `debug`, reproduce the problem, then attach the file from `exportLog()`. It holds the background timeline that a live console misses.

## The error taxonomy

Beekon’s errors are typed, and **`start()` never throws.** Missing permissions, disabled location services and the OS stopping the service arrive as `Stopped(reason)` on the `state` stream, not as exceptions. Only these calls throw:

| Call                                                    | Throws on                                                             |
| ------------------------------------------------------- | --------------------------------------------------------------------- |
| `getLocations`, `deleteLocations`                       | a storage failure                                                     |
| `addGeofences`                                          | an invalid geofence; `GeofencesManagedByServer` in Cloud mode         |
| `removeGeofences`                                       | `GeofencesManagedByServer` in Cloud mode                              |
| `getCurrentLocation`                                    | location unavailable                                                  |
| `configure`, the cloud factory                          | an invalid configuration                                              |
| `setUserId`                                             | an invalid user id                                                    |
| `pendingUploadCount`, `getLog`, `exportLog`, `clearLog` | a storage failure (on iOS they are `throws`, so call them with `try`) |

**Invalid user id.** `setUserId(...)` trims the value, and a blank or null value clears the id without an error. It throws when the trimmed value contains a control character or is longer than 256 UTF-8 bytes. Each platform’s type for this error is in the list below.

The per-platform types:

* **Android:** `sealed class BeekonException` with five subclasses: `StorageException(cause)`, `InvalidConfiguration(reason)`, `InvalidGeofence(reason)`, `GeofencesManagedByServer`, `LocationUnavailable(reason)`. An invalid user id throws a plain `IllegalArgumentException`, not a `BeekonException`.
* **iOS:** `enum BeekonError: Error` with six cases: `.invalidConfiguration(reason:)`, `.invalidGeofence(reason:)`, `.geofencesManagedByServer`, `.storage(reason:)`, `.invalidUserId(reason:)`, `.locationUnavailable(reason:)`.
* **Flutter:** `sealed class BeekonException` with seven subclasses: `LocationUnavailable(reason)`, `StorageException(reason)`, `InvalidConfiguration(reason)`, `InvalidGeofence(reason)`, `GeofencesManagedByServer`, `NoActivity`, `InvalidUserId(reason)`. `NoActivity` is Android-only: `requestPermission` or `openSettings` was called while the plugin had no foreground Activity.
* **React Native:** `class BeekonError extends Error` with a `kind` field: `'storage'`, `'invalidGeofence'`, `'geofencesManagedByServer'`, `'invalidConfiguration'`, `'invalidUserId'`, `'permissionDenied'`, `'locationServicesDisabled'`, `'locationUnavailable'`. The last three are `getCurrentLocation()` precondition failures.

`LocationUnavailable(reason)` carries a `LocationUnavailableReason`: `PermissionDenied`, `LocationServicesDisabled` or `Unavailable`, in the platform’s casing. React Native spells the same three as the `kind`s above. See [One-shot fix](https://docs.getbeekon.com/guide/locations/#one-shot-fix).

### Thrown vs. `Stopped`

| Scenario                                                                                                 | Surface                                                                            |
| -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| The user never granted permission and you call `start()`                                                 | `start()` returns; state becomes `Stopped(PermissionDenied)`. No exception.        |
| The user revokes permission while tracking                                                               | State becomes `Stopped(PermissionDenied)`. No exception.                           |
| Android stops the foreground service under memory pressure                                               | State becomes `Stopped(System)`. Android only.                                     |
| `getLocations(...)` hits a SQLite failure                                                                | throws `BeekonException.StorageException` / `BeekonError.storage`                  |
| `addGeofences(...)` given an invalid geofence                                                            | throws `BeekonException.InvalidGeofence` / `BeekonError.invalidGeofence`           |
| A cloud config with an empty or cell-less project key, or a rejected `endpoint`                          | throws `BeekonException.InvalidConfiguration` / `BeekonError.invalidConfiguration` |
| `configure(...)` switching to cloud mode while tracking                                                  | throws `InvalidConfiguration`. Call `stop()` first.                                |
| `configure(...)` given an out-of-range tracking value (for example a stationary radius outside 5–1000 m) | No error. The value is clamped.                                                    |

There is no `NotInitialised` or `NotConfigured` error. `start()` without an earlier `configure(...)` uses the last stored config, or the defaults on a fresh install.

Note

Two thrown cases that are easy to miss: `InvalidConfiguration` fires only for cloud configuration (a bad project key or endpoint, or a switch to cloud mode while tracking), never for an out-of-range tracking value, and `GeofencesManagedByServer` fires from `addGeofences()` **only in [Beekon Cloud](https://docs.getbeekon.com/cloud/) mode**, where the server owns the geofence set. In self-managed mode you manage geofences yourself and never see it.

Watch the [state stream](https://docs.getbeekon.com/guide/lifecycle/) for everything to do with starting and stopping, and keep try/catch for history and geofence calls. Beekon doesn’t restart by itself after a stop: call `start()` again once the cause is fixed.

## Troubleshooting

Each entry gives a symptom, the likely cause and the fix. Most problems come from permissions, the gate or the app’s own setup.

### `start()` seems to do nothing

`start()` never throws. If tracking can’t run, `state` becomes `Stopped(reason)`. Watch `state` and read the reason: `permissionDenied`, `locationServicesDisabled`, `locationUnavailable`, `system`, or `backgroundStartDenied` (in practice Android 12 and later only). `user` means `stop()` was called. Every platform defines all six. See [Lifecycle & states](https://docs.getbeekon.com/guide/lifecycle/).

### Locations are sparse or never arrive

* **The gate is too tight.** A fix is stored only when both `minTimeBetweenLocationsSeconds` and `minDistanceBetweenLocationsMeters` have passed. `accuracyMode: low` also raises the distance gate to at least 500 m. Lower the values, or set one to `0` to turn that gate off. See [Configuration](https://docs.getbeekon.com/start/configuration/).
* **No background permission.** With only a foreground grant, tracking doesn’t resume after the OS stops the app or the device reboots, and geofences don’t fire, until the user opens the app again. Request background location (*Always* on iOS) with `requestPermission(backgroundLocation)`: `requestNextNeededPermission()` asks only for required permissions and never for this one. See [Requesting permissions](https://docs.getbeekon.com/start/permissions/#requesting-permissions).
* **iOS asks in two steps.** iOS grants *When in Use* first; you then request *Always*. See [Platform setup](https://docs.getbeekon.com/start/setup/).

### Sync keeps failing

* **Wrong status code.** The SDK deletes the batch on `2xx`, and also on `400` and `422`, which mean the payload will never be accepted. Any other `4xx` you didn’t intend (for example a framework’s `404` for an unmatched route) keeps the batch, and the queue looks stuck. Check that your route returns `2xx`.
* **Locations go missing.** If your server answers `400` or `422` to good data, the SDK deletes that batch and doesn’t retry, and `syncStatus` shows Failed with reason `rejected`. Return `400` or `422` only for a payload that will never be accepted.
* **A redirect.** Beekon refuses `3xx` and treats it as permanent. Serve the exact `url` directly, with no `301` or `302`.
* **The body isn’t gunzipped.** The body is always `Content-Encoding: gzip`. A server that passes the raw bytes to a JSON parser fails with `400`, and the SDK then deletes the batch. Gunzip first.
* **Auth.** A `401` or `403` shows as a sync auth failure. With `SyncConfig.auth` set, the SDK refreshes the token and retries. With static `headers`, call `configure()` again with new ones. See [Auth & token refresh](https://docs.getbeekon.com/guide/sync-auth/).
* **Watch `syncStatus`** and `pendingUploadCount()` to see whether the queue is going down.

### Geofences don’t fire

* **Radius too small.** Use 100 m or more. Smaller geofences are unreliable on real hardware.
* **Background location not granted.** Geofence monitoring needs the same background grant (*Always* on iOS) as background tracking.
* **Notifications.** [Per-geofence notifications](https://docs.getbeekon.com/guide/geofencing/#per-geofence-notifications) need `POST_NOTIFICATIONS` on Android 13 and later, and notification authorisation on iOS. Ask with [`requestPermission(notifications)`](https://docs.getbeekon.com/start/permissions/#requesting-permissions) before relying on crossing alerts.
* Subscribe to `geofenceEvents` to check that crossings are recorded. See [Geofencing](https://docs.getbeekon.com/guide/geofencing/).

### Tracking doesn’t resume after the app is killed

* **Android: wire up cold-launch resume.** Call `Beekon.resumeIfNeeded()` from `Application.onCreate`. Reboots and app updates are covered by the SDK’s boot receiver, which needs `ACCESS_BACKGROUND_LOCATION` to restart tracking. See [Cold-launch resume](https://docs.getbeekon.com/guide/background/#cold-launch-resume).
* **iOS: automatic, with one exception.** A significant location change wakes the terminated app and Beekon calls `resumeIfNeeded()` itself. If the user force-quits the app, iOS stops these wakes until the app is next opened. This is an iOS rule.
* **Flutter:** call `await Beekon.instance.resumeIfNeeded()` early in `main()`.
* **React Native:** call `await Beekon.resumeIfNeeded()` early in your app entry.
* **Flutter and React Native on Android:** a background relaunch may not start the Dart or JS engine. To resume in that case too, also call the native `Beekon.resumeIfNeeded()` from `Application.onCreate`.

### Android: tracking stops on some devices

Some manufacturers’ battery managers (Xiaomi, Oppo, Huawei, …) stop background services even when they run as foreground services. The SDK can’t prevent this; ask users to exempt your app. [dontkillmyapp.com](https://dontkillmyapp.com) has steps for each vendor.

### React Native: module is undefined / build fails

`@wayq/beekon-rn` requires the New Architecture (RN 0.76 or later). On the old architecture the TurboModule doesn’t link. Turn on the New Architecture in your app.

Tip

If none of these fit, use the [log buffer](#the-log-surface): call `setLogLevel(debug)`, reproduce the problem, then read the file from `exportLog()`.
