Skip to content

Colota - Android GPS Location tracker

feat: add centralized AppLogger replacing direct Log/BuildConfig.DEBUG usage

Max Dietrich5f4bff68ec50
diff --git a/apps/docs/docs/contributing.md b/apps/docs/docs/contributing.md
index 74a513d0..b2dcb584 100644
--- a/apps/docs/docs/contributing.md
+++ b/apps/docs/docs/contributing.md
@@ -28,6 +28,7 @@ See the [Development Guide](/docs/development/architecture) for architecture det
- **Kotlin** for native Android modules
- Follow existing patterns in the codebase
- Use `logger` instead of `console.log` - import from `src/utils/logger`
+- Use `AppLogger` instead of `android.util.Log` in Kotlin code - import from `com.Colota.util.AppLogger`
- Test both build flavors if your changes touch native code:
```bash
cd apps/mobile/android
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index f3845b84..488be061 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -153,15 +153,16 @@ Wraps Android's `EncryptedSharedPreferences` for AES-256-GCM encrypted credentia
### Other Modules
-| Module | Purpose |
-| ---------------------- | --------------------------------------------------------- |
-| `LocationBootReceiver` | Auto-restarts tracking after device reboot |
-| `DeviceInfoHelper` | Device metadata and battery status with caching |
-| `FileOperations` | File I/O, sharing via FileProvider, and clipboard access |
-| `PayloadBuilder` | Builds JSON payloads with dynamic field mapping |
-| `ServiceConfig` | Centralized configuration data class |
-| `TimedCache` | Generic TTL cache used for queue count and device info |
-| `BuildConfigModule` | Exposes build constants (SDK versions, app version) to JS |
+| Module | Purpose |
+| ---------------------- | ------------------------------------------------------------------------------------------ |
+| `LocationBootReceiver` | Auto-restarts tracking after device reboot |
+| `DeviceInfoHelper` | Device metadata and battery status with caching |
+| `FileOperations` | File I/O, sharing via FileProvider, and clipboard access |
+| `PayloadBuilder` | Builds JSON payloads with dynamic field mapping |
+| `ServiceConfig` | Centralized configuration data class |
+| `TimedCache` | Generic TTL cache used for queue count and device info |
+| `BuildConfigModule` | Exposes build constants (SDK versions, app version) to JS |
+| `AppLogger` | Centralized logger - logs when debug mode is enabled or in debug builds, errors always log |
## React Native Layer
@@ -203,7 +204,7 @@ Supporting utilities in `mapUtils.ts`:
| Utility | Purpose |
| --- | --- |
-| `logger` | Environment-aware logging - suppresses debug/info in production via `__DEV__`, always logs warn/error |
+| `logger` | Environment-aware logging with ring buffer - suppresses debug/info in production via `__DEV__`, always logs warn/error. Buffer is used for log export |
| `geo` | Haversine distance, speed/distance formatting with locale-aware unit selection (km/h vs mph) |
| `exportConverters` | Converts location data to CSV, GeoJSON, GPX, and KML export formats |
| `queueStatus` | Maps sync queue size to color indicators for the dashboard |
diff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.md
index 9cefca68..f209fe99 100644
--- a/apps/docs/docs/guides/troubleshooting.md
+++ b/apps/docs/docs/guides/troubleshooting.md
@@ -27,6 +27,17 @@ sidebar_position: 4
**Common causes**: Wrong URL, HTTPS required for non-localhost, expired SSL certificate, incorrect authentication, mismatched field mapping, self-signed certificate (not supported), **Wi-Fi Only Sync** enabled while on cellular data, missing local network permission on Android 17+.
+## Exporting app logs
+
+You can export app logs directly from the device for bug reports:
+
+1. Go to **About** and tap the version number 7 times to enable debug mode
+2. Log collection starts automatically - reproduce the issue you want to report
+3. Tap **Export Logs** to share a text file with the collected log entries
+4. The export includes app version, device info, and all collected log messages
+
+Log collection is only active while debug mode is enabled and uses minimal memory.
+
## Debugging with adb logcat
Filter logs to see what Colota is doing:
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx
index 9945aa88..75854afb 100644
--- a/apps/mobile/App.tsx
+++ b/apps/mobile/App.tsx
@@ -26,9 +26,16 @@ import {
ProfileEditorScreen,
SetupImportScreen
} from "./src/screens/"
+import NativeLocationService from "./src/services/NativeLocationService"
+import { setLogCollecting } from "./src/utils/logger"
MapLibreGL.setAccessToken(null)
+// Enable log collection early if debug mode was previously enabled
+NativeLocationService.getSetting("debug_mode_enabled", "false").then((v) => {
+ if (v === "true") setLogCollecting(true)
+})
+
const Stack = createNativeStackNavigator()
const SCREEN_CONFIG = [
diff --git a/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt b/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt
index 88c24695..38a0f322 100644
--- a/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt
+++ b/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt
@@ -12,6 +12,7 @@ import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.Looper
+import com.Colota.util.AppLogger
/**
* LocationManager-based provider for FOSS flavor (no Google Play Services).
@@ -21,6 +22,7 @@ import android.os.Looper
class NativeLocationProvider(context: Context) : LocationProvider {
companion object {
+ private const val TAG = "NativeLocationProvider"
/** Ignore network updates for this long after the last GPS fix. */
private const val GPS_SUPPRESSION_MS = 10_000L
}
@@ -62,6 +64,8 @@ class NativeLocationProvider(context: Context) : LocationProvider {
looper
)
+ AppLogger.d(TAG, "Started GPS_PROVIDER updates: interval=${intervalMs}ms, distance=${minDistanceMeters}m")
+
// NETWORK_PROVIDER as coarse fallback for faster initial fix
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
val networkListener = object : LocationListener {
@@ -83,6 +87,9 @@ class NativeLocationProvider(context: Context) : LocationProvider {
networkListener,
looper
)
+ AppLogger.d(TAG, "Also started NETWORK_PROVIDER as fallback")
+ } else {
+ AppLogger.d(TAG, "NETWORK_PROVIDER not available")
}
} catch (e: SecurityException) {
listeners.forEach { locationManager.removeUpdates(it) }
@@ -93,7 +100,10 @@ class NativeLocationProvider(context: Context) : LocationProvider {
}
override fun removeLocationUpdates(callback: LocationUpdateCallback) {
- listenerMap.remove(callback)?.forEach { locationManager.removeUpdates(it) }
+ listenerMap.remove(callback)?.let { listeners ->
+ listeners.forEach { locationManager.removeUpdates(it) }
+ AppLogger.d(TAG, "Stopped location updates (${listeners.size} listener(s))")
+ }
}
override fun getLastLocation(
diff --git a/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt b/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt
index f943a42c..1748008c 100644
--- a/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt
+++ b/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt
@@ -8,11 +8,16 @@ package com.Colota.location
import android.content.Context
import android.location.Location
import android.os.Looper
+import com.Colota.util.AppLogger
import com.google.android.gms.location.*
/** FusedLocationProviderClient-based provider for GMS flavor. */
class GmsLocationProvider(context: Context) : LocationProvider {
+ companion object {
+ private const val TAG = "GmsLocationProvider"
+ }
+
private val fusedClient: FusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(context)
@@ -38,6 +43,7 @@ class GmsLocationProvider(context: Context) : LocationProvider {
try {
fusedClient.requestLocationUpdates(request, gmsCallback, looper)
+ AppLogger.d(TAG, "Started FusedLocationProvider updates: interval=${intervalMs}ms, distance=${minDistanceMeters}m")
} catch (e: SecurityException) {
callbackMap.remove(callback)
throw e
@@ -45,7 +51,10 @@ class GmsLocationProvider(context: Context) : LocationProvider {
}
override fun removeLocationUpdates(callback: LocationUpdateCallback) {
- callbackMap.remove(callback)?.let { fusedClient.removeLocationUpdates(it) }
+ callbackMap.remove(callback)?.let {
+ fusedClient.removeLocationUpdates(it)
+ AppLogger.d(TAG, "Stopped location updates")
+ }
}
override fun getLastLocation(
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
index 67c3f885..382692ff 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
@@ -21,9 +21,9 @@ import com.Colota.sync.NetworkManager
import com.Colota.sync.PayloadBuilder
import com.Colota.util.DeviceInfoHelper
import com.Colota.util.FileOperations
+import com.Colota.util.AppLogger
import com.Colota.util.SecureStorageHelper
import android.os.Build
-import android.util.Log
import com.facebook.react.bridge.*
import com.facebook.react.modules.core.DeviceEventManagerModule
import com.Colota.location.LocationProviderFactory
@@ -101,7 +101,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
.emit("onLocationUpdate", params)
true
} catch (e: Exception) {
- Log.e(TAG, "Failed to send location event", e)
+ AppLogger.e(TAG, "Failed to send location event", e)
false
}
}
@@ -121,7 +121,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
.emit("onTrackingStopped", params)
true
} catch (e: Exception) {
- Log.e(TAG, "Failed to send tracking stopped event", e)
+ AppLogger.e(TAG, "Failed to send tracking stopped event", e)
false
}
}
@@ -142,7 +142,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
.emit("onSyncError", params)
true
} catch (e: Exception) {
- Log.e(TAG, "Failed to send sync error event", e)
+ AppLogger.e(TAG, "Failed to send sync error event", e)
false
}
}
@@ -167,7 +167,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
.emit("onProfileSwitch", params)
true
} catch (e: Exception) {
- Log.e(TAG, "Failed to send profile switch event", e)
+ AppLogger.e(TAG, "Failed to send profile switch event", e)
false
}
}
@@ -189,7 +189,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
.emit("onSyncProgress", params)
true
} catch (e: Exception) {
- Log.e(TAG, "Failed to send sync progress event", e)
+ AppLogger.e(TAG, "Failed to send sync progress event", e)
false
}
}
@@ -210,7 +210,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
.emit("onPauseZoneChange", params)
true
} catch (e: Exception) {
- Log.e(TAG, "Failed to send pause zone event", e)
+ AppLogger.e(TAG, "Failed to send pause zone event", e)
false
}
}
@@ -244,7 +244,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
val result = withContext(Dispatchers.IO) { operation() }
promise.resolve(result)
} catch (e: Exception) {
- Log.e(TAG, "Database operation failed", e)
+ AppLogger.e(TAG, "Database operation failed", e)
promise.reject("DB_ERROR", e.message, e)
}
}
@@ -252,7 +252,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@ReactMethod
fun startService(config: ReadableMap, promise: Promise) {
- Log.d(TAG, "Starting Service with config")
+ AppLogger.d(TAG, "Starting Service with config")
val serviceConfig = ServiceConfig.fromReadableMap(config, dbHelper)
val serviceIntent = Intent(reactApplicationContext, LocationForegroundService::class.java)
@@ -269,14 +269,14 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
promise.resolve(null)
} catch (e: Exception) {
- Log.e(TAG, "Failed to start service", e)
+ AppLogger.e(TAG, "Failed to start service", e)
promise.reject("START_FAILED", e.message, e)
}
}
@ReactMethod
fun stopService() {
- Log.d(TAG, "Stopping Service via UI")
+ AppLogger.d(TAG, "Stopping Service via UI")
val intent = Intent(reactApplicationContext, LocationForegroundService::class.java)
reactApplicationContext.stopService(intent)
@@ -327,7 +327,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
startServiceWithAction(LocationForegroundService.ACTION_MANUAL_FLUSH)
promise.resolve(true)
} catch (e: Exception) {
- Log.e(TAG, "Manual flush failed", e)
+ AppLogger.e(TAG, "Manual flush failed", e)
promise.reject("FLUSH_ERROR", e.message, e)
}
}
@@ -373,7 +373,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
try {
startServiceWithAction(LocationForegroundService.ACTION_RECHECK_ZONE)
} catch (e: Exception) {
- Log.e(TAG, "Failed to trigger zone recheck", e)
+ AppLogger.e(TAG, "Failed to trigger zone recheck", e)
}
}
@@ -383,7 +383,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
try {
startServiceWithAction(LocationForegroundService.ACTION_REFRESH_NOTIFICATION)
} catch (e: Exception) {
- Log.w(TAG, "Notification refresh skipped: service not running", e)
+ AppLogger.w(TAG, "Notification refresh skipped: service not running")
}
}
}
@@ -467,12 +467,12 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
},
onFailure = { e ->
- Log.e(TAG, "Failed to get location for pause zone check", e)
+ AppLogger.e(TAG, "Failed to get location for pause zone check", e)
promise.resolve(null)
}
)
} catch (e: SecurityException) {
- Log.e(TAG, "Location permission not granted", e)
+ AppLogger.e(TAG, "Location permission not granted", e)
promise.resolve(null)
}
}
@@ -550,7 +550,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
triggerProfileRecheck()
promise.resolve(true)
} catch (e: Exception) {
- Log.e(TAG, "Profile recheck failed", e)
+ AppLogger.e(TAG, "Profile recheck failed", e)
promise.reject("RECHECK_ERROR", e.message, e)
}
}
@@ -561,7 +561,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
try {
startServiceWithAction(LocationForegroundService.ACTION_RECHECK_PROFILES)
} catch (e: Exception) {
- Log.w(TAG, "Profile recheck skipped: service not running", e)
+ AppLogger.w(TAG, "Profile recheck skipped: service not running")
}
}
}
@@ -583,10 +583,13 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
@ReactMethod
- fun saveSetting(key: String, value: String, promise: Promise) =
- executeAsync(promise) {
+ fun saveSetting(key: String, value: String, promise: Promise) =
+ executeAsync(promise) {
dbHelper.saveSetting(key, value)
- true
+ if (key == "debug_mode_enabled") {
+ AppLogger.enabled = value.toBoolean()
+ }
+ true
}
@ReactMethod
@@ -642,7 +645,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
reactApplicationContext.startService(intent)
}
} catch (e: Exception) {
- Log.e(TAG, "Failed to start service with action: $action", e)
+ AppLogger.e(TAG, "Failed to start service with action: $action", e)
throw e
}
}
@@ -724,5 +727,16 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
headers.forEach { (k, v) -> putString(k, v) }
}
}
+
+ @ReactMethod
+ fun getNativeLogs(promise: Promise) = executeAsync(promise) {
+ val pid = android.os.Process.myPid()
+ val process = Runtime.getRuntime().exec(arrayOf("logcat", "-d", "-v", "threadtime", "--pid=$pid"))
+ val lines = process.inputStream.bufferedReader().readLines()
+ process.waitFor()
+ Arguments.createArray().apply {
+ lines.forEach { pushString(it) }
+ }
+ }
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
index 1a305538..6694d173 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
@@ -6,12 +6,11 @@
package com.Colota.data
import android.content.ContentValues
-import com.Colota.BuildConfig
+import com.Colota.util.AppLogger
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.database.sqlite.SQLiteStatement
-import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.*
@@ -67,6 +66,7 @@ class DatabaseHelper private constructor(context: Context) :
private var incrementRetryStmt: SQLiteStatement? = null
override fun onCreate(db: SQLiteDatabase) {
+ AppLogger.i(TAG, "Creating database v$DATABASE_VERSION")
db.execSQL("""
CREATE TABLE $TABLE_LOCATIONS (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -178,7 +178,7 @@ class DatabaseHelper private constructor(context: Context) :
}
db.setTransactionSuccessful()
} catch (e: Exception) {
- Log.e(TAG, "Error prepopulating settings", e)
+ AppLogger.e(TAG, "Error prepopulating settings", e)
} finally {
db.endTransaction()
}
@@ -191,6 +191,7 @@ class DatabaseHelper private constructor(context: Context) :
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
+ AppLogger.i(TAG, "Upgrading database from v$oldVersion to v$newVersion")
if (oldVersion < 2) {
db.execSQL("""
CREATE TABLE IF NOT EXISTS $TABLE_PROFILES (
@@ -279,7 +280,7 @@ class DatabaseHelper private constructor(context: Context) :
}
}
} catch (e: Exception) {
- Log.e(TAG, "Query failed", e)
+ AppLogger.e(TAG, "Query failed", e)
null
}
}
@@ -326,7 +327,7 @@ class DatabaseHelper private constructor(context: Context) :
}
}
} catch (e: Exception) {
- Log.e(TAG, "Error reading table $tableName", e)
+ AppLogger.e(TAG, "Error reading table $tableName", e)
}
return data
@@ -371,7 +372,7 @@ class DatabaseHelper private constructor(context: Context) :
}
}
} catch (e: Exception) {
- Log.e(TAG, "Error reading locations by date range", e)
+ AppLogger.e(TAG, "Error reading locations by date range", e)
}
return data
@@ -436,8 +437,8 @@ class DatabaseHelper private constructor(context: Context) :
args
)
- if (BuildConfig.DEBUG && deleted > 0) {
- Log.d(TAG, "Batch deleted $deleted queue items")
+ if (deleted > 0) {
+ AppLogger.d(TAG, "Batch deleted $deleted queue items")
}
}
@@ -495,6 +496,7 @@ class DatabaseHelper private constructor(context: Context) :
fun clearSentHistory(): Int {
+ AppLogger.d(TAG, "Clearing sent history")
return writableDatabase.delete(
TABLE_LOCATIONS,
"id NOT IN (SELECT location_id FROM $TABLE_QUEUE)",
@@ -503,6 +505,7 @@ class DatabaseHelper private constructor(context: Context) :
}
fun clearQueue(): Int {
+ AppLogger.d(TAG, "Clearing queue")
// Deleting locations cascades to their queue entries via FK ON DELETE CASCADE
return writableDatabase.delete(
TABLE_LOCATIONS,
@@ -523,11 +526,13 @@ class DatabaseHelper private constructor(context: Context) :
/** Reclaims unused space. Call from background thread only. */
fun vacuum() {
+ AppLogger.d(TAG, "Starting VACUUM + ANALYZE")
try {
writableDatabase.execSQL("VACUUM")
writableDatabase.execSQL("ANALYZE")
+ AppLogger.d(TAG, "VACUUM + ANALYZE completed")
} catch (e: Exception) {
- Log.e(TAG, "Vacuum failed (likely concurrent access)", e)
+ AppLogger.e(TAG, "Vacuum failed (likely concurrent access)", e)
}
}
@@ -578,7 +583,7 @@ class DatabaseHelper private constructor(context: Context) :
}
}
} catch (e: Exception) {
- Log.e(TAG, "Error loading settings", e)
+ AppLogger.e(TAG, "Error loading settings", e)
}
return settings
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
index fb986ee1..ad338931 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
@@ -6,11 +6,10 @@
package com.Colota.data
import android.content.ContentValues
-import com.Colota.BuildConfig
+import com.Colota.util.AppLogger
import com.Colota.util.TimedCache
import android.content.Context
import android.location.Location
-import android.util.Log
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.WritableArray
import kotlin.math.*
@@ -52,16 +51,19 @@ class GeofenceHelper(private val context: Context) {
fun getPauseZone(location: Location): String? {
val fences = getGeofences()
- return fences.find {
- isWithinRadius(location.latitude, location.longitude, it.lat, it.lon, it.radius)
- }?.name
+ val match = fences.find {
+ isWithinRadius(location.latitude, location.longitude, it.lat, it.lon, it.radius)
+ }
+ if (fences.isNotEmpty() && match != null) {
+ val dist = calculateDistance(location.latitude, location.longitude, match.lat, match.lon)
+ AppLogger.d(TAG, "Inside zone '${match.name}' (${String.format("%.0f", dist)}m from center, radius=${match.radius}m)")
+ }
+ return match?.name
}
fun invalidateCache() {
geofenceCache.invalidate()
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Geofence cache invalidated")
- }
+ AppLogger.d(TAG, "Geofence cache invalidated")
}
private fun getGeofences(): List<CachedGeofence> = geofenceCache.get()
@@ -89,9 +91,10 @@ class GeofenceHelper(private val context: Context) {
))
}
}
+ AppLogger.d(TAG, "Loaded ${fences.size} active pause zone(s)")
fences
} catch (e: Exception) {
- Log.e(TAG, "Failed to refresh geofence cache", e)
+ AppLogger.e(TAG, "Failed to refresh geofence cache", e)
emptyList()
}
}
@@ -128,7 +131,7 @@ class GeofenceHelper(private val context: Context) {
}
}
} catch (e: Exception) {
- Log.e(TAG, "Failed to load geofences as array", e)
+ AppLogger.e(TAG, "Failed to load geofences as array", e)
}
return array
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt
index 974b7270..4b074674 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt
@@ -6,11 +6,10 @@
package com.Colota.data
import android.content.ContentValues
-import com.Colota.BuildConfig
+import com.Colota.util.AppLogger
import com.Colota.service.ProfileConstants
import com.Colota.util.TimedCache
import android.content.Context
-import android.util.Log
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.WritableArray
@@ -38,9 +37,7 @@ class ProfileHelper(private val context: Context) {
fun invalidateCache() {
profileCache.invalidate()
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Profile cache invalidated")
- }
+ AppLogger.d(TAG, "Profile cache invalidated")
}
fun getEnabledProfiles(): List<CachedProfile> = profileCache.get()
@@ -80,7 +77,7 @@ class ProfileHelper(private val context: Context) {
}
profiles
} catch (e: Exception) {
- Log.e(TAG, "Failed to load profiles", e)
+ AppLogger.e(TAG, "Failed to load profiles", e)
emptyList()
}
}
@@ -127,7 +124,7 @@ class ProfileHelper(private val context: Context) {
}
}
} catch (e: Exception) {
- Log.e(TAG, "Failed to load profiles as array", e)
+ AppLogger.e(TAG, "Failed to load profiles as array", e)
}
return array
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt b/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt
index abf5d375..67828291 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt
@@ -6,12 +6,11 @@
package com.Colota.service
import android.content.BroadcastReceiver
-import com.Colota.BuildConfig
import com.Colota.data.DatabaseHelper
import android.content.Context
import android.content.Intent
import android.os.Build
-import android.util.Log
+import com.Colota.util.AppLogger
import kotlinx.coroutines.*
/**
@@ -47,7 +46,7 @@ class LocationBootReceiver : BroadcastReceiver() {
try {
handleBootCompleted(context.applicationContext, action)
} catch (e: Exception) {
- Log.e(TAG, "Error handling boot", e)
+ AppLogger.e(TAG, "Error handling boot", e)
} finally {
// CRITICAL: Always call finish()
pendingResult.finish()
@@ -66,9 +65,7 @@ class LocationBootReceiver : BroadcastReceiver() {
dbHelper.getSetting("tracking_enabled")
return true
} catch (e: Exception) {
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "DB not ready, attempt ${attempt + 1}/$MAX_DB_RETRIES")
- }
+ AppLogger.d(TAG, "DB not ready, attempt ${attempt + 1}/$MAX_DB_RETRIES")
if (attempt < MAX_DB_RETRIES - 1) {
delay(RETRY_DELAY_MS)
}
@@ -83,22 +80,18 @@ class LocationBootReceiver : BroadcastReceiver() {
// Wait for database to be ready
if (!waitForDatabaseReady(dbHelper)) {
- Log.e(TAG, "Database not ready after $MAX_DB_RETRIES attempts")
+ AppLogger.e(TAG, "Database not ready after $MAX_DB_RETRIES attempts")
return
}
val isEnabled = dbHelper.getSetting("tracking_enabled", "false") == "true"
if (!isEnabled) {
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Boot detected but tracking disabled")
- }
+ AppLogger.d(TAG, "Boot detected but tracking disabled")
return
}
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Boot detected ($action). Restarting service...")
- }
+ AppLogger.d(TAG, "Boot detected ($action). Restarting service...")
// Load config using ServiceConfig (eliminates duplication)
val config = ServiceConfig.fromDatabase(dbHelper)
@@ -114,14 +107,12 @@ class LocationBootReceiver : BroadcastReceiver() {
context.startService(serviceIntent)
}
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Service start requested successfully")
- }
+ AppLogger.d(TAG, "Service start requested successfully")
} catch (e: SecurityException) {
- Log.e(TAG, "Permission denied when starting service", e)
+ AppLogger.e(TAG, "Permission denied when starting service", e)
} catch (e: Exception) {
- Log.e(TAG, "Error restarting service on boot", e)
+ AppLogger.e(TAG, "Error restarting service on boot", e)
}
}
}
\ No newline at end of file
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt
index 1538576d..e494e41a 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt
@@ -12,10 +12,9 @@ import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Handler
import android.os.Looper
-import android.util.Log
import androidx.car.app.connection.CarConnection
import androidx.lifecycle.Observer
-import com.Colota.BuildConfig
+import com.Colota.util.AppLogger
/**
* Monitors device conditions (charging state, Android Auto connection)
@@ -51,18 +50,14 @@ class ConditionMonitor(
val charging = readCurrentChargingState()
profileManager.onChargingStateChanged(charging)
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Condition monitors started — charging: $charging")
- }
+ AppLogger.d(TAG, "Condition monitors started - charging: $charging")
}
fun stop() {
chargingReceiver = unregisterSafely(chargingReceiver)
stopCarConnectionMonitor()
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Condition monitors stopped")
- }
+ AppLogger.d(TAG, "Condition monitors stopped")
}
private fun unregisterSafely(receiver: BroadcastReceiver?): Nothing? {
@@ -77,11 +72,11 @@ class ConditionMonitor(
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_POWER_CONNECTED -> {
- if (BuildConfig.DEBUG) Log.d(TAG, "Power connected")
+ AppLogger.d(TAG, "Power connected")
profileManager.onChargingStateChanged(true)
}
Intent.ACTION_POWER_DISCONNECTED -> {
- if (BuildConfig.DEBUG) Log.d(TAG, "Power disconnected")
+ AppLogger.d(TAG, "Power disconnected")
profileManager.onChargingStateChanged(false)
}
}
@@ -101,9 +96,7 @@ class ConditionMonitor(
val observer = Observer<Int> { connectionType ->
val connected = connectionType != CarConnection.CONNECTION_TYPE_NOT_CONNECTED
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "CarConnection type: $connectionType (connected: $connected)")
- }
+ AppLogger.d(TAG, "CarConnection type: $connectionType (connected: $connected)")
profileManager.onCarModeStateChanged(connected)
}
carConnectionObserver = observer
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
index afbbb5f3..9ed2bf8b 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
@@ -6,8 +6,8 @@
package com.Colota.service
import android.app.*
-import com.Colota.BuildConfig
import com.Colota.bridge.LocationServiceModule
+import com.Colota.util.AppLogger
import com.Colota.data.DatabaseHelper
import com.Colota.data.GeofenceHelper
import com.Colota.data.ProfileHelper
@@ -18,7 +18,6 @@ import com.Colota.util.DeviceInfoHelper
import com.Colota.util.SecureStorageHelper
import android.content.Intent
import android.os.*
-import android.util.Log
import com.Colota.location.LocationProvider
import com.Colota.location.LocationProviderFactory
import com.Colota.location.LocationUpdateCallback
@@ -93,6 +92,9 @@ class LocationForegroundService : Service() {
notificationHelper = NotificationHelper(this, notificationManager)
notificationHelper.createChannel()
+
+ AppLogger.enabled = dbHelper.getSetting("debug_mode_enabled")?.toBoolean() ?: false
+ AppLogger.d(TAG, "Service created - provider: ${locationProvider.javaClass.simpleName}")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
@@ -105,9 +107,7 @@ class LocationForegroundService : Service() {
// intent == null: Android restarted the service after OOM kill
if (intent == null && !shouldBeTracking) {
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "System restart prevented")
- }
+ AppLogger.d(TAG, "System restart prevented")
stopSelf()
return START_NOT_STICKY
}
@@ -115,6 +115,8 @@ class LocationForegroundService : Service() {
val action = intent?.action
val isLightweight = action in LIGHTWEIGHT_ACTIONS
+ AppLogger.d(TAG, "onStartCommand: action=${action ?: "START"}, lightweight=$isLightweight")
+
// Skip config reload for lightweight actions, but if the service was
// killed and restarted by one, load from DB so SyncManager has an endpoint.
if (!isLightweight) {
@@ -152,9 +154,7 @@ class LocationForegroundService : Service() {
}
ACTION_FORCE_EXIT_ZONE -> {
if (insidePauseZone) {
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Force exit from zone: $currentZoneName")
- }
+ AppLogger.d(TAG, "Force exit from zone: $currentZoneName")
exitPauseZone()
lastKnownLocation?.let { recheckZoneWithLocation(it) }
}
@@ -201,6 +201,8 @@ class LocationForegroundService : Service() {
}
override fun onDestroy() {
+ AppLogger.d(TAG, "Service destroyed")
+
conditionMonitor.stop()
stopLocationUpdates()
syncManager.stopPeriodicSync()
@@ -224,13 +226,13 @@ class LocationForegroundService : Service() {
if (deviceInfoHelper.isBatteryCritical(threshold = 5)) {
val (level, _) = deviceInfoHelper.getCachedBatteryStatus()
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Battery critical ($level%) and unplugged - stopping service")
- }
+ AppLogger.d(TAG, "Battery critical ($level%) and unplugged - stopping service")
stopForegroundServiceWithReason("Battery critical")
return
}
+ AppLogger.d(TAG, "Requesting location updates: interval=${config.interval}ms, distance=${config.minUpdateDistance}m")
+
try {
locationProvider.requestLocationUpdates(
intervalMs = config.interval,
@@ -253,10 +255,10 @@ class LocationForegroundService : Service() {
onFailure = { /* initial location unavailable, updates will arrive */ }
)
} catch (e: SecurityException) {
- Log.e(TAG, "Location permission missing", e)
+ AppLogger.e(TAG, "Location permission missing", e)
stopForegroundServiceWithReason("Location permission missing")
} catch (e: Exception) {
- Log.e(TAG, "Failed to start location updates", e)
+ AppLogger.e(TAG, "Failed to start location updates", e)
stopForegroundServiceWithReason("Location provider error")
}
}
@@ -282,15 +284,13 @@ class LocationForegroundService : Service() {
recheckZoneWithLocation(location)
} else {
if (insidePauseZone) {
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "No location for recheck, forcing exit from zone")
- }
+ AppLogger.d(TAG, "No location for recheck, forcing exit from zone")
exitPauseZone()
}
}
},
onFailure = { e ->
- Log.e(TAG, "Recheck error", e)
+ AppLogger.e(TAG, "Recheck error", e)
if (insidePauseZone) {
exitPauseZone()
}
@@ -350,6 +350,7 @@ class LocationForegroundService : Service() {
private fun handleLocationUpdate(location: android.location.Location) {
if (config.filterInaccurateLocations && location.accuracy > config.accuracyThreshold) {
+ AppLogger.d(TAG, "Location filtered: accuracy ${location.accuracy}m > threshold ${config.accuracyThreshold}m")
return
}
@@ -358,9 +359,12 @@ class LocationForegroundService : Service() {
if (prev != null && location.time == prev.time
&& location.latitude == prev.latitude
&& location.longitude == prev.longitude) {
+ AppLogger.d(TAG, "Duplicate location skipped (same timestamp and coords)")
return
}
+ AppLogger.d(TAG, "Location received: ${String.format(Locale.US, "%.5f, %.5f", location.latitude, location.longitude)} acc=${location.accuracy}m provider=${location.provider}")
+
applySpeedFallback(location)
// After accuracy filter so bad GPS doesn't pollute speed average
@@ -381,9 +385,7 @@ class LocationForegroundService : Service() {
val (battery, batteryStatus) = deviceInfoHelper.getCachedBatteryStatus()
if (deviceInfoHelper.isBatteryCritical()) {
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Battery critical ($battery%) during tracking - stopping")
- }
+ AppLogger.d(TAG, "Battery critical ($battery%) during tracking - stopping")
stopForegroundServiceWithReason("Battery critical")
return
}
@@ -439,9 +441,7 @@ class LocationForegroundService : Service() {
LocationServiceModule.sendPauseZoneEvent(true, zoneName)
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Entered pause zone: $zoneName")
- }
+ AppLogger.d(TAG, "Entered pause zone: $zoneName")
}
@@ -454,7 +454,7 @@ class LocationForegroundService : Service() {
updateNotification(lat = loc?.latitude, lon = loc?.longitude, forceUpdate = true)
LocationServiceModule.sendPauseZoneEvent(false, exited)
- if (BuildConfig.DEBUG) Log.d(TAG, "Exited pause zone: $exited")
+ AppLogger.d(TAG, "Exited pause zone: $exited")
}
private fun updateNotification(
@@ -480,9 +480,7 @@ class LocationForegroundService : Service() {
}
private fun stopForegroundServiceWithReason(reason: String) {
- if (BuildConfig.DEBUG) {
- Log.i(TAG, "Stopping: $reason")
- }
+ AppLogger.i(TAG, "Stopping: $reason")
// Reset profile indicator in JS UI
if (profileManager.getActiveProfileName() != null) {
@@ -528,9 +526,7 @@ class LocationForegroundService : Service() {
val loc = lastKnownLocation
updateNotification(lat = loc?.latitude, lon = loc?.longitude, forceUpdate = true)
- if (BuildConfig.DEBUG) {
- Log.i(TAG, "Profile config applied: ${profileManager.getActiveProfileName() ?: "default"} - interval=${interval}ms, distance=${distance}m, sync=${syncInterval}s")
- }
+ AppLogger.i(TAG, "Profile config applied: ${profileManager.getActiveProfileName() ?: "default"} - interval=${interval}ms, distance=${distance}m, sync=${syncInterval}s")
}
private fun pushConfigToSyncManager() {
@@ -568,10 +564,10 @@ class LocationForegroundService : Service() {
if (it.isNotBlank()) customFields = payloadBuilder.parseCustomFields(it)
}
- if (BuildConfig.DEBUG) {
+ if (AppLogger.enabled) {
val batteryStatusStr = deviceInfoHelper.getBatteryStatusString()
- Log.d(TAG, """
+ AppLogger.d(TAG, """
╔════════════════════════════════════════════════════════════════╗
║ COLOTA LOCATION SERVICE CONFIGURATION ║
╠════════════════════════════════════════════════════════════════╣
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
index c27c8759..045587c9 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt
@@ -5,8 +5,7 @@
package com.Colota.service
-import android.util.Log
-import com.Colota.BuildConfig
+import com.Colota.util.AppLogger
import com.Colota.bridge.LocationServiceModule
import com.Colota.data.ProfileHelper
import kotlinx.coroutines.*
@@ -126,7 +125,7 @@ class ProfileManager(
}
private fun matchesCondition(profile: ProfileHelper.CachedProfile): Boolean {
- return when (profile.conditionType) {
+ val result = when (profile.conditionType) {
ProfileConstants.CONDITION_CHARGING -> isCharging
ProfileConstants.CONDITION_ANDROID_AUTO -> isCarMode
ProfileConstants.CONDITION_SPEED_ABOVE -> {
@@ -141,6 +140,17 @@ class ProfileManager(
}
else -> false
}
+
+ if (result) {
+ val detail = when (profile.conditionType) {
+ ProfileConstants.CONDITION_SPEED_ABOVE,
+ ProfileConstants.CONDITION_SPEED_BELOW -> " (avg=${String.format("%.1f", getAverageSpeed())}m/s, threshold=${profile.speedThreshold})"
+ else -> ""
+ }
+ AppLogger.d(TAG, "Profile '${profile.name}' matched: ${profile.conditionType}$detail")
+ }
+
+ return result
}
private fun getAverageSpeed(): Float? {
@@ -153,9 +163,7 @@ class ProfileManager(
private fun activateProfile(profile: ProfileHelper.CachedProfile) {
activeProfile = profile
- if (BuildConfig.DEBUG) {
- Log.i(TAG, "Activated profile: ${profile.name} (interval=${profile.intervalMs}ms, sync=${profile.syncIntervalSeconds}s)")
- }
+ AppLogger.i(TAG, "Activated profile: ${profile.name} (interval=${profile.intervalMs}ms, sync=${profile.syncIntervalSeconds}s)")
// Notify JS
LocationServiceModule.sendProfileSwitchEvent(profile.name, profile.id)
@@ -180,9 +188,7 @@ class ProfileManager(
deactivateIfStillActive(scheduledProfileId)
}
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Scheduled deactivation of '${profile.name}' in ${profile.deactivationDelaySeconds}s")
- }
+ AppLogger.d(TAG, "Scheduled deactivation of '${profile.name}' in ${profile.deactivationDelaySeconds}s")
}
/**
@@ -207,9 +213,7 @@ class ProfileManager(
activeProfile = null
deactivationJob = null
- if (BuildConfig.DEBUG) {
- Log.i(TAG, "Deactivated profile: ${previousProfile.name} — reverting to defaults")
- }
+ AppLogger.i(TAG, "Deactivated profile: ${previousProfile.name} - reverting to defaults")
// Notify JS
LocationServiceModule.sendProfileSwitchEvent(null, null)
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
index e0dedd10..0197c704 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
@@ -1,11 +1,10 @@
package com.Colota.sync
import android.content.Context
-import com.Colota.BuildConfig
+import com.Colota.util.AppLogger
import com.Colota.util.TimedCache
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
-import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
@@ -36,7 +35,7 @@ class NetworkManager(private val context: Context) {
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
} catch (e: Exception) {
- Log.e(TAG, "Network check failed", e)
+ AppLogger.e(TAG, "Network check failed", e)
false
}
}
@@ -52,24 +51,24 @@ class NetworkManager(private val context: Context) {
httpMethod: String = "POST"
): Boolean = withContext(Dispatchers.IO) {
if (endpoint.isBlank()) {
- if (BuildConfig.DEBUG) Log.d(TAG, "Empty endpoint provided")
+ AppLogger.d(TAG, "Empty endpoint provided")
return@withContext false
}
val url = try {
URL(endpoint)
} catch (e: Exception) {
- Log.e(TAG, "Invalid URL: $endpoint")
+ AppLogger.e(TAG, "Invalid URL: $endpoint")
return@withContext false
}
if (!isValidProtocol(url)) {
- Log.e(TAG, "Protocol blocked or invalid: $endpoint")
+ AppLogger.e(TAG, "Protocol blocked or invalid: $endpoint")
return@withContext false
}
if (!isNetworkAvailable()) {
- if (BuildConfig.DEBUG) Log.d(TAG, "Sync skipped: No internet")
+ AppLogger.d(TAG, "Sync skipped: No internet")
return@withContext false
}
@@ -101,19 +100,19 @@ class NetworkManager(private val context: Context) {
useCaches = false
}
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "=== HTTP REQUEST ===")
- Log.d(TAG, "Endpoint: ${if (isGet) targetUrl else endpoint}")
- Log.d(TAG, "Method: ${connection.requestMethod}")
- Log.d(TAG, "Headers:")
+ if (AppLogger.enabled) {
+ AppLogger.d(TAG, "=== HTTP REQUEST ===")
+ AppLogger.d(TAG, "Endpoint: ${if (isGet) targetUrl else endpoint}")
+ AppLogger.d(TAG, "Method: ${connection.requestMethod}")
+ AppLogger.d(TAG, "Headers:")
connection.requestProperties.forEach { (key, values) ->
val masked = values.map { maskSensitiveHeaderValue(key, it) }
- Log.d(TAG, "$key: ${masked.joinToString()}")
+ AppLogger.d(TAG, "$key: ${masked.joinToString()}")
}
if (!isGet) {
- Log.d(TAG, "Body: ${payload.toString(2)}")
+ AppLogger.d(TAG, "Body: ${payload.toString(2)}")
}
- Log.d(TAG, "===================")
+ AppLogger.d(TAG, "===================")
}
if (!isGet) {
@@ -124,24 +123,24 @@ class NetworkManager(private val context: Context) {
val responseCode = connection.responseCode
return@withContext if (responseCode in 200..299) {
- if (BuildConfig.DEBUG) Log.d(TAG, "Location successfully sent")
+ AppLogger.d(TAG, "Location successfully sent")
true
} else {
val errorBody = try {
connection.errorStream?.bufferedReader()?.use { it.readText() } ?: "No error body"
} catch (_: Exception) { "Could not read error body" }
- Log.e(TAG, "${connection.requestMethod} failed: $responseCode - $errorBody")
+ AppLogger.e(TAG, "${connection.requestMethod} failed: $responseCode - $errorBody")
false
}
} catch (e: java.net.SocketException) {
if (isPrivateHost(url.host ?: "") && e.message?.contains("EPERM") == true) {
- Log.e(TAG, "Local network access denied - grant Nearby Devices permission", e)
+ AppLogger.e(TAG, "Local network access denied - grant Nearby Devices permission", e)
} else {
- Log.e(TAG, "Network error: ${e.message}", e)
+ AppLogger.e(TAG, "Network error: ${e.message}", e)
}
false
} catch (e: Exception) {
- Log.e(TAG, "Network error: ${e.message}", e)
+ AppLogger.e(TAG, "Network error: ${e.message}", e)
false
} finally {
connection?.disconnect()
@@ -240,7 +239,7 @@ class NetworkManager(private val context: Context) {
capabilities != null &&
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
} catch (e: Exception) {
- Log.e(TAG, "Unmetered check failed", e)
+ AppLogger.e(TAG, "Unmetered check failed", e)
false
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt
index 798ce96b..c4f7754b 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt
@@ -6,7 +6,7 @@
package com.Colota.sync
import android.location.Location
-import android.util.Log
+import com.Colota.util.AppLogger
import org.json.JSONObject
import kotlin.math.*
@@ -63,7 +63,7 @@ class PayloadBuilder {
val json = JSONObject(jsonString)
json.keys().asSequence().associateWith { json.getString(it) }
} catch (e: Exception) {
- Log.e(TAG, "Failed to parse field map", e)
+ AppLogger.e(TAG, "Failed to parse field map", e)
null
}
}
@@ -90,7 +90,7 @@ class PayloadBuilder {
}
if (map.isEmpty()) null else map
} catch (e: Exception) {
- Log.e(TAG, "Failed to parse custom fields", e)
+ AppLogger.e(TAG, "Failed to parse custom fields", e)
null
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
index 08260052..c7272b57 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
@@ -5,8 +5,7 @@
package com.Colota.sync
-import android.util.Log
-import com.Colota.BuildConfig
+import com.Colota.util.AppLogger
import com.Colota.bridge.LocationServiceModule
import com.Colota.data.DatabaseHelper
import com.Colota.util.TimedCache
@@ -67,6 +66,7 @@ class SyncManager(
}
fun startPeriodicSync() {
+ AppLogger.d(TAG, "Starting periodic sync: interval=${syncIntervalSeconds}s, endpoint=${if (endpoint.isBlank()) "NONE" else endpoint}")
syncJob = scope.launch {
while (isActive) {
val baseDelay = calculateNextSyncDelay()
@@ -82,8 +82,8 @@ class SyncManager(
val success = performSyncAndCheckSuccess()
if (success) {
- if (consecutiveFailures > 0 && BuildConfig.DEBUG) {
- Log.i(TAG, "Sync restored")
+ if (consecutiveFailures > 0) {
+ AppLogger.i(TAG, "Sync restored")
}
consecutiveFailures = 0
null
@@ -91,7 +91,7 @@ class SyncManager(
"Sync failed"
}
} catch (e: Exception) {
- Log.e(TAG, "Sync error", e)
+ AppLogger.e(TAG, "Sync error", e)
e.message ?: "Sync error"
}
@@ -113,11 +113,13 @@ class SyncManager(
fun stopPeriodicSync() {
syncJob?.cancel()
syncJob = null
+ AppLogger.d(TAG, "Periodic sync stopped")
}
suspend fun manualFlush() {
if (endpoint.isNotBlank()) {
val total = dbHelper.getQueuedCount()
+ AppLogger.d(TAG, "Manual flush started: $total items in queue")
syncQueue { sent, failed -> LocationServiceModule.sendSyncProgressEvent(sent, failed, total) }
}
}
@@ -128,16 +130,14 @@ class SyncManager(
invalidateQueueCache()
if (endpoint.isBlank() || isOfflineMode) {
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Queued location $locationId - ${if (isOfflineMode) "offline mode" else "no endpoint"}")
- }
+ AppLogger.d(TAG, "Queued location $locationId - ${if (isOfflineMode) "offline mode" else "no endpoint"}")
return
}
// Immediate send mode (syncInterval = 0)
if (syncIntervalSeconds == 0 && networkManager.isNetworkAvailable() &&
!(isWifiOnlySync && !networkManager.isUnmeteredConnection())) {
- if (BuildConfig.DEBUG) Log.d(TAG, "Instant send")
+ AppLogger.d(TAG, "Instant send")
val success = networkManager.sendToEndpoint(payload, endpoint, authHeaders, httpMethod)
if (success) {
@@ -179,9 +179,7 @@ class SyncManager(
else -> 900L
}
- if (BuildConfig.DEBUG) {
- Log.w(TAG, "Backoff: ${backoffSeconds}s")
- }
+ AppLogger.w(TAG, "Backoff: ${backoffSeconds}s")
delay(backoffSeconds * 1000L)
}
@@ -201,15 +199,13 @@ class SyncManager(
while (isActive && batchNumber <= MAX_BATCHES_PER_SYNC) {
val queued = dbHelper.getQueuedLocations(50)
if (queued.isEmpty()) {
- if (BuildConfig.DEBUG && totalProcessed > 0) {
- Log.d(TAG, "Sync complete: $totalProcessed items in $batchNumber batches")
+ if (totalProcessed > 0) {
+ AppLogger.d(TAG, "Sync complete: $totalProcessed items in $batchNumber batches")
}
break
}
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Processing batch $batchNumber/$MAX_BATCHES_PER_SYNC: ${queued.size} items")
- }
+ AppLogger.d(TAG, "Processing batch $batchNumber/$MAX_BATCHES_PER_SYNC: ${queued.size} items")
// Chunks of 10 concurrent HTTP requests to avoid flooding the server
val processedBefore = totalProcessed
@@ -225,8 +221,8 @@ class SyncManager(
}
permanentlyFailedIds.addAll(exceeded.map { it.queueId })
- if (BuildConfig.DEBUG && exceeded.isNotEmpty()) {
- Log.w(TAG, "Removing ${exceeded.size} items that exceeded $currentMaxRetries retries")
+ if (exceeded.isNotEmpty()) {
+ AppLogger.w(TAG, "Removing ${exceeded.size} items that exceeded $currentMaxRetries retries")
}
val results = retriable.map { item ->
@@ -250,9 +246,7 @@ class SyncManager(
if (currentMaxRetries > 0 && item.retryCount + 1 >= currentMaxRetries) {
permanentlyFailedIds.add(queueId)
- if (BuildConfig.DEBUG) {
- Log.w(TAG, "Item $queueId reached max retries")
- }
+ AppLogger.w(TAG, "Item $queueId reached max retries")
}
}
}
@@ -280,17 +274,15 @@ class SyncManager(
// No items removed from queue. Stop re-fetching the same failing items
if (totalProcessed == processedBefore) {
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "No progress in batch $batchNumber, stopping sync pass")
- }
+ AppLogger.d(TAG, "No progress in batch $batchNumber, stopping sync pass")
break
}
batchNumber++
}
- if (batchNumber > MAX_BATCHES_PER_SYNC && BuildConfig.DEBUG) {
- Log.w(TAG, "Sync paused: reached batch limit. Remaining items will sync next cycle.")
+ if (batchNumber > MAX_BATCHES_PER_SYNC) {
+ AppLogger.w(TAG, "Sync paused: reached batch limit. Remaining items will sync next cycle.")
}
invalidateQueueCache()
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/AppLogger.kt b/apps/mobile/android/app/src/main/java/com/colota/util/AppLogger.kt
new file mode 100644
index 00000000..bc10a59b
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/AppLogger.kt
@@ -0,0 +1,46 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.util
+
+import android.util.Log
+import com.Colota.BuildConfig
+
+/**
+ * App-level logger controlled by the user's debug mode toggle.
+ *
+ * Logs are emitted when either:
+ * - The user has enabled debug mode via the About screen (works in release builds)
+ * - The app is running as a debug build (BuildConfig.DEBUG)
+ *
+ * This ensures developers always see logs during local development without
+ * needing to toggle debug mode, while release users can opt in via the setting.
+ *
+ * Errors (Log.e) are always logged regardless of debug mode.
+ */
+object AppLogger {
+
+ @Volatile
+ var enabled: Boolean = false
+
+ private val active: Boolean
+ get() = enabled || BuildConfig.DEBUG
+
+ fun d(tag: String, msg: String) {
+ if (active) Log.d(tag, msg)
+ }
+
+ fun i(tag: String, msg: String) {
+ if (active) Log.i(tag, msg)
+ }
+
+ fun w(tag: String, msg: String) {
+ if (active) Log.w(tag, msg)
+ }
+
+ fun e(tag: String, msg: String, throwable: Throwable? = null) {
+ if (throwable != null) Log.e(tag, msg, throwable) else Log.e(tag, msg)
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt
index ec6af003..9da415dc 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt
@@ -12,7 +12,7 @@ import android.os.BatteryManager
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
-import android.util.Log
+import com.Colota.util.AppLogger
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.WritableMap
@@ -110,7 +110,7 @@ class DeviceInfoHelper(private val context: Context) {
context.startActivity(intent)
true
} catch (e: Exception) {
- Log.e(TAG, "Failed to open battery optimization settings", e)
+ AppLogger.e(TAG, "Failed to open battery optimization settings", e)
// Fallback to general settings
try {
val fallbackIntent = Intent(Settings.ACTION_SETTINGS).apply {
@@ -119,7 +119,7 @@ class DeviceInfoHelper(private val context: Context) {
context.startActivity(fallbackIntent)
false // Indicate fallback was used
} catch (e2: Exception) {
- Log.e(TAG, "Failed to open general settings", e2)
+ AppLogger.e(TAG, "Failed to open general settings", e2)
throw e2 // Let caller handle this
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/FileOperations.kt b/apps/mobile/android/app/src/main/java/com/colota/util/FileOperations.kt
index 7d3058ef..b1a717e9 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/util/FileOperations.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/FileOperations.kt
@@ -9,9 +9,7 @@ import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
-import com.Colota.BuildConfig
import android.net.Uri
-import android.util.Log
import androidx.core.content.FileProvider
import com.facebook.react.bridge.*
import java.io.File
@@ -69,12 +67,10 @@ class FileOperations(private val context: ReactApplicationContext) {
try {
if (file.exists()) {
file.delete()
- if (BuildConfig.DEBUG) {
- Log.d("FileOperations", "Cleaned up export file: ${file.name}")
- }
+ AppLogger.d("FileOperations", "Cleaned up export file: ${file.name}")
}
} catch (e: Exception) {
- Log.w("FileOperations", "Failed to cleanup file", e)
+ AppLogger.w("FileOperations", "Failed to cleanup file")
}
}, 60000)
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt
index 9bc80dc4..9720407c 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt
@@ -8,7 +8,7 @@ package com.Colota.util
import android.content.Context
import android.content.SharedPreferences
import android.util.Base64
-import android.util.Log
+import com.Colota.util.AppLogger
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import org.json.JSONObject
@@ -48,7 +48,7 @@ class SecureStorageHelper private constructor(context: Context) {
prefs = try {
createEncryptedPrefs(context)
} catch (e: Exception) {
- Log.e(TAG, "EncryptedSharedPreferences corrupted, clearing and retrying", e)
+ AppLogger.e(TAG, "EncryptedSharedPreferences corrupted, clearing and retrying", e)
context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit().clear().commit()
createEncryptedPrefs(context)
}
@@ -117,7 +117,7 @@ class SecureStorageHelper private constructor(context: Context) {
}
}
} catch (e: Exception) {
- Log.w(TAG, "Failed to parse custom headers", e)
+ AppLogger.w(TAG, "Failed to parse custom headers")
}
}
diff --git a/apps/mobile/src/screens/AboutScreen.tsx b/apps/mobile/src/screens/AboutScreen.tsx
index b1e6921e..c7a3becf 100644
--- a/apps/mobile/src/screens/AboutScreen.tsx
+++ b/apps/mobile/src/screens/AboutScreen.tsx
@@ -4,7 +4,7 @@
*/
import React, { useState, useEffect, useCallback } from "react"
-import { Text, StyleSheet, View, ScrollView, Linking, Pressable, Image } from "react-native"
+import { Text, StyleSheet, View, ScrollView, Linking, Pressable, Image, ActivityIndicator } from "react-native"
import { ScreenProps, ThemeColors } from "../types/global"
import { useTheme } from "../hooks/useTheme"
import { ChevronRight, Bug, FileText, Code, ScrollText, MessageCircle, Copy, Check } from "lucide-react-native"
@@ -14,7 +14,7 @@ import { useTimeout } from "../hooks/useTimeout"
import NativeLocationService from "../services/NativeLocationService"
import icon from "../assets/icons/icon.png"
import { REPO_URL, ISSUES_URL, PRIVACY_POLICY_URL } from "../constants"
-import { logger } from "../utils/logger"
+import { logger, getLogEntries, setLogCollecting } from "../utils/logger"
// Helper function to map SDK to Android version
function getAndroidVersion(sdkVersion: number): string {
@@ -80,6 +80,7 @@ export function AboutScreen({}: ScreenProps) {
const [showDebugInfo, setShowDebugInfo] = useState(false)
const [tapCount, setTapCount] = useState(0)
const [copied, setCopied] = useState(false)
+ const [exportingLogs, setExportingLogs] = useState(false)
const copiedTimeout = useTimeout()
const [deviceInfo, setDeviceInfo] = useState<{
model: string
@@ -94,13 +95,17 @@ export function AboutScreen({}: ScreenProps) {
// Load persisted debug mode
useEffect(() => {
NativeLocationService.getSetting(DEBUG_MODE_SETTING_KEY, "false").then((value) => {
- if (value === "true") setShowDebugInfo(true)
+ if (value === "true") {
+ setShowDebugInfo(true)
+ setLogCollecting(true)
+ }
})
}, [])
// Persist debug mode changes
const toggleDebugMode = useCallback((enabled: boolean) => {
setShowDebugInfo(enabled)
+ setLogCollecting(enabled)
NativeLocationService.saveSetting(DEBUG_MODE_SETTING_KEY, String(enabled))
}, [])
@@ -175,6 +180,68 @@ export function AboutScreen({}: ScreenProps) {
}
}, [buildConfig, deviceInfo, copiedTimeout])
+ const handleExportLogs = useCallback(async () => {
+ if (!buildConfig) return
+ setExportingLogs(true)
+ try {
+ const entries = getLogEntries()
+ const lines: string[] = [
+ "=== Colota Debug Log Export ===",
+ `Exported: ${new Date().toISOString()}`,
+ "",
+ "--- App Info ---",
+ `Version: ${buildConfig.VERSION_NAME} (${buildConfig.VERSION_CODE})`,
+ ""
+ ]
+
+ if (deviceInfo) {
+ lines.push(
+ "--- Device Info ---",
+ `OS: Android ${deviceInfo.systemVersion} (API ${deviceInfo.apiLevel})`,
+ `Device: ${deviceInfo.brand} ${deviceInfo.model}`,
+ ""
+ )
+ }
+
+ // Merge JS and native logs chronologically
+ const merged: { time: number; line: string }[] = []
+
+ for (const entry of entries) {
+ merged.push({
+ time: new Date(entry.timestamp).getTime(),
+ line: `[${entry.timestamp}] [JS] ${entry.level} ${entry.message}`
+ })
+ }
+
+ try {
+ const nativeLogs = await NativeLocationService.getNativeLogs()
+ const year = new Date().getFullYear()
+ for (const raw of nativeLogs) {
+ // Logcat threadtime format: "MM-DD HH:MM:SS.mmm PID TID LEVEL TAG: message"
+ const match = raw.match(/^(\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2}\.\d{3})/)
+ const time = match ? new Date(`${year}-${match[1]}T${match[2]}`).getTime() : 0
+ merged.push({ time, line: `[NATIVE] ${raw}` })
+ }
+ } catch {
+ // native logs are best-effort
+ }
+
+ merged.sort((a, b) => a.time - b.time)
+ lines.push(`--- Log Entries (${merged.length}) ---`, "")
+ for (const entry of merged) {
+ lines.push(entry.line)
+ }
+
+ const fileName = `colota_logs_${Date.now()}.txt`
+ const filePath = await NativeLocationService.writeFile(fileName, lines.join("\n"))
+ await NativeLocationService.shareFile(filePath, "text/plain", "Colota Debug Logs")
+ } catch (err) {
+ logger.error("[AboutScreen] Log export failed:", err)
+ } finally {
+ setExportingLogs(false)
+ }
+ }, [buildConfig, deviceInfo])
+
// Fallback if buildConfig is not available
if (!buildConfig) {
return (
@@ -326,15 +393,46 @@ export function AboutScreen({}: ScreenProps) {
</View>
)}
- <Pressable
- style={({ pressed }) => [styles.copyButton, { borderColor: colors.border }, pressed && { opacity: 0.7 }]}
- onPress={handleCopyDebugInfo}
- >
- {copied ? <Check size={16} color={colors.success} /> : <Copy size={16} color={colors.primaryDark} />}
- <Text style={[styles.copyButtonText, { color: copied ? colors.success : colors.primaryDark }]}>
- {copied ? "Copied!" : "Copy Debug Info"}
+ <View style={styles.debugActions}>
+ <Pressable
+ style={({ pressed }) => [
+ styles.copyButton,
+ { borderColor: colors.border },
+ pressed && { opacity: 0.7 }
+ ]}
+ onPress={handleCopyDebugInfo}
+ >
+ {copied ? <Check size={16} color={colors.success} /> : <Copy size={16} color={colors.primaryDark} />}
+ <Text style={[styles.copyButtonText, { color: copied ? colors.success : colors.primaryDark }]}>
+ {copied ? "Copied!" : "Copy Debug Info"}
+ </Text>
+ </Pressable>
+
+ <Pressable
+ style={({ pressed }) => [
+ styles.copyButton,
+ { borderColor: colors.border },
+ pressed && { opacity: 0.7 },
+ exportingLogs && { opacity: 0.5 }
+ ]}
+ onPress={handleExportLogs}
+ disabled={exportingLogs}
+ >
+ {exportingLogs ? (
+ <ActivityIndicator size={16} color={colors.primaryDark} />
+ ) : (
+ <FileText size={16} color={colors.primaryDark} />
+ )}
+ <Text style={[styles.copyButtonText, { color: colors.primaryDark }]}>
+ Export Logs ({getLogEntries().length})
+ </Text>
+ </Pressable>
+
+ <Text style={[styles.logHint, { color: colors.textLight }]}>
+ App activity is being recorded while debug mode is on. Try to reproduce the issue, then tap Export Logs.
+ When you're done, tap "Debug Mode" above to turn it off and stop recording.
</Text>
- </Pressable>
+ </View>
</>
)}
@@ -429,12 +527,15 @@ const styles = StyleSheet.create({
fontSize: 12,
...fonts.semiBold
},
+ debugActions: {
+ gap: 10,
+ marginTop: 16
+ },
copyButton: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 8,
- marginTop: 16,
paddingVertical: 12,
borderRadius: 12,
borderWidth: 1
@@ -442,5 +543,11 @@ const styles = StyleSheet.create({
copyButtonText: {
fontSize: 14,
...fonts.semiBold
+ },
+ logHint: {
+ fontSize: 12,
+ textAlign: "center",
+ fontStyle: "italic",
+ lineHeight: 16
}
})
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index 396d1859..7a85bea7 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -579,6 +579,14 @@ class NativeLocationService {
return LocationServiceModule.getCacheDirectory()
}
+ /**
+ * Returns native (Kotlin) Logcat entries for the app's process
+ */
+ static async getNativeLogs(): Promise<string[]> {
+ this.ensureModule()
+ return LocationServiceModule.getNativeLogs()
+ }
+
// ============================================================================
// SECURE STORAGE (Auth & Headers)
// ============================================================================
diff --git a/apps/mobile/src/utils/__tests__/logger.test.ts b/apps/mobile/src/utils/__tests__/logger.test.ts
index 8a3b4055..ea3a705a 100644
--- a/apps/mobile/src/utils/__tests__/logger.test.ts
+++ b/apps/mobile/src/utils/__tests__/logger.test.ts
@@ -84,4 +84,97 @@ describe("logger", () => {
expect(console.error).toHaveBeenCalledWith("visible error")
})
})
+
+ describe("log buffer", () => {
+ beforeEach(() => {
+ ;(globalThis as any).__DEV__ = true
+ })
+
+ function loadBuffer() {
+ const mod = require("../logger")
+ mod.setLogCollecting(true)
+ mod.clearLogBuffer()
+ return {
+ logger: mod.logger,
+ getLogEntries: mod.getLogEntries,
+ clearLogBuffer: mod.clearLogBuffer,
+ setLogCollecting: mod.setLogCollecting
+ }
+ }
+
+ it("captures log entries", () => {
+ const { logger, getLogEntries } = loadBuffer()
+ logger.info("test message")
+
+ const entries = getLogEntries()
+ expect(entries).toHaveLength(1)
+ expect(entries[0].level).toBe("INFO")
+ expect(entries[0].message).toBe("test message")
+ expect(entries[0].timestamp).toBeTruthy()
+ })
+
+ it("captures all log levels", () => {
+ const { logger, getLogEntries } = loadBuffer()
+ logger.debug("d")
+ logger.info("i")
+ logger.warn("w")
+ logger.error("e")
+
+ const entries = getLogEntries()
+ expect(entries).toHaveLength(4)
+ expect(entries.map((e: any) => e.level)).toEqual(["DEBUG", "INFO", "WARN", "ERROR"])
+ })
+
+ it("collects all entries without limit", () => {
+ const { logger, getLogEntries } = loadBuffer()
+ for (let i = 0; i < 600; i++) {
+ logger.info(`msg ${i}`)
+ }
+
+ const entries = getLogEntries()
+ expect(entries).toHaveLength(600)
+ expect(entries[0].message).toBe("msg 0")
+ expect(entries[entries.length - 1].message).toBe("msg 599")
+ })
+
+ it("clearLogBuffer empties the buffer", () => {
+ const { logger, getLogEntries, clearLogBuffer } = loadBuffer()
+ logger.info("test")
+ expect(getLogEntries()).toHaveLength(1)
+
+ clearLogBuffer()
+ expect(getLogEntries()).toHaveLength(0)
+ })
+
+ it("formats Error objects", () => {
+ const { logger, getLogEntries } = loadBuffer()
+ logger.error("failed:", new Error("something broke"))
+
+ expect(getLogEntries()[0].message).toBe("failed: something broke")
+ })
+
+ it("formats objects as JSON", () => {
+ const { logger, getLogEntries } = loadBuffer()
+ logger.info("data:", { key: "value" })
+
+ expect(getLogEntries()[0].message).toBe('data: {"key":"value"}')
+ })
+
+ it("does not collect when collecting is disabled", () => {
+ const { logger, getLogEntries, setLogCollecting } = loadBuffer()
+ setLogCollecting(false)
+ logger.info("should not be captured")
+
+ expect(getLogEntries()).toHaveLength(0)
+ })
+
+ it("clears buffer when collecting is disabled", () => {
+ const { logger, getLogEntries, setLogCollecting } = loadBuffer()
+ logger.info("captured")
+ expect(getLogEntries()).toHaveLength(1)
+
+ setLogCollecting(false)
+ expect(getLogEntries()).toHaveLength(0)
+ })
+ })
})
diff --git a/apps/mobile/src/utils/logger.ts b/apps/mobile/src/utils/logger.ts
index e7a8ac5e..15cf04bc 100644
--- a/apps/mobile/src/utils/logger.ts
+++ b/apps/mobile/src/utils/logger.ts
@@ -4,19 +4,81 @@
*
* - debug/info: Only logged in development
* - warn/error: Always logged
+ *
+ * When log collection is enabled (via debug mode), entries are captured
+ * in a buffer for export via the About screen.
*/
+type LogLevel = "DEBUG" | "INFO" | "WARN" | "ERROR"
+
+export interface LogEntry {
+ timestamp: string
+ level: LogLevel
+ message: string
+}
+
+let collecting = false
+const logBuffer: LogEntry[] = []
+
+function formatArgs(args: unknown[]): string {
+ return args
+ .map((arg) => {
+ if (arg instanceof Error) return arg.message
+ if (typeof arg === "object" && arg !== null) {
+ try {
+ return JSON.stringify(arg)
+ } catch {
+ return String(arg)
+ }
+ }
+ return String(arg)
+ })
+ .join(" ")
+}
+
+function pushEntry(level: LogLevel, args: unknown[]): void {
+ if (!collecting) return
+ logBuffer.push({
+ timestamp: new Date().toISOString(),
+ level,
+ message: formatArgs(args)
+ })
+}
+
+export function setLogCollecting(enabled: boolean): void {
+ collecting = enabled
+ if (!enabled) {
+ logBuffer.length = 0
+ }
+}
+
+export function isLogCollecting(): boolean {
+ return collecting
+}
+
+export function getLogEntries(): readonly LogEntry[] {
+ return logBuffer
+}
+
+export function clearLogBuffer(): void {
+ logBuffer.length = 0
+}
+
export const logger = {
debug: (...args: unknown[]) => {
+ pushEntry("DEBUG", args)
if (__DEV__) console.log(...args)
},
info: (...args: unknown[]) => {
+ pushEntry("INFO", args)
if (__DEV__) console.log(...args)
},
warn: (...args: unknown[]) => {
+ pushEntry("WARN", args)
console.warn(...args)
},
error: (...args: unknown[]) => {
+ pushEntry("ERROR", args)
console.error(...args)
}
}