5 Principles of Android Logging

A recent question got me thinking about how I use logging in my development/debug process.

Don’t tell lies.

Remember that it’s easy to lie to yourself with logs. I can’t tell you how many times I have made incorrect assumptions about what is going wrong with my code based on the truth presented by the logs. Eventually after exhausting all the other options you finally start tracking down the real problem.

Discover truths.

I generally use logs when I’m trying to understand the control flow of my program. It’s completely up to you when you want to use them. I often add log statements to the lifecycle methods (e.g. onCreate(), onResume()) and important functions that I create to do the work. I like to add the value of the the item I’m inspecting or handling in that function.

Log with levels.

I almost exclusively use debugging level Log.d() unless it’s an exception and then I’ll use Log.w() or Log.e(). It doesn’t really matter as long as it helps you and makes it easier for others to contribute later.

Add visual parsing.

Logs can get overwhelming, so I like to color my output in IntelliJ/Android Studio (AS) so that it’s not a big flow of useless text flying by. There’s also filtering options in AS that will help you find logs just for your application. I rarely use logcat on the command line unless I’m dumping the output to a file.

Android Logcat example. @coreylatislaw.com

Logs are code too!

Make sure to treat them with the same care as other lines of code (you’ll be maintaining them just as long). A bad practice with logging is leaving in random strings like “Corey” as the logging tag instead of something useful. I suggest defining a TAG variable for your class and use that instead:

private static final String TAG = YourClass.class.getSimpleName();

Bonus

The original question was about logging, but several commenters mentioned the virtues of debugging. There’s a long standing debate about whether watching logs fly by your face or stopping the flow of time to inspect each detail is a better approach, but you don’t have to choose! They both have value. Collect information from sources that are useful to you and expand when you’re ready.

Just starting out with Android development? Join my mailing list for tips and tricks of the trade.

Leave a Reply

Your email address will not be published. Required fields are marked *