Observability cheat sheet
Key ideas
- Structured logs (fixed event name plus keys) are filterable and countable in a log backend; free-text strings are not.
- Plant
Timber.DebugTree()only in debug builds; in release, plant a customTimber.Treethat drops low levels and forwards to a remote sink. - Never log PII (emails, names, tokens); scrub at the source with a
Scrubber, not in the backend. - Alert on rates per app version, not raw crash counts; use logs and traces to explain an alert.
- Firebase Performance custom traces allow 32 metrics and 5 custom attributes; keep both low-cardinality and free of PII.
ApplicationExitInfo(API 30+) reveals low-memory kills that produce no crash report; read it on the next launch off the main thread.- Android vitals bad-behavior thresholds: 1.09% user-perceived crash rate and 0.47% ANR rate per DAU, plus 8% on any single phone model.
- Halting a staged rollout stops new installs only; users who already updated stay until a higher
versionCodeships. - Sample high-frequency events (scrolling, frame callbacks) on-device to save battery and data; never sample errors you alert on without accounting for it.
- Respect consent: disable Crashlytics and Performance collection at runtime until the user agrees where your privacy policy requires it.
APIs at a glance
| API or term | Use it for |
|---|---|
Timber.DebugTree() | Plant only in debug builds; sends all levels to Logcat. |
Timber.Tree (custom) | Release tree that filters by priority and forwards to Crashlytics or a remote sink. |
Firebase.performance.newTrace("name").trace { } | Wrap a user-visible flow (screen load, checkout) in a custom performance trace. |
@AddTrace(name = "...") | Build-time trace on a non-suspend method via the Performance Gradle plugin. |
putAttribute / putMetric | Attach low-cardinality keys (max 5 attributes, 32 metrics per trace) to a custom trace. |
Firebase.crashlytics.setCustomKey / log / recordException | Add context to the next crash or send a caught exception as a non-fatal. |
ApplicationExitInfo | Read process exit reason (crash, ANR, low-memory) on the next launch; API 30+. |
ActivityManager.getHistoricalProcessExitReasons() | Fetch recent exit records off the main thread; store the newest timestamp to avoid duplicates. |
HttpLoggingInterceptor with Level.NONE / redactHeader | Disable OkHttp body logging in release; redact sensitive headers where logging stays on. |
reportFullyDrawn() | Report TTFD once real content is visible; call it only once per screen. |
setCrashlyticsCollectionEnabled / isPerformanceCollectionEnabled | Gate data collection on user consent at runtime. |
AndroidPublisher (Play Developer Publishing API) | Halt an in-progress rollout programmatically from a CI job or scheduled alert. |
Snippets
Release Timber tree forwarding to Crashlytics
object Scrubber {
private val email = Regex("""[\w.+-]+@[\w-]+\.[\w.]+""")
private val bearer = Regex("""(?i)bearer\s+[\w.-]+""")
fun scrub(text: String): String =
text.replace(email, "[email]").replace(bearer, "Bearer [token]")
}
class ReleaseTree : Timber.Tree() {
private val crashlytics = Firebase.crashlytics
override fun isLoggable(tag: String?, priority: Int): Boolean = priority >= Log.INFO
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
crashlytics.log("$priority/${tag ?: "app"}: ${Scrubber.scrub(message)}")
if (t != null && priority >= Log.ERROR) crashlytics.recordException(t)
}
}Custom performance trace with low-cardinality attributes
data class FeedItem(val id: String, val title: String)
interface FeedApi { suspend fun getFeed(): List<FeedItem> }
interface FeedDao { suspend fun replaceAll(items: List<FeedItem>) }
class FeedRepository(private val api: FeedApi, private val dao: FeedDao) {
suspend fun refreshFeed(): Int =
Firebase.performance.newTrace("feed_refresh").trace {
val items = api.getFeed()
dao.replaceAll(items)
putMetric("item_count", items.size.toLong())
putAttribute("feed_type", "home")
items.size
}
}Release-health gate: compare candidate vs baseline rates
data class ReleaseStats(val sessions: Long, val crashRate: Double, val anrRate: Double)
data class GateConfig(
val minSessions: Long,
val crashCeiling: Double,
val anrCeiling: Double,
val maxIncrease: Double, // e.g. 1.2 = allow 20% worse than baseline
)
sealed interface Verdict {
data object WaitForData : Verdict
data object Continue : Verdict
data class Halt(val reason: String) : Verdict
}
fun evaluate(candidate: ReleaseStats, baseline: ReleaseStats, cfg: GateConfig): Verdict {
if (candidate.sessions < cfg.minSessions) return Verdict.WaitForData
if (candidate.crashRate > cfg.crashCeiling) return Verdict.Halt("crash rate above SLO ceiling")
if (candidate.anrRate > cfg.anrCeiling) return Verdict.Halt("ANR rate above SLO ceiling")
if (candidate.crashRate > baseline.crashRate * cfg.maxIncrease) return Verdict.Halt("crash rate regressed")
if (candidate.anrRate > baseline.anrRate * cfg.maxIncrease) return Verdict.Halt("ANR rate regressed")
return Verdict.Continue
}Report ApplicationExitInfo on next launch
fun reportExitReasons(context: Context, lastReported: Long, send: (String, Long) -> Unit): Long {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return lastReported
val am = context.getSystemService(ActivityManager::class.java)
val exits = am.getHistoricalProcessExitReasons(context.packageName, 0, 10)
.filter { it.timestamp > lastReported }
exits.forEach { info ->
send(when (info.reason) {
ApplicationExitInfo.REASON_LOW_MEMORY -> "low_memory"
else -> "other_${info.reason}"
}, info.timestamp)
}
return exits.maxOfOrNull { it.timestamp } ?: lastReported
}Rules of thumb
- Prefer structured logs with a fixed event name and typed keys over free-text strings.
- Never log PII; scrub emails, tokens, and names at the source before they enter any pipeline.
- Prefer alerting on rates per app version over raw crash counts, which grow with rollout percentage.
- Never plant
Timber.DebugTree()in a release build; use a customTimber.Treethat filters and forwards. - Prefer sampling high-frequency events on-device and aggregating into metrics; never sample errors you alert on without accounting for it.
- Never alert on a single static threshold; use a burn-rate alert on the error budget so you warn while there is still time to act.
Gotchas
- Free-text log messages like "User loaded 12 items in 340ms". They cannot be grouped or counted in a log backend. Use a fixed event name plus keys (
items=12 duration_ms=340). - Planting Timber.DebugTree() in release. It sends everything to Logcat where other tools on a debuggable or rooted device can read it, and it adds overhead. Plant it in debug builds only.
- Alerting on raw crash counts. Counts grow with the rollout percentage and traffic, producing false alarms. Alert on the crash rate for the new version compared with the previous version.
- High-cardinality trace attributes (user ID, full URL). They make dashboards useless and may leak personal data into a third-party backend. Use small, fixed value sets like
feed_type=home. - Reading only averages for performance. A healthy-looking average can hide a slow tail of users who wait several seconds. Read P50 and P95 (or P90) per release and per device tier.
- Expecting a halted rollout to roll users back. Halting stops new installs only; users who already updated stay on that version. Plan a fast fix with a higher
versionCodeand use remote feature flags to switch off a broken feature.
Quick interview answers
What is the difference between TTID and TTFD?
TTID (Time to Initial Display) is the first frame drawn, reported by the system. TTFD (Time to Full Display) is when real content is visible, reported by the app calling reportFullyDrawn(); report it only once content is actually on screen.
Why should you alert on rates instead of raw crash counts?
Raw counts grow with the rollout percentage and traffic, so a 10 % rollout with the same rate looks like a spike. Alerting on the crash rate for the new version compared with the previous version isolates a true regression.
What does ApplicationExitInfo tell you that Crashlytics does not?
It reports why the process ended on the next launch, including REASON_LOW_MEMORY kills that produce no crash report. Read it via ActivityManager.getHistoricalProcessExitReasons() off the main thread, and store the newest timestamp to avoid uploading the same exit twice.
How do you structure a log event for a log backend?
Use a fixed event name plus typed key-value pairs, for example checkout_failed http_status=503 screen=cart. Free-text strings cannot be filtered or counted, so avoid them in production logs.
What happens when you halt a staged rollout on Google Play?
Halting stops new installs of that version only; users who already updated stay on it until you ship a higher versionCode. The Play Developer Publishing API can perform the halt programmatically, so a scheduled job can act on an alert without waiting for a person.
What are the Android vitals bad-behavior thresholds?
The user-perceived crash rate threshold is 1.09 % and the ANR rate is 0.47 %, both measured per daily active user, with an additional 8 % cap on any single phone model. Crossing a threshold can reduce your app's visibility on Play and add a warning on the store listing, but it does not remove the app.