Use Timber for Android Logging

December 20, 2018

Why use Timber?

  • Don’t need to declare TAG anymore, as it will automatically use the current class name as TAG.
  • You can redirect log output (e.g. log everything to logcat during debug, and log error to Crashlytics in release build).

Timber Setup

// https://mvnrepository.com/artifact/com.jakewharton.timber/timber
implementation 'com.jakewharton.timber:timber:4.7.1'
import android.app.Application;
import timber.log.Timber
import timber.log.Timber.DebugTree

/** A tree which logs important information for crash reporting.  */

class CrashReportingTree: Timber.Tree() {
    override fun isLoggable(tag: String?, priority: Int): Boolean {
        return priority >= Log.INFO
    }

    override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
        if (priority == Log.VERBOSE || priority == Log.DEBUG) {
            return
        }

        // CrashAnaytics doSomething
        /*
        Crashlytics.log(priority, tag, message);
        if (t != null) {
            if (priority == Log.ERROR) {
                Crashlytics.logException(t);
            }
        }
        */
    }
}

public class LuaApp : Application {
    override fun onCreate() {
        if (BuildConfig.DEBUG) {
            Timber.plant(DebugTree())
        } else {
            Timber.plant(CrashReportingTree())
        }
    }
}

Logging

Debug logging with string formatting (Kotlin)

Timber.d("Hello, $name")

Debug logging with string formatting (Java)

Timber.d("Hello, %s", $name);

Use custom tag

Timber.tag("Urgent").w("Warning");

Exception logging

try {

}
catch (e: Exception) {
  // e.printStackTrace()
  Timber.e(e)
}

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.