Logcat and the debugger
Why it matters
- Most runtime bugs (crashes, ANRs, wrong view sizes) are invisible until you read the right log line or pause at the right frame; knowing the filters saves time on every session.
- Interviewers ask you to describe a real debugging session; a structured answer that names the buffer, the filter, and the breakpoint type shows you have done it for real.
- Logcat only exists on the device in front of you. Logs from users' phones never reach you, so production crashes need a crash reporter and Android vitals, not
Logcalls. - Conditional breakpoints, logging breakpoints and field watchpoints turn a long hunt for a rare bug into a few minutes of work.
The simple explanation
- Logcat is the security-camera feed for the whole device: every process writes into a few shared ring buffers.
- A tag filter is like pointing the camera at one door instead of the whole building.
- A conditional breakpoint is a motion sensor that only triggers the alarm when a specific person walks by, not every footstep.
- The crash buffer is a separate tape just for crashes: it keeps the stack trace after your app's process has died, until newer entries overwrite it.
- Layout Inspector is a freeze-frame of the UI tree, like pausing a video and inspecting each layer of a sandwich.
Logcat reads ring buffers kept in memory by the logd daemon. Every line has a timestamp, a process ID and thread ID, a level, and a tag. adb logcat shows the main, system and crash buffers by default; events (binary system events) and radio are separate. Android Studio's Logcat window uses a query syntax such as package:mine tag:Network level:WARN, and supports regex with tag~: and message~:.
In the debugger you set breakpoints in the gutter. A conditional breakpoint pauses only when a boolean expression is true, which saves you from stepping through thousands of iterations. A logging breakpoint (uncheck "Suspend" and log an expression) prints a value without stopping the app and without adding a Log line. A field watchpoint pauses when a field is read or written, which helps when you cannot find the code that changes a value. The Evaluate expression dialog (Alt+F8 on Windows and Linux, Option+F8 on macOS) runs code in the paused frame.
adb logcat is the CLI equivalent. You filter by tag with positional tag:priority specs (add *:S to silence everything else), by process with --pid, and by buffer with -b / --buffer. The -c flag clears the buffers before a fresh run; -d dumps and exits.
Layout Inspector shows the live View or Compose hierarchy of a debuggable app, with sizes, positions and attributes for each node. It needs no code changes.
| Command | Purpose |
|---|---|
adb logcat -c | Clear the log buffers |
adb logcat --pid=<id> | Show logs for one process |
adb logcat -b crash -d | Dump the crash buffer and exit |
adb shell am start -n pkg/.Act | Launch an activity from shell |
adb shell dumpsys activity top | Dump the top activity's state and view hierarchy |
R8 does not remove Log calls by default. They stay in release builds unless you add -assumenosideeffects rules for android.util.Log. Either way, those logs stay on the user's device, so production diagnostics come from a crash-reporting SDK and Play Console's Android vitals.
Notes
- The common buffers are
main(app logs),system(system services, such asActivityManager),crash(fatal exception stack traces),events(binary system events) andradio(telephony).adb logcatshowsmain,systemandcrashunless you pass-b. - Buffers live in memory and are fixed-size rings: they survive your app's process dying, but old lines are overwritten, and everything is lost on reboot. Check sizes with
adb logcat -g. - The level order is VERBOSE < DEBUG < INFO < WARN < ERROR < ASSERT. In
adb logcatfilters the letters areV D I W E F S, whereS(silent) hides everything for that tag. - A conditional breakpoint is set by right-clicking the breakpoint dot and entering a Kotlin or Java expression. It is evaluated at every hit, which slows the app down; keep the expression cheap (a field check, not a network call).
- A field watchpoint (set on a field declaration) pauses when that field is accessed or modified. It is slower than a line breakpoint, so remove it when you are done. For native C/C++ code, the equivalent is a watchpoint on a memory address.
- Evaluate expression runs in the context of the paused frame. You can inspect a
Bundleor call methods, but calling a method that has side effects really changes app state. adb logcat -cclears the buffers. Run it before a fresh launch so you do not read stale lines from a previous session.adb shell setprop log.tag.MyTag Vsets the minimum level for that tag, which is whatLog.isLoggable("MyTag", Log.VERBOSE)reports. Code that guards verbose logging withisLoggablecan be switched on without a rebuild. The setting is lost on reboot.- Layout Inspector works on both View and Compose hierarchies. For Compose it shows composables by function name and can show recomposition counts.
Logcalls stay in release builds by default. Do not log tokens or personal data: anyone with adb access to the device can read them.adb shell dumpsys activity topprints the top activity's state, including its fragments and view hierarchy. It is a quick way to see what the user is looking at without attaching the debugger.
Code example
This script shows the adb commands you reach for most often: clearing the buffer, filtering by PID and tag, reading the crash buffer, launching an activity, and changing a per-tag log level at runtime.
# Clear the buffers, then capture only your app's logs
adb logcat -c
adb logcat --pid=$(adb shell pidof -s com.example.app)
# Filter by tag and minimum level (V D I W E F S); *:S silences all other tags
adb logcat NetworkClient:V DbHelper:W *:S
# Read the crash buffer; -d dumps and exits instead of tailing
adb logcat -b crash -d
# Launch an activity from shell, then watch its logs
adb shell am start -n com.example.app/.ui.MainActivity
adb logcat --pid=$(adb shell pidof -s com.example.app)
# Dump the top activity's state and view hierarchy (no debugger needed)
adb shell dumpsys activity top | head -60
# Change a per-tag log level at runtime, no rebuild
adb shell setprop log.tag.NetworkClient V
# ANR reports are logged by ActivityManager in the system buffer
adb logcat -b system -d | grep -i "ANR in"-cbefore a fresh launch prevents you from reading stale lines from a previous session.tag:priorityspecs are positional arguments; you can pass several, and*:Sturns the list into an allowlist.-b crash -dprints only fatal exception stack traces. It is the quickest way to find the crash on a test device after the app has already closed.pidof -sreturns a single PID; without-s, an app with several processes returns several.
Run the idea in plain Kotlin
enum class LogLevel(val priority: Int) {
VERBOSE(2), DEBUG(3), INFO(4), WARN(5), ERROR(6), ASSERT(7)
}
data class LogEntry(val tag: String, val level: LogLevel, val message: String)
fun filterLogs(
entries: List<LogEntry>,
minLevel: LogLevel,
tagFilter: String?
): List<LogEntry> {
return entries.filter { entry ->
entry.level.priority >= minLevel.priority &&
(tagFilter == null || entry.tag == tagFilter)
}
}
fun main() {
val logs = listOf(
LogEntry("Network", LogLevel.DEBUG, "Request sent to /api/users"),
LogEntry("Network", LogLevel.INFO, "Response 200"),
LogEntry("Database", LogLevel.WARN, "Slow query"),
LogEntry("Network", LogLevel.ERROR, "Connection timeout"),
LogEntry("Database", LogLevel.DEBUG, "Cache hit for user:42"),
LogEntry("UI", LogLevel.INFO, "Fragment resumed: ProfileFragment")
)
println("All logs at WARN and above:")
filterLogs(logs, LogLevel.WARN, null).forEach { entry ->
println(" [" + entry.level.name + "] " + entry.tag + ": " + entry.message)
}
println("")
println("Network tag only, DEBUG and above:")
filterLogs(logs, LogLevel.DEBUG, "Network").forEach { entry ->
println(" [" + entry.level.name + "] " + entry.tag + ": " + entry.message)
}
println("")
println("Database tag, INFO and above:")
filterLogs(logs, LogLevel.INFO, "Database").forEach { entry ->
println(" [" + entry.level.name + "] " + entry.tag + ": " + entry.message)
}
}The priorities 2 to 7 match the constants in android.util.Log (Log.VERBOSE is 2, Log.ASSERT is 7). The program prints two WARN-or-higher lines, three Network lines, and one Database line (the Slow query warning).
In production
- Users reported the app closing after entering card details, but the crash dashboard showed no matching crash.
- A payment SDK installed its own
Thread.setDefaultUncaughtExceptionHandlerafter the crash reporter had installed one. Its handler logged and killed the process, and never called the handler that was installed before it. - Crashes on any thread therefore never reached the crash reporter. Only crashes that happened before the SDK was initialized appeared in the dashboard.
- Reproduce on a test device using the SDK's sandbox, then run
adb logcat -b crash -d. On current Android versions the runtime writesFATAL EXCEPTIONwith the stack trace to the crash buffer even when the app's own handler swallows it. - Initialize the crash reporter after the SDK, or wrap the SDK's handler so it always forwards to the previously installed handler.
- Add an instrumented test that installs all SDKs, throws on a background thread, and asserts the crash reporter's handler was called.
- Scrolling a long list in a
RecyclerViewjanked, and the profiler showed far moreonBindViewHoldercalls than visible rows. - A plain breakpoint in
onBindViewHolderwas useless: it stopped on every normal bind during scrolling. - The team suspected something was calling
notifyDataSetChanged(), but could not see what.
- Scroll far down the list, then set a conditional breakpoint in
onBindViewHolderwith the conditionposition == 0. Row 0 is off-screen, so a bind for it means the whole list is being rebound. - The breakpoint hit, and the call stack showed a
LiveDataobserver that was registered insideonBindViewHolder. Every bind added another observer, and each one callednotifyDataSetChanged(). - Move the observer to the fragment, observe once with
viewLifecycleOwner, and switch toListAdapterwithDiffUtilso only changed rows are rebound.
Common mistakes
- Logging sensitive data.
Logcalls stay in release builds unless you add R8 rules to remove them, and anyone with adb access to the device can read them. Never log tokens, passwords or personal data. - Filtering Logcat by tag only, ignoring the process. Several apps and system services can use the same tag. Add
package:minein Android Studio or--pidon the command line to narrow the stream to your app. - Using a regular breakpoint in a hot path. A breakpoint that hits on every frame makes the debugger unusable. Use a conditional breakpoint with a cheap expression, or a logging breakpoint that does not suspend.
- Reading only the main buffer. With
adb logcat -b main, fatal stack traces in thecrashbuffer andActivityManagerlines in thesystembuffer are hidden. Use the default buffers or add-b crash. - Not using conditional breakpoints for rare conditions. A bug that triggers rarely is impossible to catch by stepping. A condition that matches the bad state stops exactly when it happens.
- Expecting Logcat to explain production crashes. Logs never leave the user's device. Use a crash-reporting SDK, upload R8 mapping files so stack traces can be deobfuscated, and check Android vitals for crashes and ANRs.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you narrow down a Logcat flood to find the relevant log line?”
“What is a conditional breakpoint and when would you use one?”
“A crash only happens on a user's device. How do you diagnose it?”
“What are the different logcat buffers and what goes in each?”
Quiz
Which logcat buffer is dedicated to fatal exception stack traces?
What does adb logcat -c do?
A conditional breakpoint in Android Studio pauses execution when:
By default, what does R8 do to Log.d calls in a release build?
0 of 4 answered
Mini task
15-minute exercise: filter, break, and inspect
- Open your Android project in Android Studio and run a debug build on a device or emulator.
- In the Logcat window, clear the log (the trash-can icon, or
adb logcat -cin the terminal). Then filter withpackage:mine level:WARN. Confirm you see fewer lines than an unfiltered view. - Add a
Log.d("MyTag", "iteration " + i)inside aforloop that runs 1,000 times in any activity or composable. Run the app. In Logcat, filter withpackage:mine tag:MyTag. Count the lines. - Set a conditional breakpoint on that
Log.dline with the conditioni == 500. Debug the app. Confirm the debugger pauses exactly once, at iteration 500. Use Evaluate expression to typeiand confirm it shows 500. - Open Layout Inspector (in recent Android Studio versions it is part of the Running Devices window; otherwise View > Tool Windows > Layout Inspector). Select your running app. Click a node in the tree and note its width and height.
- In the terminal, run
adb shell dumpsys activity top | head -40and read the output. Identify the top activity's class name and find the start of its view hierarchy.
Done when: you have filtered Logcat by package and tag, paused at a conditional breakpoint, evaluated an expression, inspected a node in Layout Inspector, and read the dumpsys output. Screenshot each step and paste them into a notes file.