Skip to content

Colota - Android GPS Location tracker

feat(logging): add opt-in persistent file logger (#422)

Max Dietrichb8d27a5311f6
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 0d1628a1..182c3084 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -361,7 +361,7 @@ Supporting utilities in `mapUtils.ts`:
| Utility | Purpose |
| --- | --- |
-| `logger` | Environment-aware logging - suppresses debug/info console output in production via `__DEV__`, always logs warn/error to console. All levels are always captured in a ring buffer (2000 entries) for the Activity Log screen |
+| `logger` | Environment-aware logging - suppresses debug/info console output in production via `__DEV__`, always logs warn/error to console. All levels are always captured in a ring buffer (2000 entries) for the Logging screen |
| `geo` | Haversine distance, speed/distance/duration/time formatting with configurable unit system (metric/imperial) and time format (12h/24h), auto-detected from locale on first use |
| `exportConverters` | Converts location data to CSV, GeoJSON, GPX, and KML export formats (flat and trip-aware variants) |
| `trips` | Trip segmentation via time-gap detection (15-min threshold) with distance computation, trip stats (avg speed, elevation gain/loss), and trip color assignment |
diff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.md
index bee53a73..f81f21ac 100644
--- a/apps/docs/docs/guides/troubleshooting.md
+++ b/apps/docs/docs/guides/troubleshooting.md
@@ -49,16 +49,31 @@ If **Test Connection** fails, the message points at the specific layer that brok
| `Connection timed out` | Network layer: the server didn't respond in time | Check connectivity, firewall, server availability |
| `Local network access denied` | Permission: Android 16+ blocked the connection to a private IP | Grant Local Network Access (Settings -> Apps -> Colota -> Permissions) |
-## Exporting app logs
+## Viewing and exporting logs
-You can view and export app logs directly from the device for bug reports:
+**Settings > Logging** shows app log entries in two tabs.
-1. Go to **Settings > Activity Log**
-2. Browse logs in the viewer - filter by level or search for keywords
-3. Tap the share button to export a text file with all log entries
-4. The export includes app version, device info and all collected log messages
+### Live tab
-Logs are always collected in the background using a fixed-size ring buffer.
+This is the easiest way to view and share recent logs.
+
+1. Open **Settings > Logging** (the Live tab opens by default)
+2. Scroll through recent entries - the chips at the top filter by severity (`DEBUG` / `INFO` / `WARN` / `ERROR`)
+3. Tap the share icon (top right) to save a text file containing the recent entries plus your app version and device info
+
+### File tab
+
+For bugs that take a while to happen:
+
+1. Open **Settings > Logging** and switch to the **File** tab
+2. Turn on **Persistent file logging**
+3. Use the app until the problem happens again
+4. Come back to the **File** tab and tap **Export log file...** - pick where to save it
+5. Open a bug report at [github.com/dietrichmax/colota/issues](https://github.com/dietrichmax/colota/issues/new) and attach the saved `colota-log-*.txt`
+
+**Heads up:** log files can contain your location coordinates. Please check the content of the file before sharing it.
+
+The file grows the whole time logging is on. Tap **Clear log files** on the **File** tab to reset it.
## Debugging with adb logcat
diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.md
index 244a80ee..1fba8f61 100644
--- a/apps/docs/docs/introduction.md
+++ b/apps/docs/docs/introduction.md
@@ -51,7 +51,7 @@ Colota has twenty-two screens, each focused on a specific task:
| **Data Management** | Clear sent history, delete old data, vacuum the database |
| **Backup & Restore** | Create or restore a single password-encrypted `.colota` archive of all data (locations, settings, geofences, credentials) |
| **Setup Import** | Confirmation screen for deep link configuration imports (`colota://setup`) |
-| **Activity Log** | In-app log viewer with level filtering, search, and export for bug reports |
+| **Logging** | In-app activity log viewer (level filtering, search, export) plus opt-in persistent file logging |
| **About** | App version, device info, links to repository and privacy policy |
## Screenshots
diff --git a/apps/docs/src/pages/privacy-policy.md b/apps/docs/src/pages/privacy-policy.md
index 89cd4340..724b55ba 100644
--- a/apps/docs/src/pages/privacy-policy.md
+++ b/apps/docs/src/pages/privacy-policy.md
@@ -52,6 +52,8 @@ Collected data is stored in a local SQLite database on your device. The data is
If you configure auto-export, the App will write export files (CSV, GeoJSON, GPX, or KML) to a directory you select on your device. No data leaves your device as part of this process.
+If you enable persistent file logging in Logging -> File, the App writes diagnostic log entries (which may include location coordinates and other sensitive information) to a private file in app storage. The file is removed when the App is uninstalled. Logs are never sent automatically; sharing them requires explicit user action via the "Export log file..." flow.
+
Authentication credentials (if configured) are encrypted.
### Importing Data
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx
index 4c1e6920..062d52ba 100644
--- a/apps/mobile/App.tsx
+++ b/apps/mobile/App.tsx
@@ -145,9 +145,9 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [
title: "Offline Maps"
},
{
- name: "Activity Log",
+ name: "Logging",
component: ActivityLogScreen,
- title: "Activity Log"
+ title: "Logging"
},
{
name: "Backup & Restore",
diff --git a/apps/mobile/android/app/src/main/java/com/colota/MainApplication.kt b/apps/mobile/android/app/src/main/java/com/colota/MainApplication.kt
index 5b5ad663..b00e7a1c 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/MainApplication.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/MainApplication.kt
@@ -14,6 +14,8 @@ import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.Colota.backup.BackupOrphanCleanup
import com.Colota.bridge.LocationServicePackage
+import com.Colota.util.FileLoggerInitializer
+import com.Colota.util.MemoryPressureLogger
class MainApplication : Application(), ReactApplication {
@@ -26,7 +28,13 @@ class MainApplication : Application(), ReactApplication {
override fun onCreate() {
super.onCreate()
+ FileLoggerInitializer.start(this)
loadReactNative(this)
BackupOrphanCleanup.start(this)
}
+
+ override fun onTrimMemory(level: Int) {
+ super.onTrimMemory(level)
+ MemoryPressureLogger.log(level)
+ }
}
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 fee63319..d8a52c7c 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
@@ -29,6 +29,7 @@ import com.Colota.util.DeviceInfoHelper
import com.Colota.export.AutoExportConfig
import com.Colota.export.AutoExportScheduler
import com.Colota.export.ExportConverters
+import com.Colota.util.AppFileLogger
import com.Colota.util.FileOperations
import com.Colota.util.AppLogger
import com.Colota.util.SecureStorageHelper
@@ -224,16 +225,19 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
override fun getName(): String = "LocationServiceModule"
override fun onHostResume() {
+ AppLogger.i(TAG, "RN host resumed (app foregrounded)")
isAppInForeground = true
registerChargingReceiver()
}
override fun onHostPause() {
+ AppLogger.i(TAG, "RN host paused (app backgrounded)")
isAppInForeground = false
unregisterChargingReceiver()
}
override fun onHostDestroy() {
+ AppLogger.i(TAG, "RN host destroyed")
isAppInForeground = false
unregisterChargingReceiver()
}
@@ -840,18 +844,68 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@ReactMethod
fun getNativeLogs(promise: Promise) = executeAsync(promise) {
- val process = Runtime.getRuntime().exec(arrayOf("/system/bin/logcat", "-d", "-v", "threadtime"))
- try {
- val lines = process.inputStream.bufferedReader().readLines()
- process.waitFor(10, java.util.concurrent.TimeUnit.SECONDS)
+ if (AppFileLogger.isEnabled()) {
Arguments.createArray().apply {
- lines.filter { "Colota." in it }.forEach { pushString(it) }
+ AppFileLogger.getRecentEntries().forEach { pushString(it) }
+ }
+ } else {
+ val process = Runtime.getRuntime().exec(arrayOf("/system/bin/logcat", "-d", "-v", "threadtime"))
+ try {
+ val lines = process.inputStream.bufferedReader().readLines()
+ process.waitFor(10, java.util.concurrent.TimeUnit.SECONDS)
+ Arguments.createArray().apply {
+ lines.filter { "Colota." in it }.forEach { pushString(it) }
+ }
+ } finally {
+ process.destroy()
}
- } finally {
- process.destroy()
}
}
+ @ReactMethod
+ fun setFileLoggingEnabled(enabled: Boolean, promise: Promise) = executeAsync(promise) {
+ dbHelper.saveSetting("debugFileLoggingEnabled", if (enabled) "true" else "false")
+ AppFileLogger.setEnabled(enabled)
+ null
+ }
+
+ @ReactMethod
+ fun clearFileLog(promise: Promise) = executeAsync(promise) {
+ AppFileLogger.clear()
+ null
+ }
+
+ @ReactMethod
+ fun getFileLogSize(promise: Promise) = executeAsync(promise) {
+ AppFileLogger.currentSizeBytes().toDouble()
+ }
+
+ @ReactMethod
+ fun exportFileLogToUri(treeUriString: String, promise: Promise) = executeAsync(promise) {
+ AppFileLogger.flushNow()
+ // Oldest segment first so the exported file reads chronologically.
+ val sources = AppFileLogger.logFiles()
+ if (sources.isEmpty()) return@executeAsync null
+
+ val treeUri = android.net.Uri.parse(treeUriString)
+ val tree = androidx.documentfile.provider.DocumentFile.fromTreeUri(reactApplicationContext, treeUri)
+ ?: throw Exception("Invalid tree URI")
+
+ val timestamp = java.text.SimpleDateFormat("yyyyMMdd-HHmmss", java.util.Locale.US)
+ .format(java.util.Date())
+ val fileName = "colota-log-$timestamp.txt"
+ val doc = tree.createFile("text/plain", fileName)
+ ?: throw Exception("Could not create document in selected directory")
+
+ reactApplicationContext.contentResolver.openOutputStream(doc.uri)?.use { output ->
+ for (source in sources) {
+ source.inputStream().use { input -> input.copyTo(output) }
+ }
+ } ?: throw Exception("Could not open output stream")
+
+ doc.uri.toString()
+ }
+
// =========================================================================
// AUTO-EXPORT
// =========================================================================
@@ -946,9 +1000,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@ReactMethod
fun exportToFile(format: String, promise: Promise) = executeAsync(promise) {
val ext = ExportConverters.extensionFor(format)
- val dateStr = java.text.SimpleDateFormat("yyyy-MM-dd_HHmm", java.util.Locale.US)
- .format(java.util.Date())
- val tempFile = java.io.File(reactApplicationContext.cacheDir, "manual_export_$dateStr$ext")
+ val tempFile = java.io.File(reactApplicationContext.cacheDir, "manual_export_${ExportConverters.exportFilenameStamp()}$ext")
val totalRows = ExportConverters.exportToFile(dbHelper, format, tempFile)
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
index e46ebe22..0a4990c1 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
@@ -121,9 +121,7 @@ class AutoExportWorker(
val ext = ExportConverters.extensionFor(config.format)
val dirUri = Uri.parse(config.uri)
- val dateStr = java.text.SimpleDateFormat("yyyy-MM-dd_HHmm", java.util.Locale.US)
- .format(java.util.Date())
- val fileName = "colota_export_$dateStr$ext"
+ val fileName = "colota_export_${ExportConverters.exportFilenameStamp()}$ext"
// Write to cache first, then copy to SAF.
val tempFile = File(appContext.cacheDir, "auto_export_temp$ext")
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt
index 02d916b1..2e4e1d72 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt
@@ -50,6 +50,10 @@ object ExportConverters {
const val PAGE_SIZE = 10_000
+ /** Filename-safe stamp for export files (e.g. `2026-05-28_1430`). */
+ fun exportFilenameStamp(): String =
+ SimpleDateFormat("yyyy-MM-dd_HHmm", Locale.US).format(Date())
+
private fun isoTime(unixSeconds: Long): String {
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
sdf.timeZone = TimeZone.getTimeZone("UTC")
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 96d57a66..83dc82cc 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
@@ -463,21 +463,34 @@ class LocationForegroundService : Service() {
private fun isLocationUpdatesRegistered(): Boolean = locationUpdateCallback != null
- /**
- * Diagnostic-only periodic logger. Records "time since last GPS fix" every 5 minutes
- * to the activity log so silent stalls (eg stale FLP binding after long uptime) become
- * visible in user-exported logs. Does not take any recovery action - data only.
- */
+ /** Logs a state snapshot every 5 minutes so silent stalls and pause/stop gaps are visible
+ * in user-exported logs. Data-only; no recovery action. */
private fun startTrackingHeartbeatLogger() {
trackingHeartbeatJob?.cancel()
val scope = serviceScope ?: return
trackingHeartbeatJob = scope.launch {
while (isActive) {
delay(TRACKING_HEARTBEAT_INTERVAL_MS)
- if (isWifiPaused || isMotionlessPaused) continue
- if (locationUpdateCallback == null) continue
- val sinceLastFix = SystemClock.elapsedRealtime() - lastFixAtMs
- AppLogger.i(TAG, "Tracking alive: ${sinceLastFix / 1000}s since last fix")
+ // Catch here so a DB or system-service hiccup doesn't kill the heartbeat loop.
+ try {
+ val state = when {
+ locationUpdateCallback == null -> "STOPPED"
+ isWifiPaused && isMotionlessPaused -> "PAUSED(wifi+motionless)"
+ isWifiPaused -> "PAUSED(wifi)"
+ isMotionlessPaused -> "PAUSED(motionless)"
+ else -> "ACTIVE"
+ }
+ val sinceLastFix = SystemClock.elapsedRealtime() - lastFixAtMs
+ val (battery, _) = deviceInfoHelper.getCachedBatteryStatus()
+ val doze = (getSystemService(POWER_SERVICE) as? PowerManager)?.isDeviceIdleMode ?: false
+ AppLogger.i(TAG,
+ "Heartbeat state=$state, ${sinceLastFix / 1000}s since last fix, " +
+ "queue=${dbHelper.getStats().queued}, batt=$battery%, " +
+ "profile=${profileManager.getActiveProfileName() ?: "default"}, doze=$doze"
+ )
+ } catch (e: Exception) {
+ AppLogger.w(TAG, "Heartbeat snapshot failed: ${e.message}")
+ }
}
}
}
@@ -1253,7 +1266,7 @@ class LocationForegroundService : Service() {
AppLogger.d(TAG, buildString {
append("Config loaded: interval=${config.interval}ms, distance=${config.minUpdateDistance}m, accuracy=${config.accuracyThreshold}m")
- append(", endpoint=${if (config.endpoint.isBlank()) "NOT CONFIGURED" else config.endpoint}")
+ append(", endpoint=${if (config.endpoint.isBlank()) "NOT CONFIGURED" else AppLogger.maskSensitiveUrlValues(config.endpoint)}")
append(", offline=${config.isOfflineMode}, sync=${if (config.syncIntervalSeconds == 0) "instant" else "${config.syncIntervalSeconds}s"}")
if (parsedFieldMap.isNotEmpty()) append(", fieldMap=${parsedFieldMap.size} mappings")
})
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 d4b2b144..ef2af29b 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
@@ -163,7 +163,7 @@ class NetworkManager(private val context: Context) {
) {
if (!BuildConfig.DEBUG) return
AppLogger.d(TAG, "=== HTTP REQUEST ===")
- AppLogger.d(TAG, "Endpoint: ${if (isGet) targetUrl else resolvedEndpoint}")
+ AppLogger.d(TAG, "Endpoint: ${AppLogger.maskSensitiveUrlValues(if (isGet) targetUrl.toString() else resolvedEndpoint)}")
AppLogger.d(TAG, "Method: ${connection.requestMethod}")
AppLogger.d(TAG, "Headers:")
connection.requestProperties.forEach { (key, values) ->
@@ -193,12 +193,12 @@ class NetworkManager(private val context: Context) {
val url = try {
URL(resolvedEndpoint)
} catch (e: Exception) {
- AppLogger.e(TAG, "Invalid URL: $resolvedEndpoint")
+ AppLogger.e(TAG, "Invalid URL: ${AppLogger.maskSensitiveUrlValues(resolvedEndpoint)}")
return@withContext BatchResult.NetworkError
}
if (!UrlSafety.isValidProtocol(resolvedEndpoint)) {
- AppLogger.e(TAG, "Protocol blocked or invalid: $endpoint")
+ AppLogger.e(TAG, "Protocol blocked or invalid: ${AppLogger.maskSensitiveUrlValues(endpoint)}")
return@withContext BatchResult.NetworkError
}
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 4f63dd2c..ce34cb8b 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
@@ -71,7 +71,7 @@ class SyncManager(
}
fun startPeriodicSync() {
- AppLogger.d(TAG, "Starting periodic sync: interval=${syncIntervalSeconds}s, endpoint=${if (endpoint.isBlank()) "NONE" else endpoint}")
+ AppLogger.d(TAG, "Starting periodic sync: interval=${syncIntervalSeconds}s, endpoint=${if (endpoint.isBlank()) "NONE" else AppLogger.maskSensitiveUrlValues(endpoint)}")
syncJob = scope.launch {
while (isActive) {
val baseDelay = calculateNextSyncDelay()
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/AppFileLogger.kt b/apps/mobile/android/app/src/main/java/com/colota/util/AppFileLogger.kt
new file mode 100644
index 00000000..a7151c02
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/AppFileLogger.kt
@@ -0,0 +1,237 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+package com.Colota.util
+
+import android.content.Context
+import androidx.annotation.VisibleForTesting
+import java.io.BufferedWriter
+import java.io.File
+import java.io.FileWriter
+import java.io.IOException
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+import java.util.concurrent.Callable
+import java.util.concurrent.Executors
+import java.util.concurrent.LinkedBlockingQueue
+import java.util.concurrent.ThreadPoolExecutor
+import java.util.concurrent.TimeUnit
+
+class AppFileLogger @VisibleForTesting internal constructor(
+ private val logDir: File,
+ flushIntervalMs: Long = FLUSH_INTERVAL_MS,
+ private val maxFileBytes: Long = MAX_FILE_BYTES
+) {
+ private val timestampFormat = SimpleDateFormat(TIMESTAMP_PATTERN, Locale.US)
+
+ private val writeExecutor = ThreadPoolExecutor(
+ 1, 1, 0L, TimeUnit.MILLISECONDS,
+ LinkedBlockingQueue<Runnable>(MAX_QUEUE_SIZE),
+ { r -> Thread(r, "AppFileLogger-write").apply { isDaemon = true } },
+ ThreadPoolExecutor.DiscardPolicy()
+ )
+ private val flushExecutor = Executors.newSingleThreadScheduledExecutor { r ->
+ Thread(r, "AppFileLogger-flush").apply { isDaemon = true }
+ }
+
+ @Volatile private var enabled = false
+
+ private var bufferedWriter: BufferedWriter? = null
+
+ /** Approximate byte count of the active file; drives rotation without a stat on every write. */
+ private var bytesWritten: Long = 0L
+
+ init {
+ logDir.mkdirs()
+ // Flush on the write thread so bufferedWriter is only ever touched there (no cross-thread race).
+ flushExecutor.scheduleAtFixedRate(
+ { writeExecutor.execute { flushSafely() } }, flushIntervalMs, flushIntervalMs, TimeUnit.MILLISECONDS
+ )
+ }
+
+ fun setEnabled(enabled: Boolean) {
+ this.enabled = enabled
+ if (!enabled) writeExecutor.execute {
+ flushSafely()
+ closeWriter()
+ }
+ }
+
+ fun log(level: String, tag: String, msg: String) {
+ if (!enabled) return
+ val timestamp = System.currentTimeMillis()
+ writeExecutor.execute { writeEntry(timestamp, level, tag, msg) }
+ }
+
+ fun flushNow() {
+ onWriteThread(Unit) { flushSafely() }
+ }
+
+ fun isEnabled(): Boolean = enabled
+
+ fun getRecentEntries(): List<String> = onWriteThread(emptyList()) {
+ flushSafely()
+ // Newest file first so the live view keeps history right after a rotation empties the active file.
+ val collected = ArrayList<String>()
+ var budget = LIVE_TAIL_MAX_BYTES
+ for (file in listOf(File(logDir, LOG_FILE), File(logDir, LOG_FILE_PREV))) {
+ if (collected.size >= LIVE_TAIL_LINES || budget <= 0L) break
+ if (!file.exists()) continue
+ val lines = if (file.length() <= budget) file.readLines() else tailRead(file, budget)
+ budget -= file.length()
+ collected.addAll(0, lines)
+ }
+ if (collected.size > LIVE_TAIL_LINES) collected.takeLast(LIVE_TAIL_LINES) else collected
+ }
+
+ private fun tailRead(file: File, maxBytes: Long): List<String> {
+ val start = (file.length() - maxBytes).coerceAtLeast(0L)
+ return file.inputStream().use { stream ->
+ if (start > 0L) stream.skip(start)
+ val lines = stream.bufferedReader().readLines()
+ if (start > 0L && lines.isNotEmpty()) lines.drop(1) else lines
+ }
+ }
+
+ fun currentSizeBytes(): Long = onWriteThread(0L) {
+ flushSafely()
+ File(logDir, LOG_FILE).length() + File(logDir, LOG_FILE_PREV).length()
+ }
+
+ fun clear() {
+ onWriteThread(Unit) {
+ closeWriter()
+ File(logDir, LOG_FILE).delete()
+ File(logDir, LOG_FILE_PREV).delete()
+ bytesWritten = 0L
+ }
+ }
+
+ /** Log segment files, oldest first, for export. Existing and non-empty only. */
+ fun logFiles(): List<File> =
+ listOf(File(logDir, LOG_FILE_PREV), File(logDir, LOG_FILE)).filter { it.exists() && it.length() > 0L }
+
+ @VisibleForTesting
+ internal fun shutdown() {
+ flushExecutor.shutdownNow()
+ onWriteThread(Unit) {
+ flushSafely()
+ closeWriter()
+ }
+ writeExecutor.shutdownNow()
+ }
+
+ private fun writeEntry(timestamp: Long, level: String, tag: String, msg: String) {
+ try {
+ val writer = bufferedWriter ?: openWriter()
+ val line = "${timestampFormat.format(Date(timestamp))} $level/$tag: $msg"
+ writer.write(line)
+ writer.newLine()
+ bytesWritten += line.length + 1
+ if (bytesWritten >= maxFileBytes) rotate()
+ } catch (_: IOException) {
+ // Cannot recursively log from here.
+ }
+ }
+
+ private fun openWriter(): BufferedWriter {
+ logDir.mkdirs()
+ val file = File(logDir, LOG_FILE)
+ bytesWritten = file.length()
+ val w = BufferedWriter(FileWriter(file, true))
+ bufferedWriter = w
+ return w
+ }
+
+ // Rolls the active file to LOG_FILE_PREV; the next write opens a fresh one. Bounds disk to
+ // ~2x maxFileBytes. On the write thread, so no locking.
+ private fun rotate() {
+ closeWriter()
+ val current = File(logDir, LOG_FILE)
+ val previous = File(logDir, LOG_FILE_PREV)
+ previous.delete()
+ current.renameTo(previous)
+ bytesWritten = 0L
+ }
+
+ private fun closeWriter() {
+ try {
+ bufferedWriter?.close()
+ } catch (_: Exception) {
+ }
+ bufferedWriter = null
+ }
+
+ private fun flushSafely() {
+ try {
+ bufferedWriter?.flush()
+ } catch (_: Exception) {
+ }
+ }
+
+ private fun <T> onWriteThread(fallback: T, block: () -> T): T =
+ try {
+ writeExecutor.submit(Callable { block() }).get(WRITE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
+ } catch (_: Exception) {
+ fallback
+ }
+
+ companion object {
+ const val FLUSH_INTERVAL_MS: Long = 10_000L
+ private const val WRITE_TIMEOUT_MS: Long = 2_000L
+ private const val MAX_QUEUE_SIZE: Int = 10_000
+ const val LOG_DIR: String = "logs"
+ const val LOG_FILE: String = "colota.log"
+ const val LOG_FILE_PREV: String = "colota.log.1"
+
+ const val MAX_FILE_BYTES: Long = 5L * 1024L * 1024L
+
+ // Live view returns only the most recent slice so it stays responsive as the file grows:
+ // LIVE_TAIL_MAX_BYTES bounds the disk read, LIVE_TAIL_LINES the line count.
+ const val LIVE_TAIL_LINES: Int = 1000
+ private const val LIVE_TAIL_MAX_BYTES: Long = 512L * 1024L
+
+ // If you change this, also update the matching regex in apps/mobile/src/utils/logExport.ts.
+ private const val TIMESTAMP_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS"
+
+ @Volatile
+ private var instance: AppFileLogger? = null
+
+ fun init(context: Context) {
+ if (instance != null) return
+ synchronized(this) {
+ if (instance != null) return
+ val dir = File(context.filesDir, LOG_DIR)
+ instance = AppFileLogger(dir).also { logger ->
+ Runtime.getRuntime().addShutdownHook(Thread { logger.flushNow() })
+ }
+ }
+ }
+
+ fun setEnabled(enabled: Boolean) {
+ instance?.setEnabled(enabled)
+ }
+
+ fun isEnabled(): Boolean = instance?.isEnabled() ?: false
+
+ fun log(level: String, tag: String, msg: String) {
+ instance?.log(level, tag, msg)
+ }
+
+ fun flushNow() {
+ instance?.flushNow()
+ }
+
+ fun getRecentEntries(): List<String> = instance?.getRecentEntries() ?: emptyList()
+
+ fun logFiles(): List<File> = instance?.logFiles() ?: emptyList()
+
+ fun currentSizeBytes(): Long = instance?.currentSizeBytes() ?: 0L
+
+ fun clear() {
+ instance?.clear()
+ }
+ }
+}
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
index 13e209c7..072fbfee 100644
--- 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
@@ -19,25 +19,35 @@ object AppLogger {
fun d(tag: String, msg: String) {
Log.d(PREFIX + tag, msg)
+ AppFileLogger.log("DEBUG", tag, msg)
}
fun i(tag: String, msg: String) {
Log.i(PREFIX + tag, msg)
+ AppFileLogger.log("INFO", tag, msg)
}
fun w(tag: String, msg: String) {
Log.w(PREFIX + tag, msg)
+ AppFileLogger.log("WARN", tag, msg)
}
fun e(tag: String, msg: String, throwable: Throwable? = null) {
val t = PREFIX + tag
if (throwable != null) Log.e(t, msg, throwable) else Log.e(t, msg)
+ val fileMsg = if (throwable != null) "$msg :: ${throwable.javaClass.simpleName}: ${throwable.message}" else msg
+ AppFileLogger.log("ERROR", tag, fileMsg)
}
private val sensitiveHeaderPatterns = listOf(
"authorization", "bearer", "token", "secret", "password", "api-key", "apikey"
)
+ private val sensitiveQueryRegex = Regex(
+ "(?:^|[-_.])(token|secret|password|api[-_]?key|access[-_]?token|auth)(?:\$|[-_.])",
+ RegexOption.IGNORE_CASE
+ )
+
/**
* Masks the value of sensitive HTTP headers before logging.
* Shows the first 4 characters followed by "***", or "***" for values shorter than 5.
@@ -46,11 +56,32 @@ object AppLogger {
val nameLower = headerName.lowercase()
val isSensitive = sensitiveHeaderPatterns.any { pattern -> nameLower.contains(pattern) }
if (!isSensitive) return headerValue
+ return maskValue(headerValue)
+ }
- return if (headerValue.length > 4) {
- "${headerValue.substring(0, 4)}***"
- } else {
- "***"
+ /**
+ * Masks sensitive query parameter values inside a URL before logging.
+ * Returns the input unchanged if the URL has no query string or can't be parsed.
+ */
+ fun maskSensitiveUrlValues(url: String): String {
+ return try {
+ val uri = android.net.Uri.parse(url)
+ val names = uri.queryParameterNames
+ if (names.isEmpty()) return url
+
+ val builder = uri.buildUpon().clearQuery()
+ for (name in names) {
+ val isSensitive = sensitiveQueryRegex.containsMatchIn(name)
+ for (value in uri.getQueryParameters(name)) {
+ builder.appendQueryParameter(name, if (isSensitive) maskValue(value) else value)
+ }
+ }
+ builder.build().toString()
+ } catch (_: Exception) {
+ url
}
}
+
+ private fun maskValue(value: String): String =
+ if (value.length > 4) "${value.substring(0, 4)}***" else "***"
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/ApplicationLogging.kt b/apps/mobile/android/app/src/main/java/com/colota/util/ApplicationLogging.kt
new file mode 100644
index 00000000..f4ff387d
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/ApplicationLogging.kt
@@ -0,0 +1,56 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+package com.Colota.util
+
+import android.app.Application
+import android.content.ComponentCallbacks2
+import android.util.Log
+import com.Colota.data.DatabaseHelper
+
+/** Reads file-logging settings from the DB into [AppFileLogger] and installs the
+ * uncaught-exception flush hook. Called once from MainApplication.onCreate. */
+object FileLoggerInitializer {
+
+ fun start(app: Application) {
+ AppFileLogger.init(app)
+
+ Thread({
+ try {
+ val enabled = DatabaseHelper.getInstance(app)
+ .getSetting("debugFileLoggingEnabled", "false") == "true"
+ AppFileLogger.setEnabled(enabled)
+ } catch (e: Exception) {
+ Log.w("Colota.FileLoggerInit", "Could not load file-logger settings from DB", e)
+ }
+ }, "FileLoggerInit").apply { isDaemon = true }.start()
+
+ val prev = Thread.getDefaultUncaughtExceptionHandler()
+ Thread.setDefaultUncaughtExceptionHandler { thread, ex ->
+ try {
+ AppFileLogger.flushNow()
+ } finally {
+ prev?.uncaughtException(thread, ex)
+ }
+ }
+ }
+}
+
+/** Logs the actual `onTrimMemory` pressure levels (RUNNING_* and COMPLETE). Skips
+ * UI_HIDDEN / BACKGROUND / MODERATE since those fire on every backgrounding. */
+object MemoryPressureLogger {
+
+ private const val TAG = "MainApp"
+
+ fun log(level: Int) {
+ val name = when (level) {
+ ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL -> "RUNNING_CRITICAL"
+ ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW -> "RUNNING_LOW"
+ ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE -> "RUNNING_MODERATE"
+ ComponentCallbacks2.TRIM_MEMORY_COMPLETE -> "COMPLETE"
+ else -> return
+ }
+ AppLogger.w(TAG, "onTrimMemory $name (level=$level)")
+ }
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
index 3bf0b540..a68f11a9 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
@@ -1,6 +1,7 @@
package com.Colota.service
import android.app.NotificationManager
+import android.content.Intent
import android.location.Location
import com.Colota.bridge.LocationServiceModule
import com.Colota.data.DatabaseHelper
@@ -2247,6 +2248,38 @@ class LocationForegroundServiceTest {
}
}
+ private fun invokeLoadConfigFromIntent(intent: Intent?) {
+ val method = LocationForegroundService::class.java.getDeclaredMethod(
+ "loadConfigFromIntent", Intent::class.java
+ )
+ method.isAccessible = true
+ method.invoke(service, intent)
+ }
+
+ @Test
+ fun `loadConfigFromIntent masks endpoint URL when logging config`() {
+ mockkObject(ServiceConfig.Companion)
+ try {
+ every { ServiceConfig.fromDatabase(any()) } returns ServiceConfig(
+ endpoint = "https://example.com/api?token=secret123"
+ )
+ every { AppLogger.maskSensitiveUrlValues(any()) } returns "https://example.com/api?token=secr***"
+
+ val messages = mutableListOf<String>()
+ every { AppLogger.d(any(), capture(messages)) } just Runs
+
+ invokeLoadConfigFromIntent(null)
+
+ val configLine = messages.firstOrNull { it.startsWith("Config loaded:") }
+ assertNotNull("expected a 'Config loaded' log line", configLine)
+ verify { AppLogger.maskSensitiveUrlValues("https://example.com/api?token=secret123") }
+ assertTrue("endpoint must be the masked value", configLine!!.contains("endpoint=https://example.com/api?token=secr***"))
+ assertFalse("raw credential must not be logged", configLine.contains("secret123"))
+ } finally {
+ unmockkObject(ServiceConfig.Companion)
+ }
+ }
+
private val homeGeofence = geofence("Home", 52.50, 13.40, 150.0)
private val officeGeofence = geofence("Office", 48.14, 11.58, 200.0)
private val parkGeofence = geofence("Park", 52.51, 13.35, 100.0)
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/util/AppFileLoggerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/util/AppFileLoggerTest.kt
new file mode 100644
index 00000000..3745e482
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/util/AppFileLoggerTest.kt
@@ -0,0 +1,248 @@
+package com.Colota.util
+
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import java.io.File
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.Executors
+import java.util.concurrent.TimeUnit
+
+class AppFileLoggerTest {
+
+ @get:Rule
+ val tempFolder = TemporaryFolder()
+
+ private lateinit var logDir: File
+ private lateinit var logger: AppFileLogger
+
+ @Before
+ fun setUp() {
+ logDir = tempFolder.newFolder("logs")
+ // Long interval so the scheduled flush never fires; tests flush explicitly via flushNow().
+ logger = AppFileLogger(logDir = logDir, flushIntervalMs = TimeUnit.HOURS.toMillis(1))
+ }
+
+ @After
+ fun tearDown() {
+ logger.shutdown()
+ }
+
+ @Test
+ fun `log writes entry to file when enabled`() {
+ logger.setEnabled(true)
+ logger.log("INFO", "TAG", "hello")
+ logger.flushNow()
+
+ val file = File(logDir, AppFileLogger.LOG_FILE)
+ assertTrue("log file should exist", file.exists())
+ assertTrue(file.readText().contains("INFO/TAG: hello"))
+ }
+
+ @Test
+ fun `log is a no-op when disabled`() {
+ logger.setEnabled(false)
+ logger.log("INFO", "TAG", "should-not-appear")
+ logger.flushNow()
+
+ assertFalse(File(logDir, AppFileLogger.LOG_FILE).exists())
+ }
+
+ @Test
+ fun `getRecentEntries returns lines in write order`() {
+ logger.setEnabled(true)
+ for (i in 0 until 20) {
+ logger.log("INFO", "TAG", "marker-$i")
+ }
+ logger.flushNow()
+
+ val markers = logger.getRecentEntries().mapNotNull {
+ Regex("marker-(\\d+)").find(it)?.groupValues?.get(1)?.toInt()
+ }
+ assertEquals((0 until 20).toList(), markers)
+ }
+
+ @Test
+ fun `clear removes the log file`() {
+ logger.setEnabled(true)
+ repeat(5) { logger.log("INFO", "TAG", "entry-$it") }
+ logger.flushNow()
+
+ logger.clear()
+
+ assertFalse(File(logDir, AppFileLogger.LOG_FILE).exists())
+ assertEquals(0L, logger.currentSizeBytes())
+ }
+
+ @Test
+ fun `writes after clear recreate the file`() {
+ logger.setEnabled(true)
+ logger.log("INFO", "TAG", "first")
+ logger.flushNow()
+
+ logger.clear()
+ logger.log("INFO", "TAG", "second")
+ logger.flushNow()
+
+ val content = File(logDir, AppFileLogger.LOG_FILE).readText()
+ assertFalse(content.contains("first"))
+ assertTrue(content.contains("second"))
+ }
+
+ @Test
+ fun `flushNow returns synchronously with data on disk`() {
+ logger.setEnabled(true)
+ logger.log("INFO", "TAG", "sync-check")
+ logger.flushNow()
+
+ assertTrue(File(logDir, AppFileLogger.LOG_FILE).readText().contains("sync-check"))
+ }
+
+ @Test
+ fun `getRecentEntries caps to the most recent LIVE_TAIL_LINES`() {
+ logger.setEnabled(true)
+ val total = AppFileLogger.LIVE_TAIL_LINES + 500
+ repeat(total) { logger.log("INFO", "TAG", "marker-$it") }
+ logger.flushNow()
+
+ val markers = logger.getRecentEntries().mapNotNull {
+ Regex("marker-(\\d+)").find(it)?.groupValues?.get(1)?.toInt()
+ }
+ assertEquals("live view must cap at LIVE_TAIL_LINES", AppFileLogger.LIVE_TAIL_LINES, markers.size)
+ assertEquals("must keep the most recent entry", total - 1, markers.last())
+ assertEquals("oldest kept is exactly total - cap", total - AppFileLogger.LIVE_TAIL_LINES, markers.first())
+ }
+
+ @Test
+ fun `getRecentEntries flushes the buffer before reading`() {
+ logger.setEnabled(true)
+ logger.log("INFO", "TAG", "buffered-only")
+ // Deliberately no flushNow() call - getRecentEntries() must do its own flush.
+
+ val entries = logger.getRecentEntries()
+ assertTrue("getRecentEntries must return buffered entries: $entries", entries.any { it.contains("buffered-only") })
+ }
+
+ @Test
+ fun `currentSizeBytes flushes the buffer before measuring`() {
+ logger.setEnabled(true)
+ logger.log("INFO", "TAG", "size-check-message-with-some-bytes")
+
+ assertTrue("currentSizeBytes must reflect buffered writes", logger.currentSizeBytes() > 0L)
+ }
+
+ @Test
+ fun `isEnabled reflects setEnabled state`() {
+ assertFalse(logger.isEnabled())
+ logger.setEnabled(true)
+ assertTrue(logger.isEnabled())
+ logger.setEnabled(false)
+ assertFalse(logger.isEnabled())
+ }
+
+ @Test
+ fun `concurrent log calls do not corrupt the file`() {
+ logger.setEnabled(true)
+
+ val threads = 8
+ val perThread = 50
+ val pool = Executors.newFixedThreadPool(threads)
+ val latch = CountDownLatch(threads)
+ repeat(threads) { t ->
+ pool.execute {
+ try {
+ repeat(perThread) { i -> logger.log("INFO", "T$t", "msg-$i") }
+ } finally {
+ latch.countDown()
+ }
+ }
+ }
+ assertTrue(latch.await(10, TimeUnit.SECONDS))
+ pool.shutdown()
+ logger.flushNow()
+
+ val entries = logger.getRecentEntries()
+ assertEquals(threads * perThread, entries.size)
+ val malformed = entries.filterNot { it.matches(Regex(".*msg-\\d+$")) }
+ assertTrue("malformed lines: $malformed", malformed.isEmpty())
+ }
+
+ @Test
+ fun `rotation bounds disk use and preserves the most recent entries`() {
+ // Tiny cap so a few writes force several rotations.
+ val maxBytes = 1024L
+ val rotating = AppFileLogger(
+ logDir = tempFolder.newFolder("rotate"),
+ flushIntervalMs = TimeUnit.HOURS.toMillis(1),
+ maxFileBytes = maxBytes
+ )
+ try {
+ rotating.setEnabled(true)
+ val total = 500
+ repeat(total) { rotating.log("INFO", "TAG", "marker-$it") }
+ rotating.flushNow()
+
+ // Bounded to ~2x the cap; slack covers the line that tips a segment over.
+ val size = rotating.currentSizeBytes()
+ assertTrue("size must be non-zero", size > 0L)
+ assertTrue("size must stay bounded (was $size)", size <= 2 * maxBytes + 256)
+
+ val markers = rotating.getRecentEntries().mapNotNull {
+ Regex("marker-(\\d+)").find(it)?.groupValues?.get(1)?.toInt()
+ }
+ assertFalse("must have retained some entries", markers.isEmpty())
+ assertEquals("most recent entry must survive rotation", total - 1, markers.last())
+ assertFalse("oldest entry must have been rotated out", markers.contains(0))
+ assertEquals(
+ "retained entries must be a contiguous, in-order suffix",
+ (markers.first()..markers.last()).toList(), markers
+ )
+ } finally {
+ rotating.shutdown()
+ }
+ }
+
+ @Test
+ fun `logFiles spans segments oldest first for a gapless export`() {
+ val dir = tempFolder.newFolder("rotate-export")
+ val rotating = AppFileLogger(
+ logDir = dir,
+ flushIntervalMs = TimeUnit.HOURS.toMillis(1),
+ maxFileBytes = 1024L
+ )
+ try {
+ rotating.setEnabled(true)
+ repeat(200) { rotating.log("INFO", "TAG", "marker-$it") }
+ rotating.flushNow()
+
+ assertTrue(
+ "rotation must have produced a previous segment",
+ File(dir, AppFileLogger.LOG_FILE_PREV).exists()
+ )
+
+ val files = rotating.logFiles()
+ assertTrue("export must include at least the rotated segment", files.isNotEmpty())
+ // Active file is briefly absent if the last write rotated, so only check order when both exist.
+ val names = files.map { it.name }
+ val idxPrev = names.indexOf(AppFileLogger.LOG_FILE_PREV)
+ val idxActive = names.indexOf(AppFileLogger.LOG_FILE)
+ if (idxPrev >= 0 && idxActive >= 0) {
+ assertTrue("rotated segment must come before the active file", idxPrev < idxActive)
+ }
+
+ val markers = files.flatMap { it.readLines() }.mapNotNull {
+ Regex("marker-(\\d+)").find(it)?.groupValues?.get(1)?.toInt()
+ }
+ assertEquals(
+ "concatenated export must be contiguous and ordered",
+ (markers.first()..markers.last()).toList(), markers
+ )
+ assertEquals("export must include the most recent entry", 199, markers.last())
+ } finally {
+ rotating.shutdown()
+ }
+ }
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/util/AppLoggerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/util/AppLoggerTest.kt
index ae275e52..e63d851e 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/util/AppLoggerTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/util/AppLoggerTest.kt
@@ -2,7 +2,10 @@ package com.Colota.util
import org.junit.Assert.*
import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+@RunWith(RobolectricTestRunner::class)
class AppLoggerTest {
@Test
@@ -49,4 +52,73 @@ class AppLoggerTest {
fun `maskSensitiveHeaderValue is case insensitive for header names`() {
assertEquals("Bear***", AppLogger.maskSensitiveHeaderValue("AUTHORIZATION", "Bearer token123"))
}
+
+ @Test
+ fun `maskSensitiveUrlValues masks api_key query parameter`() {
+ val masked = AppLogger.maskSensitiveUrlValues("https://example.com/data?api_key=secret123")
+ assertEquals("https://example.com/data?api_key=secr***", masked)
+ }
+
+ @Test
+ fun `maskSensitiveUrlValues masks apikey variant without separator`() {
+ val masked = AppLogger.maskSensitiveUrlValues("https://example.com/data?apikey=abcdef")
+ assertEquals("https://example.com/data?apikey=abcd***", masked)
+ }
+
+ @Test
+ fun `maskSensitiveUrlValues masks access_token`() {
+ val masked = AppLogger.maskSensitiveUrlValues("https://example.com/x?access_token=xyz12345")
+ assertEquals("https://example.com/x?access_token=xyz1***", masked)
+ }
+
+ @Test
+ fun `maskSensitiveUrlValues preserves non-sensitive params`() {
+ val masked = AppLogger.maskSensitiveUrlValues("https://example.com/x?lat=1.23&lon=4.56")
+ assertEquals("https://example.com/x?lat=1.23&lon=4.56", masked)
+ }
+
+ @Test
+ fun `maskSensitiveUrlValues masks only the sensitive param when mixed`() {
+ val masked = AppLogger.maskSensitiveUrlValues("https://example.com/x?lat=1.23&token=secret123&lon=4.56")
+ assertTrue(masked.contains("lat=1.23"))
+ assertTrue(masked.contains("lon=4.56"))
+ assertTrue(masked.contains("token=secr***"))
+ assertFalse(masked.contains("secret123"))
+ }
+
+ @Test
+ fun `maskSensitiveUrlValues returns input unchanged when no query string`() {
+ val url = "https://example.com/data"
+ assertEquals(url, AppLogger.maskSensitiveUrlValues(url))
+ }
+
+ @Test
+ fun `maskSensitiveUrlValues handles short sensitive value`() {
+ val masked = AppLogger.maskSensitiveUrlValues("https://example.com/x?token=ab")
+ assertEquals("https://example.com/x?token=***", masked)
+ }
+
+ @Test
+ fun `maskSensitiveUrlValues is case insensitive for query param names`() {
+ val masked = AppLogger.maskSensitiveUrlValues("https://example.com/x?API_KEY=secret123")
+ assertEquals("https://example.com/x?API_KEY=secr***", masked)
+ }
+
+ @Test
+ fun `maskSensitiveUrlValues returns input unchanged when URL is malformed`() {
+ val malformed = "not a url at all"
+ assertEquals(malformed, AppLogger.maskSensitiveUrlValues(malformed))
+ }
+
+ @Test
+ fun `maskSensitiveUrlValues does not mask author or authority`() {
+ val url = "https://example.com/x?author=jdoe&authority=high"
+ assertEquals(url, AppLogger.maskSensitiveUrlValues(url))
+ }
+
+ @Test
+ fun `maskSensitiveUrlValues masks bare auth param`() {
+ val masked = AppLogger.maskSensitiveUrlValues("https://example.com/x?auth=abcdefgh")
+ assertEquals("https://example.com/x?auth=abcd***", masked)
+ }
}
diff --git a/apps/mobile/src/components/features/log/FileLoggingPanel.tsx b/apps/mobile/src/components/features/log/FileLoggingPanel.tsx
new file mode 100644
index 00000000..089b1ba4
--- /dev/null
+++ b/apps/mobile/src/components/features/log/FileLoggingPanel.tsx
@@ -0,0 +1,214 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useCallback, useEffect, useState } from "react"
+import { View, Text, Switch, StyleSheet, ScrollView, ActivityIndicator } from "react-native"
+import { Card, Divider, SectionTitle } from "../../index"
+import { Button } from "../../ui/Button"
+import { useTheme } from "../../../hooks/useTheme"
+import { fonts, fontSizes } from "../../../styles/typography"
+import NativeLocationService from "../../../services/NativeLocationService"
+import { logger } from "../../../utils/logger"
+import { showAlert, showChoice } from "../../../services/modalService"
+import { formatBytes } from "../../../utils/format"
+
+export function FileLoggingPanel() {
+ const { colors } = useTheme()
+ const [enabled, setEnabled] = useState(false)
+ const [sizeBytes, setSizeBytes] = useState(0)
+ const [busy, setBusy] = useState(false)
+ const [loading, setLoading] = useState(true)
+
+ const refreshSize = useCallback(async () => {
+ try {
+ const size = await NativeLocationService.getFileLogSize()
+ setSizeBytes(size)
+ } catch (err) {
+ logger.error("[FileLoggingPanel] getFileLogSize failed:", err)
+ }
+ }, [])
+
+ useEffect(() => {
+ let cancelled = false
+ ;(async () => {
+ try {
+ const enabledStr = await NativeLocationService.getSetting("debugFileLoggingEnabled", "false")
+ if (cancelled) return
+ setEnabled(enabledStr === "true")
+ await refreshSize()
+ } catch (err) {
+ logger.error("[FileLoggingPanel] initial load failed:", err)
+ } finally {
+ if (!cancelled) setLoading(false)
+ }
+ })()
+ return () => {
+ cancelled = true
+ }
+ }, [refreshSize])
+
+ // Size grows in the background while logging is on - poll while panel is visible.
+ useEffect(() => {
+ if (!enabled) return
+ const id = setInterval(refreshSize, 3000)
+ return () => clearInterval(id)
+ }, [enabled, refreshSize])
+
+ const handleToggle = useCallback(async (value: boolean) => {
+ setEnabled(value)
+ try {
+ await NativeLocationService.setFileLoggingEnabled(value)
+ } catch (err) {
+ logger.error("[FileLoggingPanel] setFileLoggingEnabled failed:", err)
+ setEnabled(!value)
+ }
+ }, [])
+
+ const handleExport = useCallback(async () => {
+ setBusy(true)
+ try {
+ const treeUri = await NativeLocationService.pickExportDirectory()
+ if (!treeUri) return
+ const docUri = await NativeLocationService.exportFileLogToUri(treeUri)
+ if (docUri) {
+ showAlert("Log exported", "Saved to the selected directory.", "success")
+ } else {
+ showAlert("Nothing to export", "There are no log entries yet.", "info")
+ }
+ } catch (err) {
+ logger.error("[FileLoggingPanel] export failed:", err)
+ showAlert("Export failed", err instanceof Error ? err.message : "Could not save log file.", "error")
+ } finally {
+ setBusy(false)
+ }
+ }, [])
+
+ const handleClear = useCallback(async () => {
+ const choice = await showChoice({
+ title: "Clear log files?",
+ message: "All persisted log entries will be deleted. This cannot be undone.",
+ variant: "warning",
+ buttons: [
+ { text: "Cancel", style: "secondary" },
+ { text: "Clear", style: "destructive" }
+ ]
+ })
+ if (choice !== 1) return
+
+ setBusy(true)
+ try {
+ await NativeLocationService.clearFileLog()
+ await refreshSize()
+ } catch (err) {
+ logger.error("[FileLoggingPanel] clearFileLog failed:", err)
+ showAlert("Clear failed", "Could not delete log files.", "error")
+ } finally {
+ setBusy(false)
+ }
+ }, [refreshSize])
+
+ if (loading) {
+ return (
+ <View style={styles.centered}>
+ <ActivityIndicator size="large" color={colors.primary} />
+ </View>
+ )
+ }
+
+ return (
+ <ScrollView contentContainerStyle={styles.scroll}>
+ <SectionTitle>File Logging</SectionTitle>
+
+ <Card style={styles.card}>
+ <Text style={[styles.intro, { color: colors.textSecondary }]}>
+ Save app logs to a file on this device. Useful when a bug takes hours or days to reproduce - the file keeps a
+ record even if the app is restarted in between. Files may contain your location coordinates, so only share
+ with people you trust.
+ </Text>
+
+ <View style={styles.toggleRow}>
+ <View style={styles.toggleLabel}>
+ <Text style={[styles.label, { color: colors.text }]}>Persistent file logging</Text>
+ </View>
+ <Switch
+ value={enabled}
+ onValueChange={handleToggle}
+ trackColor={{ false: colors.border, true: colors.primary + "80" }}
+ thumbColor={enabled ? colors.primary : colors.border}
+ />
+ </View>
+
+ <Divider />
+
+ <View style={styles.section}>
+ <View style={styles.sizeRow}>
+ <Text style={[styles.label, { color: colors.text }]}>Current size</Text>
+ <Text style={[styles.sizeValue, { color: colors.text }]}>{formatBytes(sizeBytes)}</Text>
+ </View>
+ <Text style={[styles.hint, { color: colors.textSecondary }]}>
+ The log file grows as long as logging is on. Use "Clear log files" to reset it.
+ </Text>
+ </View>
+ </Card>
+
+ <Button title="Export log file…" onPress={handleExport} loading={busy} />
+ <Button title="Clear log files" variant="danger" onPress={handleClear} disabled={busy || sizeBytes === 0} />
+ </ScrollView>
+ )
+}
+
+const styles = StyleSheet.create({
+ scroll: {
+ padding: 16,
+ paddingBottom: 40
+ },
+ card: {
+ marginBottom: 12
+ },
+ centered: {
+ flex: 1,
+ justifyContent: "center",
+ alignItems: "center"
+ },
+ intro: {
+ marginBottom: 12,
+ fontSize: 14,
+ lineHeight: 20
+ },
+ toggleRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ paddingVertical: 4
+ },
+ toggleLabel: {
+ flex: 1,
+ paddingRight: 12
+ },
+ section: {
+ paddingVertical: 4
+ },
+ label: {
+ fontSize: fontSizes.label,
+ ...fonts.semiBold,
+ marginBottom: 4
+ },
+ hint: {
+ fontSize: 13,
+ ...fonts.regular,
+ lineHeight: 18,
+ marginBottom: 12
+ },
+ sizeRow: {
+ flexDirection: "row",
+ justifyContent: "space-between",
+ alignItems: "center",
+ marginBottom: 4
+ },
+ sizeValue: {
+ fontSize: 15,
+ ...fonts.medium,
+ fontFamily: "monospace"
+ }
+})
diff --git a/apps/mobile/src/components/ui/Tab.tsx b/apps/mobile/src/components/ui/Tab.tsx
new file mode 100644
index 00000000..403dbc1a
--- /dev/null
+++ b/apps/mobile/src/components/ui/Tab.tsx
@@ -0,0 +1,49 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React from "react"
+import { Pressable, Text, StyleSheet } from "react-native"
+import { fonts } from "../../styles/typography"
+import { ThemeColors } from "../../types/global"
+
+interface TabProps {
+ label: string
+ active: boolean
+ onPress: () => void
+ colors: ThemeColors
+}
+
+export function Tab({ label, active, onPress, colors }: TabProps) {
+ const borderBottomColor = active ? colors.primary : "transparent"
+ const textColor = active ? colors.primary : colors.textSecondary
+ return (
+ <Pressable
+ onPress={onPress}
+ style={({ pressed }) => [styles.tab, { borderBottomColor }, pressed && { opacity: colors.pressedOpacity }]}
+ >
+ <Text style={[styles.tabText, active ? styles.tabTextActive : styles.tabTextInactive, { color: textColor }]}>
+ {label}
+ </Text>
+ </Pressable>
+ )
+}
+
+const styles = StyleSheet.create({
+ tab: {
+ flex: 1,
+ alignItems: "center",
+ padding: 12,
+ borderBottomWidth: 2
+ },
+ tabText: {
+ fontSize: 14
+ },
+ tabTextActive: {
+ ...fonts.bold
+ },
+ tabTextInactive: {
+ ...fonts.regular
+ }
+})
diff --git a/apps/mobile/src/screens/AboutScreen.tsx b/apps/mobile/src/screens/AboutScreen.tsx
index bcb6cbaa..c7f7afeb 100644
--- a/apps/mobile/src/screens/AboutScreen.tsx
+++ b/apps/mobile/src/screens/AboutScreen.tsx
@@ -376,7 +376,7 @@ export function AboutScreen({}: ScreenProps) {
</Pressable>
<Text style={[styles.logHint, { color: colors.textLight }]}>
- View and export logs from Settings &gt; Activity Log.
+ View and export logs from Settings &gt; Logging.
</Text>
</View>
</>
diff --git a/apps/mobile/src/screens/ActivityLogScreen.tsx b/apps/mobile/src/screens/ActivityLogScreen.tsx
index 065e52e3..4aa5c1b1 100644
--- a/apps/mobile/src/screens/ActivityLogScreen.tsx
+++ b/apps/mobile/src/screens/ActivityLogScreen.tsx
@@ -6,25 +6,31 @@
import React, { useState, useCallback, useMemo, useLayoutEffect, useRef } from "react"
import { Text, StyleSheet, View, ScrollView, TextInput, Pressable, ActivityIndicator } from "react-native"
import { useFocusEffect } from "@react-navigation/native"
+import { useSafeAreaInsets } from "react-native-safe-area-context"
import { Share2, Search, X, ArrowDown } from "lucide-react-native"
import { fonts } from "../styles/typography"
import { Container, SectionTitle } from "../components"
+import { Tab } from "../components/ui/Tab"
+import { FileLoggingPanel } from "../components/features/log/FileLoggingPanel"
import { useTheme } from "../hooks/useTheme"
-import { logger } from "../utils/logger"
+import { logger, LOG_LEVELS, type LogLevel } from "../utils/logger"
import { getMergedLogs, exportLogs, MergedLogEntry } from "../utils/logExport"
import NativeLocationService from "../services/NativeLocationService"
import { ScreenProps } from "../types/global"
-const LEVEL_LABELS = ["DEBUG", "INFO", "WARN", "ERROR"] as const
-type FilterLevel = (typeof LEVEL_LABELS)[number]
+type FilterLevel = LogLevel
+
+type LogTab = "live" | "file"
export function ActivityLogScreen({ navigation }: ScreenProps) {
const { colors } = useTheme()
+ const insets = useSafeAreaInsets()
+ const [tab, setTab] = useState<LogTab>("live")
const [logs, setLogs] = useState<MergedLogEntry[]>([])
const [loading, setLoading] = useState(true)
const [exporting, setExporting] = useState(false)
const [searchQuery, setSearchQuery] = useState("")
- const [activeLevels, setActiveLevels] = useState<Set<FilterLevel>>(new Set(LEVEL_LABELS))
+ const [activeLevels, setActiveLevels] = useState<Set<FilterLevel>>(new Set(LOG_LEVELS))
const [showScrollEnd, setShowScrollEnd] = useState(false)
const isNearEnd = useRef(true)
const scrollRef = useRef<ScrollView>(null)
@@ -48,10 +54,11 @@ export function ActivityLogScreen({ navigation }: ScreenProps) {
useFocusEffect(
useCallback(() => {
+ if (tab !== "live") return
loadLogs()
const interval = setInterval(loadLogs, 3000)
return () => clearInterval(interval)
- }, [loadLogs])
+ }, [loadLogs, tab])
)
const handleExport = useCallback(async () => {
@@ -121,7 +128,7 @@ export function ActivityLogScreen({ navigation }: ScreenProps) {
const levelCounts = useMemo(() => {
const counts: Record<string, number> = {}
- for (const level of LEVEL_LABELS) counts[level] = 0
+ for (const level of LOG_LEVELS) counts[level] = 0
for (const entry of logs) {
if (entry.level in counts) counts[entry.level]++
}
@@ -156,9 +163,17 @@ export function ActivityLogScreen({ navigation }: ScreenProps) {
[colors]
)
- if (loading) {
+ const tabBar = (
+ <View style={styles.tabBar}>
+ <Tab label="Live" active={tab === "live"} onPress={() => setTab("live")} colors={colors} />
+ <Tab label="File" active={tab === "file"} onPress={() => setTab("file")} colors={colors} />
+ </View>
+ )
+
+ if (loading && tab === "live") {
return (
<Container>
+ {tabBar}
<View style={styles.centered}>
<ActivityIndicator size="large" color={colors.primary} />
</View>
@@ -166,8 +181,18 @@ export function ActivityLogScreen({ navigation }: ScreenProps) {
)
}
+ if (tab === "file") {
+ return (
+ <Container>
+ {tabBar}
+ <FileLoggingPanel />
+ </Container>
+ )
+ }
+
return (
<Container>
+ {tabBar}
<View style={styles.filterBar}>
<View style={[styles.searchContainer, { backgroundColor: colors.card, borderColor: colors.border }]}>
<Search size={16} color={colors.textLight} />
@@ -188,7 +213,7 @@ export function ActivityLogScreen({ navigation }: ScreenProps) {
</View>
<View style={styles.levelChips}>
- {LEVEL_LABELS.map((level) => {
+ {LOG_LEVELS.map((level) => {
const active = activeLevels.has(level)
const color = levelColor(level)
const count = levelCounts[level] || 0
@@ -199,12 +224,11 @@ export function ActivityLogScreen({ navigation }: ScreenProps) {
style={[
styles.chip,
{
- backgroundColor: active ? color + "20" : colors.background,
- borderColor: active ? color : colors.border
+ backgroundColor: active ? color : colors.surface
}
]}
>
- <Text style={[styles.chipText, { color: active ? color : colors.textLight }]}>
+ <Text style={[styles.chipText, { color: active ? colors.textOnPrimary : colors.textLight }]}>
{level}
{count > 0 ? ` ${count}` : ""}
</Text>
@@ -214,6 +238,8 @@ export function ActivityLogScreen({ navigation }: ScreenProps) {
</View>
</View>
+ <View style={[styles.separator, { backgroundColor: colors.border }]} />
+
<ScrollView
ref={scrollRef}
contentContainerStyle={styles.list}
@@ -257,11 +283,14 @@ export function ActivityLogScreen({ navigation }: ScreenProps) {
</ScrollView>
{showScrollEnd ? (
- <Pressable onPress={scrollToEnd} style={[styles.scrollEndButton, { backgroundColor: colors.primary }]}>
+ <Pressable
+ onPress={scrollToEnd}
+ style={[styles.scrollEndButton, { backgroundColor: colors.primary, bottom: insets.bottom + 24 }]}
+ >
<ArrowDown size={20} color={colors.textOnPrimary} />
</Pressable>
) : filteredLogs.length > 0 ? (
- <View style={[styles.followingBadge, { backgroundColor: colors.primary + "20" }]}>
+ <View style={[styles.followingBadge, { backgroundColor: colors.primary + "20", bottom: insets.bottom + 24 }]}>
<Text style={[styles.followingText, { color: colors.primary }]}>Following</Text>
</View>
) : null}
@@ -270,6 +299,10 @@ export function ActivityLogScreen({ navigation }: ScreenProps) {
}
const styles = StyleSheet.create({
+ tabBar: {
+ flexDirection: "row",
+ marginBottom: 12
+ },
list: {
padding: 16,
paddingBottom: 40
@@ -307,13 +340,17 @@ const styles = StyleSheet.create({
gap: 6
},
chip: {
- paddingHorizontal: 10,
- paddingVertical: 4,
- borderRadius: 12,
- borderWidth: 1
+ paddingHorizontal: 12,
+ paddingVertical: 5,
+ borderRadius: 12
+ },
+ separator: {
+ height: 1,
+ marginHorizontal: 16,
+ marginTop: 4
},
chipText: {
- ...fonts.medium,
+ ...fonts.semiBold,
fontSize: 11
},
logText: {
diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsx
index fd88b9fc..6f24e1f2 100644
--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx
+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx
@@ -9,8 +9,9 @@ import { useFocusEffect } from "@react-navigation/native"
import { fonts } from "../styles/typography"
import { BarChart2 } from "lucide-react-native"
import { Container } from "../components"
+import { Tab } from "../components/ui/Tab"
import { useTheme } from "../hooks/useTheme"
-import { Trip, LocationCoords, ThemeColors } from "../types/global"
+import { Trip, LocationCoords } from "../types/global"
import NativeLocationService from "../services/NativeLocationService"
import { logger } from "../utils/logger"
import { CalendarPicker } from "../components/features/inspector/CalendarPicker"
@@ -24,13 +25,6 @@ import { TRIP_CONVERTERS, EXPORT_FORMATS, type ExportFormat } from "../utils/exp
import { showAlert, showConfirm } from "../services/modalService"
import type { RootScreenProps } from "../types/navigation"
-interface TabProps {
- label: string
- active: boolean
- onPress: () => void
- colors: ThemeColors
-}
-
type TabType = "map" | "trips" | "data"
export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Location History">) {
@@ -309,22 +303,6 @@ export function LocationHistoryScreen({ navigation, route }: RootScreenProps<"Lo
)
}
-const Tab = ({ label, active, onPress, colors }: TabProps) => {
- const borderBottomColor = active ? colors.primary : "transparent"
- const textColor = active ? colors.primary : colors.textSecondary
-
- return (
- <Pressable
- onPress={onPress}
- style={({ pressed }) => [styles.tab, { borderBottomColor }, pressed && { opacity: colors.pressedOpacity }]}
- >
- <Text style={[styles.tabText, active ? styles.tabTextActive : styles.tabTextInactive, { color: textColor }]}>
- {label}
- </Text>
- </Pressable>
- )
-}
-
const styles = StyleSheet.create({
headerBtn: {
padding: 8
@@ -351,20 +329,5 @@ const styles = StyleSheet.create({
tabBar: {
flexDirection: "row",
marginBottom: 12
- },
- tab: {
- flex: 1,
- alignItems: "center",
- padding: 12,
- borderBottomWidth: 2
- },
- tabText: {
- fontSize: 14
- },
- tabTextActive: {
- ...fonts.bold
- },
- tabTextInactive: {
- ...fonts.regular
}
})
diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsx
index 8f6ec870..845e68eb 100644
--- a/apps/mobile/src/screens/SettingsScreen.tsx
+++ b/apps/mobile/src/screens/SettingsScreen.tsx
@@ -217,11 +217,11 @@ export function SettingsScreen({ navigation }: Props) {
/>
<Divider />
<ListItem
- testID="nav-activity-log"
+ testID="nav-logging"
icon={ScrollText}
- label="Activity Log"
- sub="View and export debug logs"
- onPress={() => navigation.navigate("Activity Log")}
+ label="Logging"
+ sub="View activity log and configure file logging"
+ onPress={() => navigation.navigate("Logging")}
/>
</Card>
</View>
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index 7d28c16d..d9d1b051 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -714,14 +714,37 @@ class NativeLocationService {
return LocationServiceModule.getCacheDirectory()
}
- /**
- * Returns native (Kotlin) Logcat entries for the app's process
- */
+ /** Logcat entries for the app's process, or file-log entries when file logging is enabled. */
static async getNativeLogs(): Promise<string[]> {
this.ensureModule()
return LocationServiceModule.getNativeLogs()
}
+ // ============================================================================
+ // FILE LOGGING (debug)
+ // ============================================================================
+
+ static async setFileLoggingEnabled(enabled: boolean): Promise<void> {
+ this.ensureModule()
+ await LocationServiceModule.setFileLoggingEnabled(enabled)
+ }
+
+ static async clearFileLog(): Promise<void> {
+ this.ensureModule()
+ await LocationServiceModule.clearFileLog()
+ }
+
+ static async getFileLogSize(): Promise<number> {
+ this.ensureModule()
+ return LocationServiceModule.getFileLogSize()
+ }
+
+ /** Returns null if there are no entries to export. */
+ static async exportFileLogToUri(treeUri: string): Promise<string | null> {
+ this.ensureModule()
+ return LocationServiceModule.exportFileLogToUri(treeUri)
+ }
+
// ============================================================================
// AUTO-EXPORT
// ============================================================================
diff --git a/apps/mobile/src/types/navigation.ts b/apps/mobile/src/types/navigation.ts
index a09ad236..03d57d21 100644
--- a/apps/mobile/src/types/navigation.ts
+++ b/apps/mobile/src/types/navigation.ts
@@ -31,7 +31,7 @@ export type RootStackParamList = {
"Setup Import": undefined
"Trip Detail": { trip: Trip; trips: Trip[] }
"Offline Maps": undefined
- "Activity Log": undefined
+ Logging: undefined
"Backup & Restore": undefined
}
diff --git a/apps/mobile/src/utils/__tests__/logExport.test.ts b/apps/mobile/src/utils/__tests__/logExport.test.ts
index 04d0690b..81227a92 100644
--- a/apps/mobile/src/utils/__tests__/logExport.test.ts
+++ b/apps/mobile/src/utils/__tests__/logExport.test.ts
@@ -68,6 +68,25 @@ describe("getMergedLogs", () => {
expect(result[3].level).toBe("INFO")
})
+ it("parses AppFileLogger format entries with year-qualified timestamps", async () => {
+ mockGetNativeLogs.mockResolvedValue([
+ "2026-03-31 10:00:02.000 DEBUG/Service: Location received",
+ "2026-03-31 10:00:03.000 ERROR/Sync: Network error",
+ "2026-03-31 10:00:04.000 WARN/Boot: Slow start",
+ "2026-03-31 10:00:05.000 INFO/Profile: Switched"
+ ])
+
+ const result = await getMergedLogs()
+
+ expect(result).toHaveLength(4)
+ expect(result[0].level).toBe("DEBUG")
+ expect(result[1].level).toBe("ERROR")
+ expect(result[2].level).toBe("WARN")
+ expect(result[3].level).toBe("INFO")
+ expect(result[1].time).toBeGreaterThan(result[0].time)
+ expect(result[3].time).toBeGreaterThan(result[2].time)
+ })
+
it("sorts merged entries chronologically", async () => {
// Use timestamps far apart to avoid timezone issues
const year = new Date().getFullYear()
diff --git a/apps/mobile/src/utils/logExport.ts b/apps/mobile/src/utils/logExport.ts
index 3ab00497..a6fbb3e6 100644
--- a/apps/mobile/src/utils/logExport.ts
+++ b/apps/mobile/src/utils/logExport.ts
@@ -4,17 +4,51 @@
*/
import NativeLocationService from "../services/NativeLocationService"
-import { getLogEntries } from "./logger"
+import { getLogEntries, type LogLevel } from "./logger"
export interface MergedLogEntry {
id: string
time: number
- level: "DEBUG" | "INFO" | "WARN" | "ERROR" | "NATIVE"
+ level: LogLevel | "NATIVE"
source: "JS" | "NATIVE"
message: string
raw: string
}
+type ParsedLevel = MergedLogEntry["level"]
+
+/**
+ * Recognises both logcat threadtime (`MM-DD HH:MM:SS.mmm PID TID L TAG: msg`)
+ * and AppFileLogger output (`yyyy-MM-dd HH:mm:ss.SSS LEVEL/TAG: msg`).
+ */
+function parseNativeLogLine(raw: string): { time: number; level: ParsedLevel } {
+ const fileMatch = raw.match(/^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2}\.\d{3})\s+(DEBUG|INFO|WARN|ERROR)\//)
+ if (fileMatch) {
+ return {
+ time: new Date(`${fileMatch[1]}T${fileMatch[2]}`).getTime(),
+ level: fileMatch[3] as ParsedLevel
+ }
+ }
+
+ const logcatMatch = raw.match(/^(\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2}\.\d{3})/)
+ const time = logcatMatch ? new Date(`${new Date().getFullYear()}-${logcatMatch[1]}T${logcatMatch[2]}`).getTime() : 0
+
+ const levelMatch = raw.match(/\d+\s+\d+\s+([VDIWEF])\s/)
+ const nativeLevel = levelMatch ? levelMatch[1] : ""
+ const level: ParsedLevel =
+ nativeLevel === "E"
+ ? "ERROR"
+ : nativeLevel === "W"
+ ? "WARN"
+ : nativeLevel === "I"
+ ? "INFO"
+ : nativeLevel === "D"
+ ? "DEBUG"
+ : "NATIVE"
+
+ return { time, level }
+}
+
/**
* Merges JS and native log entries chronologically.
*/
@@ -36,26 +70,9 @@ export async function getMergedLogs(): Promise<MergedLogEntry[]> {
try {
const nativeLogs = await NativeLocationService.getNativeLogs()
- const year = new Date().getFullYear()
for (let i = 0; i < nativeLogs.length; i++) {
const raw = nativeLogs[i]
- 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
-
- // Extract level from logcat threadtime format: "MM-DD HH:MM:SS.mmm PID TID L TAG: msg"
- const levelMatch = raw.match(/\d+\s+\d+\s+([VDIWEF])\s/)
- const nativeLevel = levelMatch ? levelMatch[1] : ""
- const level =
- nativeLevel === "E"
- ? "ERROR"
- : nativeLevel === "W"
- ? "WARN"
- : nativeLevel === "I"
- ? "INFO"
- : nativeLevel === "D"
- ? "DEBUG"
- : ("NATIVE" as const)
-
+ const { time, level } = parseNativeLogLine(raw)
merged.push({
id: `native-${i}`,
time,
diff --git a/apps/mobile/src/utils/logger.ts b/apps/mobile/src/utils/logger.ts
index c8ea1071..a4e26ce2 100644
--- a/apps/mobile/src/utils/logger.ts
+++ b/apps/mobile/src/utils/logger.ts
@@ -9,7 +9,9 @@
* via the Activity Log screen.
*/
-type LogLevel = "DEBUG" | "INFO" | "WARN" | "ERROR"
+export type LogLevel = "DEBUG" | "INFO" | "WARN" | "ERROR"
+
+export const LOG_LEVELS: readonly LogLevel[] = ["DEBUG", "INFO", "WARN", "ERROR"]
export interface LogEntry {
timestamp: string
diff --git a/fastlane/metadata/android/en-US/changelogs/39.txt b/fastlane/metadata/android/en-US/changelogs/39.txt
index bd9e3c34..3ded1c7a 100644
--- a/fastlane/metadata/android/en-US/changelogs/39.txt
+++ b/fastlane/metadata/android/en-US/changelogs/39.txt
@@ -5,3 +5,4 @@
- Fixed app freezes on slower devices caused by motion detection.
- Trip detail: track on the map now matches the trip's title color.
- Trip detail: switch between trips with prev/next arrows next to the title.
+- Activity Log is now Logging, with a new File tab for persistent bug-report logs.