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.Timberimport 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)}
Log exception with message
try {}catch (e: Exception) { Timber.w(e, "Add failure")}
References: