When debugging apps, we sometimes start putting logging statements all over the code to figure out what’s going on:
That works, but it happens that we forget to remove the logs before committing, and they either get flagged in the code review, or they’re still there when we release.
It’s good practice not to leave debug logging statements behind after you’re done debugging, even if you use ProGuard to strip them out, since they have a detrimental impact on the Signal-to-Noise ratio of your codebase. Like comments, logging statements can easily get out of sync with the surrounding code, becoming useless at best, or misleading as worst.
The situation is even more complicated when our logging statements require some conditional checks before being performed. Now you have potentially expensive and useless ifs scattered around as well.
What if there was a way to have debug-only logging without adding any code?
Well, it turns out, there is. IntelliJ IDEA and Android Studio allow you to create non-suspending breakpoints:
How do you create a non-suspending breakpoint? You first create a normal breakpoint, either by clicking in the editor gutter, or by using the
Cmd-F8 shortcut. Then, you can edit the breakpoint by either right-clicking it, or by using the
Cmd-Shift-F8 shortcut. You will be presented with the above dialog, where you can untick Suspend and specify whether you want to have the IDE automatically print out some predefined information, or the result of an expression you provide.
For example, I can replace one of the last couple of logs with this non-suspending breakpoint:
The whole code will then look like this once all breakpoints are replaced:
Much better, right? Now go and use non-suspending breakpoints! All you need to do is run the app with the debugger attached, and the messages will show up in the debug console.
The richness of the breakpoints functionality in the IDE is not limited to this kind of simple logging either. You can add conditions to breakpoints, use combinations of breakpoints to only have certain breakpoints enabled after another is hit, and many other things.
I believe there’s so many great things the IDEA debugger can do, and it’s such an under-appreciated piece of the IDE that can be immensely helpful. While the logging feature of non-suspending breakpoints has been brought up already in the past, it has still flown largely under the radar, and it’s not even the best bit.
I hope this quick tip will encourage more people to look into the tools that we have at our disposal and realise how powerful they are!