How to integrate Timber with Crashlytics or other crash reporting tools in Kotlin Android
How to integrate Timber with Crashlytics or other crash reporting tools in Kotlin Android.
Here's a step-by-step tutorial on integrating Timber with Crashlytics or other crash reporting tools in Kotlin Android.
Step 1: Add dependencies
First, open your project's build.gradle
file and add the following dependencies to the dependencies
block:
implementation 'com.jakewharton.timber:timber:4.7.1'
implementation 'com.crashlytics.sdk.android:crashlytics:2.11.1'
Step 2: Initialize Crashlytics
In your Application
class, initialize Crashlytics by adding the following code in the onCreate
method:
import com.crashlytics.android.Crashlytics
import io.fabric.sdk.android.Fabric
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
Fabric.with(this, Crashlytics())
}
}
Step 3: Configure Timber
Create a new Kotlin file called TimberInitializer.kt
and add the following code:
import timber.log.Timber
class TimberInitializer {
fun init() {
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
} else {
Timber.plant(CrashlyticsTree())
}
}
}
class CrashlyticsTree : Timber.Tree() {
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (priority == Log.VERBOSE || priority == Log.DEBUG) {
return
}
Crashlytics.log(priority, tag, message)
if (t != null) {
if (priority == Log.ERROR || priority == Log.WARN) {
Crashlytics.logException(t)
}
}
}
}
Step 4: Initialize Timber
In your Application
class, initialize Timber by adding the following code in the onCreate
method:
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
TimberInitializer().init()
}
}
Step 5: Use Timber for logging
Now you can use Timber for logging throughout your app. Here's an example:
import timber.log.Timber
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Timber.d("Activity created")
try {
// Code that may throw an exception
} catch (e: Exception) {
Timber.e(e, "An error occurred")
}
}
}
Step 6: Test crash reporting
To test crash reporting, you can force a crash in your app. Here's an example:
import com.crashlytics.android.Crashlytics
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Crashlytics.getInstance().crash()
}
}
When the crash occurs, Crashlytics will log the crash information and you can view it in the Crashlytics dashboard.
That's it! You have successfully integrated Timber with Crashlytics or other crash reporting tools in your Kotlin Android app.