Modern Apps git

← Modern-Apps.git

log: persist last crashes for every app; error IDs

Commit
6cd44f1d0435216ee244ba5c5255fc3e76d4aa8c
Author
Vayun Mathur <[email protected]>
When
2026-11-21 04:38 UTC (15 days ago)
Parents
dd6b2db
No app captured its own crashes (only logviewer's privileged
read existed). MaInitProvider - the init path shared by all
apps - now installs CrashCapture: an uncaught-exception
handler that writes time/thread/version/stack to
filesDir/crashes (3 rotating files, bounded), then always
chains to the previous handler. Persistence never throws
(runCatching throughout, the NativeLoader lesson).

Log gains newErrorId/errorWithId so user-facing errors can
carry a support correlation ID (display wiring is a later
batch). The debug/dev contract is now documented in Log's
KDoc: dev is dev-only and may carry sensitive detail; debug is
always-on, payload-free shipped diagnostics - gating debug
would have deleted real field diagnostics, so it stays.

Verified: :library:log 13 tests incl. 6 crash-capture tests
(write, chaining on persistence failure, rotation, idempotence).

Diff

library/log/AGENTS.md
diff --git a/library/log/AGENTS.md b/library/log/AGENTS.mdindex 2ddf2af225..02bf67a62b 100644--- a/library/log/AGENTS.md+++ b/library/log/AGENTS.md@@ -17,9 +17,10 @@ **Gotchas:** This card was missing entirely (no AGENTS.md existed) — it was created by the agent-docs redesign. If an app still has an `Application` subclass doing only `Log.init`, delete it (everysync's is the exception — it schedules sync).  ## Key files-- com/vayunmathur/library/log/Log.kt — the facade (use this, never `android.util.Log`)+- com/vayunmathur/library/log/Log.kt — the facade (use this, never `android.util.Log`); `newErrorId()`/`errorWithId()` mint + log a short error-correlation id - com/vayunmathur/library/log/NativeLoader.kt — the one guarded `System.loadLibrary` caller; every `<Feature>Native` wrapper loads through it and exposes the returned availability flag-- com/vayunmathur/library/log/MaInitProvider.kt — dev-gate init via manifest merger+- com/vayunmathur/library/log/CrashCapture.kt — default uncaught-exception handler: persists last 3 crashes to `filesDir/crashes/last_crash.txt` (rotation, never throws), then chains to the previous handler+- com/vayunmathur/library/log/MaInitProvider.kt — dev-gate init + `CrashCapture.install` via manifest merger  ## Verify (this module only) ```
library/log/src/main/java/com/vayunmathur/library/log/CrashCapture.kt
diff --git a/library/log/src/main/java/com/vayunmathur/library/log/CrashCapture.kt b/library/log/src/main/java/com/vayunmathur/library/log/CrashCapture.ktnew file mode 100644index 0000000000..8657fe312e--- /dev/null+++ b/library/log/src/main/java/com/vayunmathur/library/log/CrashCapture.kt@@ -0,0 +1,204 @@+package com.vayunmathur.library.log++import android.content.Context+import java.io.File+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale+import java.util.concurrent.atomic.AtomicBoolean++/**+ * Crash-capture foundation: persists the last few uncaught exceptions to disk+ * so the next launch (or the user, via a future viewer) can see *why* the app+ * died, even with no network and no crash-reporting backend.+ *+ * [install] — called once from [MaInitProvider] for every app — wraps the+ * current default [Thread.UncaughtExceptionHandler]. On a crash the handler:+ *  1. writes the crash (time, thread, app version when known, stack trace) to+ *     `filesDir/crashes/last_crash.txt`, rotating the previous reports so at+ *     most [MAX_CRASH_FILES] files are kept, then+ *  2. chains to the previously installed handler — the crash is never+ *     swallowed; the process still dies the way it would have without us.+ *+ * Persistence must never throw (the [NativeLoader] lesson: a guard that throws+ * becomes the failure it was meant to contain). Every disk/version/logging call+ * on the crash path is wrapped; if writing fails the crash simply chains on.+ */+object CrashCapture {++    /** Directory under `filesDir` that holds crash reports. */+    const val CRASH_DIR_NAME = "crashes"++    /** Newest crash report file inside [CRASH_DIR_NAME]. */+    const val LAST_CRASH_FILE_NAME = "last_crash.txt"++    /** Total crash files kept: newest + this many - 1 rotated generations. */+    const val MAX_CRASH_FILES = 3++    private val installed = AtomicBoolean(false)++    /**+     * Install the crash handler for [context]'s app, resolving the app version+     * best-effort. Idempotent: a second call is a no-op, so the handler never+     * chains to itself. Never throws.+     */+    fun install(context: Context) {+        runCatching {+            val filesDir = context.filesDir ?: return+            install(filesDir, appVersion(context))+        }+    }++    /**+     * Install with an explicit storage root + version label (the [install]+     * seam, also what tests drive). Idempotent and never throws: any failure+     * leaves the previous default handler untouched.+     */+    internal fun install(filesDir: File, appVersion: String?) {+        runCatching {+            if (!installed.compareAndSet(false, true)) return+            val previous = Thread.getDefaultUncaughtExceptionHandler()+            Thread.setDefaultUncaughtExceptionHandler(+                CrashUncaughtExceptionHandler(filesDir, appVersion, previous),+            )+        }.onFailure {+            // Roll back the claim so a later retry can still install.+            installed.set(false)+        }+    }++    /** Location of the crash-reports directory under an app's [filesDir]. */+    fun crashesDir(filesDir: File): File = File(filesDir, CRASH_DIR_NAME)++    /** Location of the newest crash report under an app's [filesDir]. */+    fun lastCrashFile(filesDir: File): File = File(crashesDir(filesDir), LAST_CRASH_FILE_NAME)++    /**+     * Rotated file name for [generation]: 0 → `last_crash.txt` (newest),+     * 1 → `last_crash.1.txt`, 2 → `last_crash.2.txt` (oldest kept).+     */+    internal fun rotatedFileName(generation: Int): String =+        if (generation == 0) LAST_CRASH_FILE_NAME else "last_crash.$generation.txt"++    /**+     * Render + persist one crash under [filesDir], rotating older reports.+     * Returns the written file, or null when persistence failed. Never throws.+     */+    internal fun writeCrash(+        filesDir: File,+        thread: Thread,+        throwable: Throwable,+        appVersion: String?,+        nowMillis: Long = System.currentTimeMillis(),+    ): File? = runCatching {+        val dir = crashesDir(filesDir)+        if (!dir.exists()) dir.mkdirs()+        rotate(dir)+        val target = File(dir, LAST_CRASH_FILE_NAME)+        target.writeText(renderCrash(thread, throwable, appVersion, nowMillis))+        prune(dir)+        target+    }.getOrNull()++    @Suppress("DEPRECATION") // Thread.id: threadId() is not available on all API levels+    internal fun renderCrash(+        thread: Thread,+        throwable: Throwable,+        appVersion: String?,+        nowMillis: Long,+    ): String {+        val timestamp = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US)+            .format(Date(nowMillis))+        return buildString {+            append("time: ").append(timestamp)+                .append(" (epochMillis=").append(nowMillis).append(")\n")+            append("thread: ").append(thread.name)+                .append(" (id=").append(thread.id).append(")\n")+            append("appVersion: ").append(appVersion ?: "unknown").append('\n')+            append("exception: ").append(throwable.javaClass.name)+            throwable.message?.let { append(": ").append(it) }+            append('\n')+            append("stack:\n")+            append(throwable.stackTraceToString())+        }+    }++    // Shift generations up by one (oldest falls off the end), freeing+    // last_crash.txt for the new report. Bounded at MAX_CRASH_FILES.+    private fun rotate(dir: File) {+        for (generation in MAX_CRASH_FILES - 1 downTo 0) {+            val source = File(dir, rotatedFileName(generation))+            if (!source.exists()) continue+            if (generation == MAX_CRASH_FILES - 1) {+                runCatching { source.delete() }+            } else {+                runCatching { source.renameTo(File(dir, rotatedFileName(generation + 1))) }+            }+        }+    }++    // Defensive bound: drop anything beyond the kept generations (e.g. files+    // left by an older scheme) so the directory can never grow unbounded.+    private fun prune(dir: File) {+        runCatching {+            val kept = (0 until MAX_CRASH_FILES).map { rotatedFileName(it) }.toSet()+            dir.listFiles()?.forEach { file ->+                if (file.isFile && file.name !in kept) runCatching { file.delete() }+            }+        }+    }++    // "versionName (versionCode)" when the package manager can tell us, else+    // null (rendered as "unknown"). Never throws.+    @Suppress("DEPRECATION")+    private fun appVersion(context: Context): String? = runCatching {+        val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)+        val code = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {+            packageInfo.longVersionCode+        } else {+            packageInfo.versionCode.toLong()+        }+        "${packageInfo.versionName ?: "unknown"} ($code)"+    }.getOrNull()++    /** Test seam: uninstall the handler installed by [install], if any. */+    internal fun resetForTest() {+        val current = Thread.getDefaultUncaughtExceptionHandler()+        if (current is CrashUncaughtExceptionHandler) {+            Thread.setDefaultUncaughtExceptionHandler(current.previous)+        }+        installed.set(false)+    }+}++/**+ * The installed handler: persist, then chain. Persistence failure never+ * escapes and never blocks chaining; chaining failure is left alone (there is+ * nothing more useful we could do with it on a crashing thread).+ */+internal class CrashUncaughtExceptionHandler(+    private val filesDir: File,+    private val appVersion: String?,+    internal val previous: Thread.UncaughtExceptionHandler?,+) : Thread.UncaughtExceptionHandler {++    override fun uncaughtException(thread: Thread, throwable: Throwable) {+        runCatching {+            CrashCapture.writeCrash(filesDir, thread, throwable, appVersion)+        }+        runCatching { Log.error(TAG, "uncaught exception on ${thread.name}", throwable) }++        val chained = previous+        if (chained != null) {+            chained.uncaughtException(thread, throwable)+        } else {+            // No previous handler to kill the process: preserve the default+            // "thread dies with its exception" contract instead of swallowing.+            throw throwable+        }+    }++    private companion object {+        const val TAG = "CrashCapture"+    }+}
library/log/src/main/java/com/vayunmathur/library/log/Log.kt
diff --git a/library/log/src/main/java/com/vayunmathur/library/log/Log.kt b/library/log/src/main/java/com/vayunmathur/library/log/Log.ktindex 37bee41255..a4e7cbd68b 100644--- a/library/log/src/main/java/com/vayunmathur/library/log/Log.kt+++ b/library/log/src/main/java/com/vayunmathur/library/log/Log.kt@@ -1,6 +1,7 @@ package com.vayunmathur.library.log  import android.util.Log as AndroidLog+import java.security.SecureRandom  /**  * Repo-wide logging facade. Replaces direct `android.util.Log` use everywhere; a@@ -9,8 +10,8 @@ import android.util.Log as AndroidLog  * Four levels, each an explicit `tag` plus `content` (existing call-site `TAG`  * constants are kept as-is, so custom tags like `MaAuto.Server` survive):  *  - [dev]    → DEBUG, only when [init] was called with `isDev = true`- *               (the `BuildConfig.DEV_BUILD` flag that also gates findfamily trackers)- *  - [debug]  → DEBUG, always+ *               (the app's `debuggable` flag, wired by `MaInitProvider`)+ *  - [debug]  → DEBUG, always — shippable diagnostics only (see below)  *  - [status] → INFO, always (absorbs old `Log.i` and `Log.w` — see below)  *  - [error]  → ERROR, always  *@@ -22,11 +23,38 @@ import android.util.Log as AndroidLog  * name: R8 inlines and renames frames, so any `Thread.stackTrace` / reflection  * scheme degrades in release builds, and an explicit tag costs nothing.  *- * Each app wires the dev gate once in its `Application.onCreate`:- * `Log.init(BuildConfig.DEV_BUILD)`. Until then [dev] is silent.+ * ## [dev] vs [debug] — which one do I use?+ *+ * The split is about what is safe to ship, not about severity (both emit at+ * DEBUG priority):+ *  - [dev] is **dev-only**: silent in release builds. Use it for verbose or+ *    potentially sensitive detail — request/response payloads, decoded+ *    locations, protocol internals — anything you would not want in a shipped+ *    logcat (e.g. Uber GraphQL variables in taxi, PQC details in findfamily).+ *  - [debug] is **shippable diagnostics**: always emitted, so it must stay+ *    low-volume and payload-free — status codes, sizes, lifecycle/state+ *    transitions and ids, never bodies or secrets. Shipped code relies on it+ *    (e.g. every Lyft/Uber HTTP status line and ride-terminal transition in+ *    taxi, "no fix yet" heartbeat diagnostics in findfamily), which is why+ *    [debug] is deliberately *not* gated on [init]: gating it would silence+ *    those diagnostics in release.+ *+ * Each app gets the dev gate for free: `MaInitProvider` (merged from this+ * module's manifest) calls [init] from the manifest `debuggable` flag before+ * `Application.onCreate`. Until then [dev] is silent.+ *+ * ## Error correlation+ *+ * [newErrorId] mints a short per-error id (8 lowercase hex chars) and+ * [errorWithId] logs an error together with one, returning the id so the+ * caller can surface the same id in UI/error state and a user report can be+ * matched to the log line. Ids are correlation aids, not unique identifiers:+ * 32 bits collide occasionally, which is fine for matching one report.  */ object Log { +    private val errorIdRandom = SecureRandom()+     @Volatile     private var devEnabled: Boolean = false @@ -54,13 +82,20 @@ object Log {         if (devEnabled) AndroidLog.d(tag, content, tr)     } -    /** DEBUG-level log, always emitted. */+    /**+     * DEBUG-level log, always emitted — shippable diagnostics only: status+     * codes, sizes, lifecycle/state transitions and ids. No payloads, bodies+     * or secrets here; verbose or sensitive detail belongs in [dev].+     */     @JvmStatic     fun debug(tag: String, content: String) {         AndroidLog.d(tag, content)     } -    /** DEBUG-level log with an attached throwable, always emitted. */+    /**+     * DEBUG-level log with an attached throwable, always emitted. Same+     * payload-free contract as [debug] (tag, content) above.+     */     @JvmStatic     fun debug(tag: String, content: String, tr: Throwable?) {         AndroidLog.d(tag, content, tr)@@ -89,4 +124,46 @@ object Log {     fun error(tag: String, content: String, tr: Throwable?) {         AndroidLog.e(tag, content, tr)     }++    /**+     * A fresh short error-correlation id: 8 lowercase hex chars (32 random+     * bits), e.g. `3f9a1c07`. Cheap and dependency-free; see the error+     * correlation note on [Log].+     */+    @JvmStatic+    fun newErrorId(): String {+        val bytes = ByteArray(ERROR_ID_BYTES)+        errorIdRandom.nextBytes(bytes)+        val sb = StringBuilder(ERROR_ID_HEX_LENGTH)+        for (b in bytes) {+            val v = b.toInt() and 0xFF+            sb.append(HEX[v ushr 4]).append(HEX[v and 0x0F])+        }+        return sb.toString()+    }++    /**+     * ERROR-level log stamped with a fresh [newErrorId]; returns that id so+     * the caller can show the same id in error UI/state and a user report can+     * be grepped back to this line. The logged message is+     * `"errorId=<id> <content>"`.+     */+    @JvmStatic+    fun errorWithId(tag: String, content: String): String {+        val id = newErrorId()+        AndroidLog.e(tag, "errorId=$id $content")+        return id+    }++    /** [errorWithId] with an attached throwable. */+    @JvmStatic+    fun errorWithId(tag: String, content: String, tr: Throwable?): String {+        val id = newErrorId()+        AndroidLog.e(tag, "errorId=$id $content", tr)+        return id+    }++    private const val ERROR_ID_BYTES = 4+    private const val ERROR_ID_HEX_LENGTH = 8+    private const val HEX = "0123456789abcdef" }
library/log/src/main/java/com/vayunmathur/library/log/MaInitProvider.kt
diff --git a/library/log/src/main/java/com/vayunmathur/library/log/MaInitProvider.kt b/library/log/src/main/java/com/vayunmathur/library/log/MaInitProvider.ktindex 1a683f565a..60bb1ad73b 100644--- a/library/log/src/main/java/com/vayunmathur/library/log/MaInitProvider.kt+++ b/library/log/src/main/java/com/vayunmathur/library/log/MaInitProvider.kt@@ -18,15 +18,23 @@ import android.net.Uri  * which matches the old `BuildConfig.DEV_BUILD` semantics (`dev` variants  * are debuggable, `release` variants are not).  *+ * This provider is also where every app gets [CrashCapture]: [onCreate]+ * installs its default uncaught-exception handler (persist-then-chain, see+ * [CrashCapture]) alongside the dev gate. Both wirings are guarded so a+ * failure here can never break app startup.+ *  * Carries no data: every method besides [onCreate] is a stub.  */ class MaInitProvider : ContentProvider() {     override fun onCreate(): Boolean {         val appContext = context?.applicationContext         if (appContext != null) {-            val isDev =-                appContext.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0-            Log.init(isDev)+            runCatching {+                val isDev =+                    appContext.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0+                Log.init(isDev)+            }+            runCatching { CrashCapture.install(appContext) }         }         return true     }
library/log/src/test/java/com/vayunmathur/library/log/CrashCaptureTest.kt
diff --git a/library/log/src/test/java/com/vayunmathur/library/log/CrashCaptureTest.kt b/library/log/src/test/java/com/vayunmathur/library/log/CrashCaptureTest.ktnew file mode 100644index 0000000000..35af55426f--- /dev/null+++ b/library/log/src/test/java/com/vayunmathur/library/log/CrashCaptureTest.kt@@ -0,0 +1,177 @@+package com.vayunmathur.library.log++import java.io.File+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+import org.robolectric.annotation.Config++/**+ * Crash-capture: a synthetic exception must land in+ * `filesDir/crashes/last_crash.txt` (stack, thread, time, version), rotation+ * must keep at most [CrashCapture.MAX_CRASH_FILES] files, and the previous+ * default handler must always be chained to — even when persistence fails.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CrashCaptureTest {++    @BeforeTest+    fun setUp() {+        // MaInitProvider installs the handler too; start each test from a+        // known uninstalled state regardless of test ordering.+        CrashCapture.resetForTest()+    }++    @AfterTest+    fun tearDown() {+        CrashCapture.resetForTest()+    }++    private fun filesDir(): File = RuntimeEnvironment.getApplication().filesDir++    @Test+    fun handlerWritesCrashFileWithStackThreadTimeAndVersion() {+        val chained = RecordingHandler()+        val handler = CrashUncaughtExceptionHandler(filesDir(), "9.9.9 (42)", chained)+        val boom = IllegalStateException("synthetic boom")++        handler.uncaughtException(Thread.currentThread(), boom)++        val crashFile = CrashCapture.lastCrashFile(filesDir())+        assertTrue(crashFile.isFile, "expected crash file at $crashFile")+        val text = crashFile.readText()+        assertTrue(text.contains("appVersion: 9.9.9 (42)"), text)+        assertTrue(text.contains("thread: ${Thread.currentThread().name}"), text)+        assertTrue(text.contains("time: "), text)+        assertTrue(text.contains("exception: java.lang.IllegalStateException: synthetic boom"), text)+        assertTrue(text.contains("synthetic boom"), text)+        assertTrue(text.contains("CrashCaptureTest"), text) // stack frames present+        assertEquals(1, chained.invocations)+        assertTrue(chained.lastThread === Thread.currentThread())+        assertTrue(chained.lastThrowable === boom)+    }++    @Test+    fun writeCrashReturnsNullInsteadOfThrowingWhenStorageIsUnusable() {+        // filesDir as a regular file: the crashes/ dir can never be created.+        val blocker = File(filesDir(), "not-a-dir-${System.nanoTime()}")+        blocker.writeText("occupied")+        try {+            assertNull(+                CrashCapture.writeCrash(blocker, Thread.currentThread(), RuntimeException("x"), null),+            )+        } finally {+            blocker.delete()+        }+    }++    @Test+    fun handlerStillChainsWhenPersistenceFails() {+        val blocker = File(filesDir(), "not-a-dir-chain-${System.nanoTime()}")+        blocker.writeText("occupied")+        val chained = RecordingHandler()+        val handler = CrashUncaughtExceptionHandler(blocker, null, chained)+        try {+            // Must not throw, and must still delegate.+            handler.uncaughtException(Thread.currentThread(), RuntimeException("chain me"))+            assertEquals(1, chained.invocations)+            assertEquals("chain me", chained.lastThrowable?.message)+        } finally {+            blocker.delete()+        }+    }++    @Test+    fun rotationKeepsAtMostMaxCrashFilesWithNewestFirst() {+        val dir = File(filesDir(), "rotation-${System.nanoTime()}").apply { mkdirs() }+        try {+            repeat(CrashCapture.MAX_CRASH_FILES + 2) { index ->+                assertNotNull(+                    CrashCapture.writeCrash(+                        dir,+                        Thread.currentThread(),+                        IllegalStateException("crash-$index"),+                        "1.0 ($index)",+                        nowMillis = 1_700_000_000_000L + index,+                    ),+                )+            }+            val crashesDir = CrashCapture.crashesDir(dir)+            val names = crashesDir.listFiles().orEmpty().map { it.name }.sorted()+            assertEquals(+                listOf("last_crash.1.txt", "last_crash.2.txt", "last_crash.txt"),+                names,+            )+            assertEquals(CrashCapture.MAX_CRASH_FILES, names.size)+            // Newest report is last_crash.txt; the oldest kept is N-1 crashes back.+            assertTrue(CrashCapture.lastCrashFile(dir).readText().contains("crash-4"))+            assertTrue(+                File(crashesDir, CrashCapture.rotatedFileName(2)).readText().contains("crash-2"),+            )+        } finally {+            dir.deleteRecursively()+        }+    }++    @Test+    fun installIsIdempotentAndChainsToOriginalHandlerExactlyOnce() {+        val original = RecordingHandler()+        val prior = Thread.getDefaultUncaughtExceptionHandler()+        Thread.setDefaultUncaughtExceptionHandler(original)+        try {+            CrashCapture.install(filesDir(), "1.0 (1)")+            val installedHandler = Thread.getDefaultUncaughtExceptionHandler()+            assertTrue(installedHandler is CrashUncaughtExceptionHandler)++            // Second install must not wrap the handler in itself.+            CrashCapture.install(filesDir(), "1.0 (1)")+            assertTrue(Thread.getDefaultUncaughtExceptionHandler() === installedHandler)++            val boom = IllegalStateException("installed boom")+            installedHandler.uncaughtException(Thread.currentThread(), boom)+            assertEquals(1, original.invocations)+            assertTrue(original.lastThrowable === boom)+            assertTrue(CrashCapture.lastCrashFile(filesDir()).readText().contains("installed boom"))+        } finally {+            CrashCapture.resetForTest()+            Thread.setDefaultUncaughtExceptionHandler(prior)+        }+    }++    @Test+    fun installNeverThrows() {+        val prior = Thread.getDefaultUncaughtExceptionHandler()+        try {+            // Install only registers the handler (the write happens at crash+            // time); reaching the assert without throwing is the contract.+            CrashCapture.install(filesDir(), null)+            assertTrue(+                Thread.getDefaultUncaughtExceptionHandler() is CrashUncaughtExceptionHandler,+            )+        } finally {+            CrashCapture.resetForTest()+            Thread.setDefaultUncaughtExceptionHandler(prior)+            assertTrue(Thread.getDefaultUncaughtExceptionHandler() === prior)+        }+    }++    private class RecordingHandler : Thread.UncaughtExceptionHandler {+        var invocations = 0+        var lastThread: Thread? = null+        var lastThrowable: Throwable? = null++        override fun uncaughtException(thread: Thread, throwable: Throwable) {+            invocations+++            lastThread = thread+            lastThrowable = throwable+        }+    }+}
library/log/src/test/java/com/vayunmathur/library/log/LogFacadeTest.kt
diff --git a/library/log/src/test/java/com/vayunmathur/library/log/LogFacadeTest.kt b/library/log/src/test/java/com/vayunmathur/library/log/LogFacadeTest.ktindex bba413f18e..c291523179 100644--- a/library/log/src/test/java/com/vayunmathur/library/log/LogFacadeTest.kt+++ b/library/log/src/test/java/com/vayunmathur/library/log/LogFacadeTest.kt@@ -53,6 +53,32 @@ class LogFacadeTest {         assertEquals("err2", ShadowLog.getLogsForTag("E")[1].msg)     } +    @Test+    fun newErrorIdIsEightLowercaseHexAndVaries() {+        val ids = (1..64).map { Log.newErrorId() }+        assertTrue(ids.all { it.matches(Regex("[0-9a-f]{8}")) }, "ids: $ids")+        // 32-bit ids: 64 draws must not all collide to one value.+        assertTrue(ids.toSet().size > 1, "ids: $ids")+    }++    @Test+    fun errorWithIdLogsAtErrorWithTheReturnedId() {+        ShadowLog.clear()+        val id = Log.errorWithId("E", "something broke")+        val logs = ShadowLog.getLogsForTag("E")+        assertEquals(1, logs.size)+        assertEquals(android.util.Log.ERROR, logs[0].type)+        assertEquals("errorId=$id something broke", logs[0].msg)++        ShadowLog.clear()+        val id2 = Log.errorWithId("E", "with cause", RuntimeException("cause"))+        val logs2 = ShadowLog.getLogsForTag("E")+        assertEquals(1, logs2.size)+        assertEquals(android.util.Log.ERROR, logs2[0].type)+        assertEquals("errorId=$id2 with cause", logs2[0].msg)+        assertTrue(id2.matches(Regex("[0-9a-f]{8}")))+    }+     @Test     fun providerInitializesAndStubsReturnNeutral() {         val provider = Robolectric.buildContentProvider(MaInitProvider::class.java).create().get()