vxh.viet
8/24/2016 - 10:54 AM

Replace Android log with Timber

Replace Android log with Timber

The Why:

Why do we need to replace handy Android Log with Timber? Two reasons:

  • Security: in short, ProGuard can not remove Log that has string concatenation. Something like this:

    Log.d(TAG, "Message"); can be removed by ProGuard.

    but something like this:

    Log.d(TAG, "Message" + MySecret.getMySecret()) get translated into bytecode like this:

    new StringBuilder("Message").append(MySecret.getMySecret());; anyone reverse-engineer the app can read your secret.

  • Performance: One, String concatenation is a costly operation. Two, if the appending MySecret.getMySecret() is a very complex operation (like you have to bury your Mistress's number under 2 or more AES/ SHA-256 encryption) that would be a lot of unnecessary extra overhead. Three, if you were someone that is very pure with completely no secret (like me ;)), that's a potential NullPointerException which has just been added to production code.

The How:

Great, I get it, time waster. But I'm so used to the old handy Log, how can I change to Timber?

You use String format instead of String concatenation. So something like this:

Log.d(TAG, "Message" + someRandomInteger);
Log.d(TAG, "Message" + someRandomString);

will be rewritten like this:

Timber.d("Message %d", someRandomInteger);
Timber.d("Message %s", someRandomString);

For additional String format reference, see (this cheatsheet).

Oh, and did I tell you that you dont have to write this shit anymore?

private static final String TAG = "MySecret";

The Setup:

I set it all up for you, but if you are curious, see Set up Timber and Crashlytic.

In short, only two thing you have to remember:

  • Debug with Timber.d, this log will only show up in the debug build.

  • Any critical error that you think I should know about in the release build, use Timber.e (error) or Timber.w (warning). This will get pushed into Crashlytic. For example:

try {
  callMyMistress();
} catch (InvalidPhoneNumberException e) {
  Timber.e("WTF??? Has she just dumped me??? Totally irrelevant but whoever monitoring Crashlytic should know about this tragedy!");
}

Also, see Crashlytic's issue #339 for a real example.

The Get It:

Okay, okay smartass, anything to shut you up. But Im so use to typing logd to get a nice shiny Log, I dont what to type Timber.d, those are 3 EXTRA characters, you get me???

I got you all sorted out. Download this Live Template and import it to Android Studio with File → Import Settings….. Now you can simply type timd or time to Timber. For the more curious that want to customize it, see here.

TL;DR:

  • Use Timber.d("Message"); to debug.

  • Use Timber.e("Message"); to send the error to Crashlytic.

  • Or if you want to keep me awake all night, just use Timber.e for everything.