sentry-android-sdk 是做什麼的?
完整的 Sentry SDK 設定,適用於 Android 開發。當被要求「在 Android 中加入 Sentry」、「安裝 sentry-android」、「在 Android 中設定 Sentry」,或需要配置錯誤監控、追蹤、效能分析、工作階段重播或紀錄功能時使用。支援 Kotlin 和 Java 程式碼庫。
支援的功能
- 錯誤監控(Error Monitoring)
- 效能追蹤(Performance Tracing)
- 資料庫剖析(Database Profiling)
- 工作階段重播(Session Replay)
- 紀錄(Logging)
使用方式
1. 在專案的根層級 build.gradle.kts (或 build.gradle) 中加入 Sentry 外掛
// build.gradle.kts (專案層級)
plugins {
id("io.sentry.android.gradle") version "4.12.0" apply false
}
或使用 Groovy:
// build.gradle (專案層級)
buildscript {
dependencies {
classpath 'io.sentry:sentry-android-gradle-plugin:4.12.0'
}
}
2. 在應用程式模組的 build.gradle.kts (或 build.gradle) 中套用外掛並加入相依性
// build.gradle.kts (app 模組層級)
plugins {
id("com.android.application")
id("io.sentry.android.gradle")
}
dependencies {
implementation("io.sentry:sentry-android:7.16.0")
}
或使用 Groovy:
// build.gradle (app 模組層級)
plugins {
id 'com.android.application'
id 'io.sentry.android.gradle'
}
dependencies {
implementation 'io.sentry:sentry-android:7.16.0'
}
3. 初始化 Sentry
在您的 AndroidManifest.xml 中加入中繼資料(Metadata):
<application>
<meta-data
android:name="io.sentry.dsn"
android:value="https://[email protected]/0" />
</application>
或者透過程式碼初始化:
import io.sentry.Sentry
import io.sentry.android.core.SentryAndroid
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
SentryAndroid.init(this) { options ->
options.dsn = "https://[email protected]/0"
options.tracesSampleRate = 1.0
options.profilesSampleRate = 1.0
}
}
}
4. 配置效能追蹤與工作階段重播(選擇性)
SentryAndroid.init(this) { options ->
options.dsn = "https://[email protected]/0"
options.tracesSampleRate = 1.0
options.profilesSampleRate = 1.0
// 啟用工作階段重播
options.experimental.sessionReplay.sessionSampleRate = 1.0
options.experimental.sessionReplay.onErrorSampleRate = 1.0
}
進階設定
自動上傳原始碼對應檔案(ProGuard / R8)
若已套用 io.sentry.android.gradle 外掛,建置時會自動上傳對應的對映檔案。您也可以在 build.gradle.kts 中進一步自訂:
sentry {
autoUploadProguardMapping.set(true)
includeProguardMapping.set(true)
uploadNativeSymbols.set(true)
}
紀錄整合
若要同時啟用紀錄功能,可以加入 sentry-android-logcat:
dependencies {
implementation("io.sentry:sentry-android-logcat:7.16.0")
}
注意事項
- 請務必將
DSN換成您 Sentry 專案中實際的 DSN 金鑰。 - 如果需要更詳細的設定選項,請參考 Sentry Android SDK 官方文件。
- 若是使用 Jetpack Compose 專案,可額外加入
sentry-android-compose相依性以取得更緊密的整合。