Sunday, August 28, 2011

Android Logging Best Practices

You are implementing some small piece of logic, deep inside of your code's activities and a crash occurs, problem is, you have been scrolling LogCat window and you can't find your exception. Here are some best ways to stop wasting time, filtering out the useless:
  • Create a TAG with which you will be logging all the time. Saves memory and time. i.e. 
public static final String TAG = "MyApplicationTag";
or
public static final String TAG = MyActivityClass.class.getSimpleName();

...

Then in your code:
...

Log.d(TAG, "log this");


One for an entire application, one per activity. As long as it makes sense to you and you can quickly find it.

Additional tips:
  • Setup additional tabs inside of LogCat. These are very useful:
    • AndroidRuntime
    • System.err
    • MediaProvider
  • Create a utility class
public static class SuperAppLog {

public final static String TAG = SuperAppLog.class.getSimpleName();

public void error(String message) {
// .. do some app wide logging
// .. redirect to a file
// .. fire off a analytics logging request
// .. etc
}

}



That's it. If you want to get more fancy or mess around with Log levels, check out this answer or this guide.

Happy Coding!