Logging, metrics and tracing on mobile
Why it matters
- A log line alone cannot tell you how many users hit a problem or where the time went. Senior interviews expect you to separate logs, metrics and traces and say which question each one answers.
- Unstructured
Log.d("got $user")strings cannot be filtered or counted in a backend. Structured events with fixed keys can be queried, grouped by app version and turned into alerts. - Observability lets you move from "the app is slow" to "the profile screen load is slow on the latest release, and the time is in JSON parsing, not the network".
- Mobile telemetry costs battery, data and user trust. You must sample it, keep it off the main thread and keep personal data (PII) out of it.
The simple explanation
- Think of an aircraft flight recorder.
- Logs are the written transcript of what the crew did.
- Metrics are the gauges: altitude, fuel, engine temperature over time.
- Traces are the timeline of one manoeuvre, showing which step took how long.
What are logs, metrics and traces on Android? They are the three kinds of telemetry you collect from real devices. Logs are individual events with context ("checkout failed, http_status=503"). Metrics are numbers aggregated over many events ("checkout error rate per app version"). Traces measure the duration of one operation, often split into spans ("profile load: 900 ms, of which network 300 ms and parsing 600 ms").
Logs. Use structured logging: an event name plus key-value attributes instead of free text, so a backend can index the fields. Give each log a level (DEBUG, INFO, WARN, ERROR). On Android the usual setup is Timber: plant Timber.DebugTree() only in debug builds (it writes to Logcat), and in release plant your own Timber.Tree that forwards INFO and above to a remote sink such as Firebase Crashlytics logs. Crashlytics attaches recent log() lines and custom keys (setCustomKey) to the next crash or non-fatal report (recordException). Never log PII: emails, names, phone numbers, tokens, precise location.
Metrics. Metrics answer "how many" and "how much": error rate, request latency percentiles, crash-free users. You alert on metrics, not on individual logs. Some come for free: Android vitals in Play Console reports user-perceived crash and ANR rates per daily active user, and Crashlytics computes crash-free statistics per version. Others you emit yourself, as custom trace metrics or analytics events.
Traces. Firebase Performance Monitoring records an app start trace, screen rendering traces and HTTP network requests automatically (network capture needs its Gradle plugin). For your own flows you add custom code traces with newTrace(...), the trace { } helper or the @AddTrace annotation, with up to 32 metrics and 5 custom attributes per trace. Following one request from the app into backend services is distributed tracing, which needs a trace ID propagated in a request header (OpenTelemetry uses the W3C traceparent header). OpenTelemetry for Android is an official OpenTelemetry project that exports traces, metrics and logs to any OTLP backend.
| Type | Answers | Example | Typical Android tool |
|---|---|---|---|
| Log | What happened, with which context? | checkout_failed http_status=503 | Timber, Crashlytics log() |
| Metric | How often or how much, over time? | Checkout error rate per app version | Android vitals, Crashlytics, analytics |
| Trace | Where did the time go in one operation? | Button tap to profile rendered | Firebase Performance, OpenTelemetry |
Notes
- Structured logs (event name plus fixed keys) can be filtered and counted in a log backend; free-text strings cannot.
- Plant
Timber.DebugTree()only in debug builds. In release, plant a customTimber.Treethat drops low levels and forwards the rest to a remote sink. - Never log PII (emails, names, phone numbers, auth tokens). Use a random installation or session ID, and scrub before logging, not in the backend.
- Do not log request or response bodies in release. Set OkHttp's
HttpLoggingInterceptortoLevel.NONEthere and useredactHeader("Authorization")where logging stays on. - Sample high-frequency events (scrolling, frame callbacks, polling) on the device to save battery and data. Never sample errors you alert on without accounting for it.
- Alert on metrics (rates per app version), and use logs and traces to explain an alert.
- Crashlytics
setCustomKeyandlogadd context to the next crash or non-fatal;recordExceptionsends a caught exception as a non-fatal. - Keep trace names and attributes low-cardinality ("feed_type=home", not a user ID). Firebase Performance allows 5 custom attributes and 32 metrics per trace.
ApplicationExitInfo(Android 11, API 30+) tells you on the next launch why the process ended, including low-memory kills that produce no crash report.- Respect consent: Crashlytics and Performance Monitoring collection can be turned off at runtime (
setCrashlyticsCollectionEnabled,isPerformanceCollectionEnabled) until the user agrees, where your privacy policy requires it.
Code example
This shows a release logging setup with Timber and Crashlytics that scrubs sensitive values, plus a Firebase Performance custom trace around a user-visible operation.
import android.app.Application
import android.util.Log
import com.google.firebase.Firebase
import com.google.firebase.crashlytics.crashlytics
import com.google.firebase.perf.performance
import com.google.firebase.perf.trace
import timber.log.Timber
class App : Application() {
override fun onCreate() {
super.onCreate()
// BuildConfig needs buildFeatures { buildConfig = true } in AGP 8+
if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree()) else Timber.plant(ReleaseTree())
}
}
/** Release tree: INFO and above become Crashlytics breadcrumbs, errors become non-fatals. */
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)
}
}
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 ProfileRepository(private val api: ProfileApi, private val parser: ProfileParser) {
suspend fun loadProfile(): Profile =
Firebase.performance.newTrace("load_profile").trace {
val json = api.fetchProfileJson() // the HTTP call is also captured as a network trace
val profile = parser.parse(json) // CPU work; the parser switches to an injected Default dispatcher
putAttribute("source", "network") // low-cardinality, no user data
putMetric("item_count", profile.items.size.toLong())
profile
}
}
// Structured event: fixed event name plus keys, no free text, no PII.
fun logCheckoutFailed(httpStatus: Int, screen: String) {
Firebase.crashlytics.setCustomKey("screen", screen)
Timber.w("checkout_failed http_status=%d screen=%s", httpStatus, screen)
}DebugTreeexists only in debug builds, so release Logcat stays quiet.ReleaseTreedropsVERBOSEandDEBUGwithisLoggable, scrubs each message and sends errors as non-fatals.Trace.trace { }starts the trace, runs the block and stops it. Because it isinline, the block can call suspend functions.- Custom keys and log lines are stored locally and uploaded with the next crash or non-fatal, so they cost nothing until something goes wrong.
- The scrubber is a safety net. The first defence is never passing user data into log calls at all.
Run the idea in plain Kotlin
A small structured logger redacts sensitive keys and samples DEBUG events, keeping the first and then every fifth one. Errors are never sampled.
data class LogEvent(val level: String, val name: String, val attrs: Map<String, String>)
object Redactor {
private val sensitiveKeys = setOf("email", "token", "password", "phone")
fun clean(attrs: Map<String, String>): Map<String, String> =
attrs.mapValues { (key, value) -> if (key.lowercase() in sensitiveKeys) "[REDACTED]" else value }
}
class StructuredLogger(private val sampleEvery: Int) {
private var debugCount = 0
val sent = mutableListOf<LogEvent>()
fun log(level: String, name: String, attrs: Map<String, String>) {
if (level == "DEBUG") {
debugCount++
if (debugCount % sampleEvery != 1) return
}
val event = LogEvent(level, name, Redactor.clean(attrs))
sent += event
println(event.level + " " + event.name + " " + event.attrs)
}
}
fun main() {
val logger = StructuredLogger(sampleEvery = 5)
val traceId = "trace-0001"
logger.log("INFO", "login_started", mapOf("trace_id" to traceId, "email" to "a@example.com"))
repeat(10) { i -> logger.log("DEBUG", "scroll", mapOf("trace_id" to traceId, "index" to i.toString())) }
logger.log("ERROR", "login_failed", mapOf("trace_id" to traceId, "http_status" to "503", "token" to "abc123"))
println("Sent " + logger.sent.size + " of 12 events")
}Expected output:
INFO login_started {trace_id=trace-0001, email=[REDACTED]}
DEBUG scroll {trace_id=trace-0001, index=0}
DEBUG scroll {trace_id=trace-0001, index=5}
ERROR login_failed {trace_id=trace-0001, http_status=503, token=[REDACTED]}
Sent 4 of 12 events
In production
- A security review of the log backend found
Authorization: Bearer ...headers in thousands of entries. - OkHttp's
HttpLoggingInterceptorwas set toLevel.BODYfor every build type, and a release Timber tree forwarded every line to the remote sink. - Anyone with read access to the logging tool could have replayed those tokens until they expired.
- The interceptor is now added only in debug builds, and calls
redactHeader("Authorization")andredactHeader("Cookie")even there. - The release tree drops
DEBUGand below and runs a scrubber for emails and bearer tokens before forwarding. - A unit test feeds known secrets through the release tree and asserts they never reach the sink. The exposed tokens were revoked server side.
- After a release, users said the profile screen took noticeably longer to appear. Firebase Performance network traces for the profile endpoint showed no change in response time.
- The backend team concluded the API was fine, which was true: the time was being spent on the device.
- Nothing measured the steps between the response arriving and the screen rendering.
- The team wrapped the screen load in a custom trace (
load_profile) and added separate traces for fetching and parsing. - The parse trace dominated: a new feature parsed a large cached JSON file on the main thread before the network call.
- Parsing moved to an injected
Dispatchers.Default, and the trace durations for the next release confirmed the fix.
Common mistakes
- Logging PII. Emails, names and tokens in logs create privacy (GDPR, CCPA) and security exposure. Log random IDs and coarse values only.
- Free-text log messages.
"User loaded 12 items in 340ms"cannot be grouped or counted. Use a fixed event name and keys (items=12 duration_ms=340). - Planting
DebugTreein 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. - Synchronous logging on the main thread. A logger that writes files or makes network calls inline can drop frames or cause ANRs. Buffer and send in the background; Crashlytics already does this.
- Logging at high frequency. Logging in
onDraw, a scroll listener or a frame callback floods the pipeline and drains the battery. Sample, or aggregate into a metric. - High-cardinality trace attributes. Putting a user ID or full URL into a trace attribute makes dashboards useless and may leak personal data. Use small, fixed value sets.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you handle logging in a production Android app?”
“What is the difference between a log, a metric and a trace?”
“Users say the app is slow for some of them. How do you investigate?”
“Why must you keep PII out of mobile logs and telemetry?”
Quiz
Which of these is a metric rather than a log?
What is the main benefit of structured logging?
How should Timber be set up in a release build?
You want to measure how long one checkout flow takes, split into network and parsing steps. Which tool fits best?
0 of 4 answered
Mini task
Task: Build a safe structured logger
Goal: Create a logging wrapper that redacts sensitive values and samples noisy events.
- Create a class
SafeLoggerwith a functionlogEvent(level: String, name: String, attributes: Map<String, String>). - Define
SENSITIVE_KEYS = setOf("password", "token", "email"). - Inside
logEvent, replace the value of any attribute whose key is inSENSITIVE_KEYS(ignoring case) with"[REDACTED]". - Drop all but every tenth
DEBUGevent. Never dropWARNorERROR. - Print the level, name and cleaned map for each event that is kept.
Done condition: logging "email" to "test@example.com" prints email=[REDACTED], and logging 20 DEBUG events prints exactly 2 of them.