sentry-android-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
All Skills > SDK Setup > Android SDK
All Skills > SDK Setup > Android SDK

Sentry Android SDK

Sentry Android SDK

Opinionated wizard that scans your Android project and guides you through complete Sentry setup — error monitoring, tracing, profiling, session replay, logging, and more.
这个定制化向导会扫描你的Android项目,引导你完成Sentry的全量配置,包括错误监控、链路追踪、性能剖析、会话回放、日志等功能。

Invoke This Skill When

适用调用场景

  • User asks to "add Sentry to Android" or "set up Sentry" in an Android app
  • User wants error monitoring, crash reporting, ANR detection, tracing, profiling, session replay, or logging in Android
  • User mentions
    sentry-android
    ,
    io.sentry:sentry-android
    , mobile crash tracking, or Sentry for Kotlin/Java Android
  • User wants to monitor native (NDK) crashes, application not responding (ANR) events, or app startup performance
Note: SDK versions and APIs below reflect current Sentry docs at time of writing (
io.sentry:sentry-android:8.33.0
, Gradle plugin
6.1.0
). Always verify against docs.sentry.io/platforms/android/ before implementing.

  • 用户要求在Android应用中「添加Sentry」或者「配置Sentry」
  • 用户需要为Android应用配置错误监控、崩溃上报、ANR检测、链路追踪、性能剖析、会话回放或日志功能
  • 用户提到
    sentry-android
    io.sentry:sentry-android
    、移动端崩溃追踪,或面向Kotlin/Java Android的Sentry相关内容
  • 用户想要监控原生(NDK)崩溃、应用无响应(ANR)事件或应用启动性能
注意: 下文提到的SDK版本和API对应编写时的官方Sentry文档版本(
io.sentry:sentry-android:8.33.0
,Gradle插件版本
6.1.0
)。 实施前请务必对照docs.sentry.io/platforms/android/确认最新内容。

Phase 1: Detect

阶段1:项目探测

Run these commands to understand the project before making any recommendations:
bash
undefined
在给出任何推荐方案前,请先运行以下命令了解项目结构:
bash
undefined

Detect project structure and build system

探测项目结构和构建系统

ls build.gradle build.gradle.kts settings.gradle settings.gradle.kts 2>/dev/null
ls build.gradle build.gradle.kts settings.gradle settings.gradle.kts 2>/dev/null

Check AGP version and existing Sentry

检查AGP版本和已有的Sentry配置

grep -r '"com.android.application"' build.gradle* app/build.gradle* 2>/dev/null | head -3 grep -ri sentry build.gradle* app/build.gradle* 2>/dev/null | head -10
grep -r '"com.android.application"' build.gradle* app/build.gradle* 2>/dev/null | head -3 grep -ri sentry build.gradle* app/build.gradle* 2>/dev/null | head -10

Check app-level build file (Groovy vs KTS)

检查应用级构建文件类型(Groovy还是KTS)

ls app/build.gradle app/build.gradle.kts 2>/dev/null
ls app/build.gradle app/build.gradle.kts 2>/dev/null

Detect Kotlin vs Java

探测是Kotlin还是Java项目

find app/src/main -name ".kt" 2>/dev/null | head -3 find app/src/main -name ".java" 2>/dev/null | head -3
find app/src/main -name ".kt" 2>/dev/null | head -3 find app/src/main -name ".java" 2>/dev/null | head -3

Check minSdk, targetSdk

检查minSdk、targetSdk版本

grep -E 'minSdk|targetSdk|compileSdk|minSdkVersion|targetSdkVersion' app/build.gradle app/build.gradle.kts 2>/dev/null | head -6
grep -E 'minSdk|targetSdk|compileSdk|minSdkVersion|targetSdkVersion' app/build.gradle app/build.gradle.kts 2>/dev/null | head -6

Detect Jetpack Compose

探测是否使用Jetpack Compose

grep -E 'compose|androidx.compose' app/build.gradle app/build.gradle.kts 2>/dev/null | head -5
grep -E 'compose|androidx.compose' app/build.gradle app/build.gradle.kts 2>/dev/null | head -5

Detect OkHttp (popular HTTP client — has dedicated integration)

探测是否使用OkHttp(流行HTTP客户端,有专属集成方案)

grep -E 'okhttp|retrofit' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
grep -E 'okhttp|retrofit' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3

Detect Room or SQLite

探测是否使用Room或SQLite

grep -E 'androidx.room|androidx.sqlite' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
grep -E 'androidx.room|androidx.sqlite' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3

Detect Timber (logging library)

探测是否使用Timber(日志库)

grep -E 'timber' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
grep -E 'timber' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3

Detect Jetpack Navigation

探测是否使用Jetpack Navigation

grep -E 'androidx.navigation' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
grep -E 'androidx.navigation' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3

Detect Apollo (GraphQL)

探测是否使用Apollo(GraphQL)

grep -E 'apollo' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3
grep -E 'apollo' app/build.gradle app/build.gradle.kts 2>/dev/null | head -3

Check existing Sentry initialization

检查已有的Sentry初始化代码

grep -r "SentryAndroid.init|io.sentry.Sentry" app/src/ 2>/dev/null | head -5
grep -r "SentryAndroid.init\|io.sentry.Sentry" app/src/ 2>/dev/null | head -5

Check Application class

检查Application类

find app/src/main -name ".kt" -o -name ".java" 2>/dev/null | xargs grep -l "Application()" 2>/dev/null | head -3
find app/src/main -name ".kt" -o -name ".java" 2>/dev/null | xargs grep -l "Application()" 2>/dev/null | head -3

Adjacent backend (for cross-linking)

相邻后端项目(用于跨端链路关联)

ls ../backend ../server ../api 2>/dev/null find .. -maxdepth 2 ( -name "go.mod" -o -name "requirements.txt" -o -name "Gemfile" ) 2>/dev/null | grep -v node_modules | head -5

**What to determine:**

| Question | Impact |
|----------|--------|
| `build.gradle.kts` present? | Use Kotlin DSL syntax in all examples |
| `minSdk < 26`? | Note Session Replay requires API 26+ — silent no-op below that |
| Compose detected? | Recommend `sentry-compose-android` and Compose-specific masking |
| OkHttp present? | Recommend `sentry-okhttp` interceptor or Gradle plugin bytecode auto-instrumentation |
| Room/SQLite present? | Recommend `sentry-android-sqlite` or plugin bytecode instrumentation |
| Timber present? | Recommend `sentry-android-timber` integration |
| Jetpack Navigation? | Recommend `sentry-android-navigation` for screen tracking |
| Already has `SentryAndroid.init()`? | Skip install, jump to feature config |
| Application subclass exists? | That's where `SentryAndroid.init()` goes |

---
ls ../backend ../server ../api 2>/dev/null find .. -maxdepth 2 \( -name "go.mod" -o -name "requirements.txt" -o -name "Gemfile" \) 2>/dev/null | grep -v node_modules | head -5

**需要确认的信息:**

| 问题 | 影响 |
|----------|--------|
| 是否存在`build.gradle.kts`? | 所有示例使用Kotlin DSL语法 |
| `minSdk < 26`? | 说明会话回放仅支持API 26+,低于该版本会静默不生效 |
| 是否检测到Compose? | 推荐使用`sentry-compose-android`和Compose专属隐私屏蔽功能 |
| 是否存在OkHttp? | 推荐使用`sentry-okhttp`拦截器或Gradle插件字节码自动插桩 |
| 是否存在Room/SQLite? | 推荐使用`sentry-android-sqlite`或插件字节码插桩 |
| 是否存在Timber? | 推荐使用`sentry-android-timber`集成 |
| 是否使用Jetpack Navigation? | 推荐使用`sentry-android-navigation`做页面追踪 |
| 已存在`SentryAndroid.init()`代码? | 跳过安装步骤,直接进入功能配置阶段 |
| 是否存在Application子类? | `SentryAndroid.init()`需要放在该类中 |

---

Phase 2: Recommend

阶段2:方案推荐

Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
Recommended (core coverage — always set up these):
  • Error Monitoring — captures uncaught exceptions, ANRs, and native NDK crashes automatically
  • Tracing — auto-instruments Activity lifecycle, app start, HTTP requests, and database queries
  • Session Replay — records screen captures and user interactions for debugging (API 26+)
Optional (enhanced observability):
  • Profiling — continuous UI profiling (recommended) or transaction-based sampling
  • Logging — structured logs via
    Sentry.logger()
    , with optional Timber bridge
  • User Feedback — collect user-submitted bug reports from inside the app
Recommendation logic:
FeatureRecommend when...
Error MonitoringAlways — non-negotiable baseline for any Android app
TracingAlways for Android — app start time, Activity lifecycle, network latency matter
Session ReplayUser-facing production app on API 26+; visual debugging of user issues
ProfilingPerformance-sensitive apps, startup time investigations, production perf analysis
LoggingApp uses structured logging or you want log-to-trace correlation in Sentry
User FeedbackBeta or customer-facing app where you want user-submitted bug reports
Propose: "For your [Kotlin / Java] Android app (minSdk X), I recommend setting up Error Monitoring + Tracing + Session Replay. Want me to also add Profiling and Logging?"

基于探测到的信息给出具体的推荐方案,不要问开放性问题,直接给出提案:
推荐基础配置(所有场景都建议配置):
  • 错误监控 — 自动捕获未捕获异常、ANR和原生NDK崩溃
  • 链路追踪 — 自动插桩Activity生命周期、应用启动、HTTP请求和数据库查询
  • 会话回放 — 录屏和用户交互记录,用于问题调试(仅支持API 26+)
可选增强配置(提升可观测性):
  • 性能剖析 — 持续UI性能剖析(推荐)或基于事务的采样剖析
  • 日志 — 通过
    Sentry.logger()
    输出结构化日志,可选支持Timber桥接
  • 用户反馈 — 收集应用内用户提交的bug报告
推荐逻辑:
功能推荐场景
错误监控所有场景必选 — 任何Android应用的基础能力
链路追踪Android项目必选 — 用于分析应用启动时间、Activity生命周期、网络延迟
会话回放面向用户的生产环境应用且minSdk≥26;需要可视化复现用户问题的场景
性能剖析对性能敏感的应用、启动时间优化、生产环境性能分析场景
日志应用使用结构化日志,或者需要在Sentry中实现日志与链路关联的场景
用户反馈测试版或面向用户的应用,需要收集用户提交的bug报告的场景
提案示例:"针对你的[Kotlin / Java] Android应用(minSdk X),我推荐配置错误监控+链路追踪+会话回放。是否需要同时添加性能剖析和日志功能?"

Phase 3: Guide

阶段3:安装引导

Determine Your Setup Path

选择安装路径

Project typeRecommended setupComplexity
New project, no existing SentryGradle plugin (recommended)Low — plugin handles most config
Existing project, no SentryGradle plugin or manual initMedium — add dependency + Application class
Manual full control
SentryAndroid.init()
in Application
Medium — explicit config, most flexible
项目类型推荐安装方式复杂度
新项目,无已有Sentry配置Gradle插件(推荐)低 — 插件会处理大部分配置
现有项目,无Sentry配置Gradle插件或手动初始化中 — 添加依赖+在Application类初始化
需要完全手动控制配置在Application中调用
SentryAndroid.init()
中 — 配置明确,灵活性最高

Option 1: Wizard (Recommended)

选项1:向导安装(推荐)

You need to run this yourself — the wizard opens a browser for login and requires interactive input that the agent can't handle. Copy-paste into your terminal:
npx @sentry/wizard@latest -i android
It handles login, org/project selection, Gradle plugin setup, dependency installation, DSN configuration, and ProGuard/R8 mapping upload.
Once it finishes, come back and skip to Verification.
If the user skips the wizard, proceed with Option 2 (Manual Setup) below.

需要你自行运行 — 向导会打开浏览器完成登录,需要交互输入,Agent无法自动处理。 复制以下命令到终端运行:
npx @sentry/wizard@latest -i android
它会自动处理登录、组织/项目选择、Gradle插件配置、依赖安装、DSN配置和ProGuard/R8映射文件上传。
运行完成后回到本页面,直接跳转到验证环节即可。
如果用户跳过向导,请继续使用下方选项2(手动安装)。

Option 2: Manual Setup

选项2:手动安装

Path A: Gradle Plugin (Recommended)

路径A:使用Gradle插件(推荐)

The Sentry Gradle plugin is the easiest setup path. It:
  • Uploads ProGuard/R8 mapping files automatically on release builds
  • Injects source context into stack frames
  • Optionally instruments OkHttp, Room/SQLite, File I/O, Compose navigation, and
    android.util.Log
    via bytecode transforms (zero source changes)
Step 1 — Add the plugin to
build.gradle[.kts]
(project-level)
Groovy DSL (
build.gradle
):
groovy
plugins {
    id "io.sentry.android.gradle" version "6.1.0" apply false
}
Kotlin DSL (
build.gradle.kts
):
kotlin
plugins {
    id("io.sentry.android.gradle") version "6.1.0" apply false
}
Step 2 — Apply plugin + add dependencies in
app/build.gradle[.kts]
Groovy DSL:
groovy
plugins {
    id "com.android.application"
    id "io.sentry.android.gradle"
}

android {
    // ...
}

dependencies {
    // Use BOM for consistent versions across sentry modules
    implementation platform("io.sentry:sentry-bom:8.33.0")
    implementation "io.sentry:sentry-android"

    // Optional integrations (add what's relevant):
    // implementation "io.sentry:sentry-android-timber"     // Timber bridge
    // implementation "io.sentry:sentry-android-fragment"   // Fragment lifecycle tracing
    // implementation "io.sentry:sentry-compose-android"    // Jetpack Compose support
    // implementation "io.sentry:sentry-android-navigation"  // Jetpack Navigation
    // implementation "io.sentry:sentry-okhttp"             // OkHttp interceptor
    // implementation "io.sentry:sentry-android-sqlite"     // Room/SQLite tracing
    // implementation "io.sentry:sentry-kotlin-extensions"  // Coroutine context propagation
}

sentry {
    org = "YOUR_ORG_SLUG"
    projectName = "YOUR_PROJECT_SLUG"
    authToken = System.getenv("SENTRY_AUTH_TOKEN")

    // Enable auto-instrumentation via bytecode transforms (no source changes needed)
    tracingInstrumentation {
        enabled = true
        features = [InstrumentationFeature.DATABASE, InstrumentationFeature.FILE_IO,
                    InstrumentationFeature.OKHTTP, InstrumentationFeature.COMPOSE]
    }

    // Upload ProGuard mapping and source context on release
    autoUploadProguardMapping = true
    includeSourceContext = true
}
Kotlin DSL (
app/build.gradle.kts
):
kotlin
plugins {
    id("com.android.application")
    id("io.sentry.android.gradle")
}

dependencies {
    implementation(platform("io.sentry:sentry-bom:8.33.0"))
    implementation("io.sentry:sentry-android")

    // Optional integrations:
    // implementation("io.sentry:sentry-android-timber")
    // implementation("io.sentry:sentry-android-fragment")
    // implementation("io.sentry:sentry-compose-android")
    // implementation("io.sentry:sentry-android-navigation")
    // implementation("io.sentry:sentry-okhttp")
    // implementation("io.sentry:sentry-android-sqlite")
    // implementation("io.sentry:sentry-kotlin-extensions")
}

sentry {
    org = "YOUR_ORG_SLUG"
    projectName = "YOUR_PROJECT_SLUG"
    authToken = System.getenv("SENTRY_AUTH_TOKEN")

    tracingInstrumentation {
        enabled = true
        features = setOf(
            InstrumentationFeature.DATABASE,
            InstrumentationFeature.FILE_IO,
            InstrumentationFeature.OKHTTP,
            InstrumentationFeature.COMPOSE,
        )
    }

    autoUploadProguardMapping = true
    includeSourceContext = true
}
Step 3 — Initialize Sentry in your Application class
If you don't have an Application subclass, create one:
kotlin
// MyApplication.kt
import android.app.Application
import io.sentry.SentryLevel
import io.sentry.android.core.SentryAndroid
import io.sentry.android.replay.SentryReplayOptions

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        SentryAndroid.init(this) { options ->
            options.dsn = "YOUR_SENTRY_DSN"

            // Tracing — lower to 0.1–0.2 in high-traffic production
            options.tracesSampleRate = 1.0

            // Profiling — use continuous UI profiling (recommended, SDK ≥ 8.7.0)
            options.profileSessionSampleRate = 1.0

            // Session Replay (API 26+ only; silent no-op below API 26)
            options.sessionReplay.sessionSampleRate = 0.1    // 10% of all sessions
            options.sessionReplay.onErrorSampleRate = 1.0    // 100% on error

            // Structured logging
            options.logs.isEnabled = true

            // Environment
            options.environment = BuildConfig.BUILD_TYPE
        }
    }
}
Java equivalent:
java
// MyApplication.java
import android.app.Application;
import io.sentry.android.core.SentryAndroid;

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        SentryAndroid.init(this, options -> {
            options.setDsn("YOUR_SENTRY_DSN");
            options.setTracesSampleRate(1.0);
            options.setProfileSessionSampleRate(1.0);
            options.getSessionReplay().setSessionSampleRate(0.1);
            options.getSessionReplay().setOnErrorSampleRate(1.0);
            options.getLogs().setEnabled(true);
            options.setEnvironment(BuildConfig.BUILD_TYPE);
        });
    }
}
Step 4 — Register Application in
AndroidManifest.xml
xml
<application
    android:name=".MyApplication"
    ... >

Sentry Gradle插件是最简单的安装方案,它可以:
  • 发布构建时自动上传ProGuard/R8映射文件
  • 向堆栈帧注入源码上下文
  • 可选通过字节码转换实现OkHttp、Room/SQLite、文件I/O、Compose导航、
    android.util.Log
    的自动插桩(无需修改源码)
步骤1 — 在项目级
build.gradle[.kts]
中添加插件
Groovy DSL (
build.gradle
):
groovy
plugins {
    id "io.sentry.android.gradle" version "6.1.0" apply false
}
Kotlin DSL (
build.gradle.kts
):
kotlin
plugins {
    id("io.sentry.android.gradle") version "6.1.0" apply false
}
步骤2 — 在
app/build.gradle[.kts]
中应用插件并添加依赖
Groovy DSL:
groovy
plugins {
    id "com.android.application"
    id "io.sentry.android.gradle"
}

android {
    // ...
}

dependencies {
    // 使用BOM保证所有sentry模块版本一致
    implementation platform("io.sentry:sentry-bom:8.33.0")
    implementation "io.sentry:sentry-android"

    // 可选集成(按需添加):
    // implementation "io.sentry:sentry-android-timber"     // Timber桥接
    // implementation "io.sentry:sentry-android-fragment"   // Fragment生命周期追踪
    // implementation "io.sentry:sentry-compose-android"    // Jetpack Compose支持
    // implementation "io.sentry:sentry-android-navigation"  // Jetpack Navigation支持
    // implementation "io.sentry:sentry-okhttp"             // OkHttp拦截器
    // implementation "io.sentry:sentry-android-sqlite"     // Room/SQLite追踪
    // implementation "io.sentry:sentry-kotlin-extensions"  // 协程上下文传播
}

sentry {
    org = "YOUR_ORG_SLUG"
    projectName = "YOUR_PROJECT_SLUG"
    authToken = System.getenv("SENTRY_AUTH_TOKEN")

    // 启用字节码转换自动插桩(无需修改源码)
    tracingInstrumentation {
        enabled = true
        features = [InstrumentationFeature.DATABASE, InstrumentationFeature.FILE_IO,
                    InstrumentationFeature.OKHTTP, InstrumentationFeature.COMPOSE]
    }

    // 发布时自动上传ProGuard映射和源码上下文
    autoUploadProguardMapping = true
    includeSourceContext = true
}
Kotlin DSL (
app/build.gradle.kts
):
kotlin
plugins {
    id("com.android.application")
    id("io.sentry.android.gradle")
}

dependencies {
    implementation(platform("io.sentry:sentry-bom:8.33.0"))
    implementation("io.sentry:sentry-android")

    // 可选集成:
    // implementation("io.sentry:sentry-android-timber")
    // implementation("io.sentry:sentry-android-fragment")
    // implementation("io.sentry:sentry-compose-android")
    // implementation("io.sentry:sentry-android-navigation")
    // implementation("io.sentry:sentry-okhttp")
    // implementation("io.sentry:sentry-android-sqlite")
    // implementation("io.sentry:sentry-kotlin-extensions")
}

sentry {
    org = "YOUR_ORG_SLUG"
    projectName = "YOUR_PROJECT_SLUG"
    authToken = System.getenv("SENTRY_AUTH_TOKEN")

    tracingInstrumentation {
        enabled = true
        features = setOf(
            InstrumentationFeature.DATABASE,
            InstrumentationFeature.FILE_IO,
            InstrumentationFeature.OKHTTP,
            InstrumentationFeature.COMPOSE,
        )
    }

    autoUploadProguardMapping = true
    includeSourceContext = true
}
步骤3 — 在Application类中初始化Sentry
如果你还没有Application子类,请先创建一个:
kotlin
// MyApplication.kt
import android.app.Application
import io.sentry.SentryLevel
import io.sentry.android.core.SentryAndroid
import io.sentry.android.replay.SentryReplayOptions

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        SentryAndroid.init(this) { options ->
            options.dsn = "YOUR_SENTRY_DSN"

            // 链路追踪 — 高流量生产环境建议调低到0.1–0.2
            options.tracesSampleRate = 1.0

            // 性能剖析 — 使用持续UI剖析(推荐,SDK ≥ 8.7.0支持)
            options.profileSessionSampleRate = 1.0

            // 会话回放(仅支持API 26+;低于该版本会静默不生效)
            options.sessionReplay.sessionSampleRate = 0.1    // 录制10%的全量会话
            options.sessionReplay.onErrorSampleRate = 1.0    // 异常会话100%录制

            // 结构化日志
            options.logs.isEnabled = true

            // 环境标识
            options.environment = BuildConfig.BUILD_TYPE
        }
    }
}
Java版本等效代码:
java
// MyApplication.java
import android.app.Application;
import io.sentry.android.core.SentryAndroid;

public class MyApplication : Application {
    @Override
    public void onCreate() {
        super.onCreate();

        SentryAndroid.init(this, options -> {
            options.setDsn("YOUR_SENTRY_DSN");
            options.setTracesSampleRate(1.0);
            options.setProfileSessionSampleRate(1.0);
            options.getSessionReplay().setSessionSampleRate(0.1);
            options.getSessionReplay().setOnErrorSampleRate(1.0);
            options.getLogs().setEnabled(true);
            options.setEnvironment(BuildConfig.BUILD_TYPE);
        });
    }
}
步骤4 — 在
AndroidManifest.xml
中注册Application
xml
<application
    android:name=".MyApplication"
    ... >

Path B: Manual Setup (No Gradle Plugin)

路径B:手动安装(不使用Gradle插件)

Use this if you can't use the Gradle plugin (e.g., non-standard build setups).
Step 1 — Add dependency in
app/build.gradle[.kts]
kotlin
dependencies {
    implementation(platform("io.sentry:sentry-bom:8.33.0"))
    implementation("io.sentry:sentry-android")
}
Step 2 — Initialize in Application class (same as Path A, Step 3)
Step 3 — Configure ProGuard/R8 manually
The Sentry SDK ships a ProGuard rules file automatically. For manual mapping upload, install
sentry-cli
and add to your CI:
bash
sentry-cli releases files "my-app@1.0.0+42" upload-proguard \
  --org YOUR_ORG --project YOUR_PROJECT \
  app/build/outputs/mapping/release/mapping.txt

如果你无法使用Gradle插件(比如非标准构建配置)可以使用此方案。
步骤1 — 在
app/build.gradle[.kts]
中添加依赖
kotlin
dependencies {
    implementation(platform("io.sentry:sentry-bom:8.33.0"))
    implementation("io.sentry:sentry-android")
}
步骤2 — 在Application类中初始化(和路径A步骤3完全一致)
步骤3 — 手动配置ProGuard/R8
Sentry SDK会自动附带ProGuard规则文件。如果需要手动上传映射文件,请安装
sentry-cli
并添加到你的CI流程中:
bash
sentry-cli releases files "my-app@1.0.0+42" upload-proguard \\
  --org YOUR_ORG --project YOUR_PROJECT \\
  app/build/outputs/mapping/release/mapping.txt

Quick Reference: Full-Featured
SentryAndroid.init()

快速参考:全功能
SentryAndroid.init()
配置

kotlin
SentryAndroid.init(this) { options ->
    options.dsn = "YOUR_SENTRY_DSN"

    // Environment and release
    options.environment = BuildConfig.BUILD_TYPE     // "debug", "release", etc.
    options.release = "${BuildConfig.APPLICATION_ID}@${BuildConfig.VERSION_NAME}+${BuildConfig.VERSION_CODE}"

    // Tracing — sample 100% in dev, lower to 10–20% in production
    options.tracesSampleRate = 1.0

    // Continuous UI profiling (recommended over transaction-based)
    options.profileSessionSampleRate = 1.0

    // Session Replay (API 26+; silent no-op on API 21–25)
    options.sessionReplay.sessionSampleRate = 0.1
    options.sessionReplay.onErrorSampleRate = 1.0
    options.sessionReplay.maskAllText = true         // mask text for privacy
    options.sessionReplay.maskAllImages = true       // mask images for privacy

    // Structured logging
    options.logs.isEnabled = true

    // Error enrichment
    options.isAttachScreenshot = true                // capture screenshot on error
    options.isAttachViewHierarchy = true             // attach view hierarchy JSON

    // ANR detection (5s default; watchdog + ApplicationExitInfo API 30+)
    options.isAnrEnabled = true

    // NDK native crash handling (enabled by default)
    options.isEnableNdk = true

    // Send PII: IP address, user data
    options.sendDefaultPii = true

    // Trace propagation (backend distributed tracing)
    options.tracePropagationTargets = listOf("api.yourapp.com", ".*\\.yourapp\\.com")

    // Verbose logging — disable in production
    options.isDebug = BuildConfig.DEBUG
}

kotlin
SentryAndroid.init(this) { options ->
    options.dsn = "YOUR_SENTRY_DSN"

    // 环境和版本标识
    options.environment = BuildConfig.BUILD_TYPE     // 如"debug", "release"等
    options.release = "${BuildConfig.APPLICATION_ID}@${BuildConfig.VERSION_NAME}+${BuildConfig.VERSION_CODE}"

    // 链路追踪 — 开发环境采样100%,生产环境建议调低到10–20%
    options.tracesSampleRate = 1.0

    // 持续UI性能剖析(比基于事务的剖析更推荐)
    options.profileSessionSampleRate = 1.0

    // 会话回放(仅API 26+支持;API 21–25会静默不生效)
    options.sessionReplay.sessionSampleRate = 0.1
    options.sessionReplay.onErrorSampleRate = 1.0
    options.sessionReplay.maskAllText = true         // 隐私保护:屏蔽所有文本
    options.sessionReplay.maskAllImages = true       // 隐私保护:屏蔽所有图片

    // 结构化日志
    options.logs.isEnabled = true

    // 错误信息增强
    options.isAttachScreenshot = true                // 异常时捕获截图
    options.isAttachViewHierarchy = true             // 附加视图层级JSON

    // ANR检测(默认5s超时;使用看门狗+API 30+的ApplicationExitInfo API)
    options.isAnrEnabled = true

    // NDK原生崩溃处理(默认启用)
    options.isEnableNdk = true

    // 发送PII信息:IP地址、用户数据
    options.sendDefaultPii = true

    // 链路传播(后端分布式追踪)
    options.tracePropagationTargets = listOf("api.yourapp.com", ".*\\\\.yourapp\\\\.com")

    // 详细日志 — 生产环境请禁用
    options.isDebug = BuildConfig.DEBUG
}

For Each Agreed Feature

针对每个确认开启的功能

Walk through features one at a time. Load the reference file for each, follow its steps, then verify before moving on:
FeatureReferenceLoad when...
Error Monitoring
${SKILL_ROOT}/references/error-monitoring.md
Always (baseline)
Tracing & Performance
${SKILL_ROOT}/references/tracing.md
Always for Android (Activity lifecycle, network)
Profiling
${SKILL_ROOT}/references/profiling.md
Performance-sensitive production apps
Session Replay
${SKILL_ROOT}/references/session-replay.md
User-facing apps (API 26+)
Logging
${SKILL_ROOT}/references/logging.md
Structured logging / log-to-trace correlation
Metrics
${SKILL_ROOT}/references/metrics.md
Custom metric tracking (Beta, SDK ≥ 8.30.0)
Crons
${SKILL_ROOT}/references/crons.md
Scheduled jobs, WorkManager check-ins
For each feature:
Read ${SKILL_ROOT}/references/<feature>.md
, follow steps exactly, verify it works.

逐个功能完成配置,加载对应参考文件,按步骤操作,验证通过后再进入下一个功能:
功能参考文件路径加载场景
错误监控
${SKILL_ROOT}/references/error-monitoring.md
所有场景必选(基础能力)
链路追踪与性能
${SKILL_ROOT}/references/tracing.md
Android项目必选(Activity生命周期、网络分析)
性能剖析
${SKILL_ROOT}/references/profiling.md
对性能敏感的生产应用
会话回放
${SKILL_ROOT}/references/session-replay.md
面向用户的应用(API 26+)
日志
${SKILL_ROOT}/references/logging.md
结构化日志/需要日志与链路关联的场景
指标
${SKILL_ROOT}/references/metrics.md
自定义指标追踪(Beta功能,SDK ≥ 8.30.0支持)
定时任务监控
${SKILL_ROOT}/references/crons.md
定时任务、WorkManager心跳检测场景
每个功能的操作流程:
读取${SKILL_ROOT}/references/<feature>.md
,严格按照步骤操作,验证生效后再继续。

Integration Reference

集成参考

Built-in (Auto-Enabled)

内置集成(自动启用)

These integrations activate automatically when
SentryAndroid.init()
is called:
IntegrationWhat it does
UncaughtExceptionHandlerIntegration
Captures all uncaught Java/Kotlin exceptions
AnrIntegration
ANR detection via watchdog thread (5s) + ApplicationExitInfo (API 30+)
NdkIntegration
Native (C/C++) crash capture via
sentry-native
ActivityLifecycleIntegration
Auto-instruments Activity create/resume/pause for TTID/TTFD
AppStartMetrics
Measures cold/warm/hot app start time
NetworkBreadcrumbsIntegration
Records connectivity changes as breadcrumbs
SystemEventsBreadcrumbsIntegration
Records battery, screen on/off, etc.
AppLifecycleIntegration
Records foreground/background transitions
UserInteractionIntegration
Breadcrumbs for taps, swipes, input events
CurrentActivityIntegration
Tracks active Activity for context
调用
SentryAndroid.init()
后这些集成会自动激活:
集成功能
UncaughtExceptionHandlerIntegration
捕获所有未捕获的Java/Kotlin异常
AnrIntegration
通过看门狗线程(5s超时)+ ApplicationExitInfo(API 30+)检测ANR
NdkIntegration
通过
sentry-native
捕获原生(C/C++)崩溃
ActivityLifecycleIntegration
自动插桩Activity的create/resume/pause生命周期,统计TTID/TTFD
AppStartMetrics
统计冷启动/温启动/热启动耗时
NetworkBreadcrumbsIntegration
记录网络连接变化作为用户行为面包屑
SystemEventsBreadcrumbsIntegration
记录电池、屏幕亮灭等系统事件作为面包屑
AppLifecycleIntegration
记录应用前后台切换事件
UserInteractionIntegration
记录点击、滑动、输入等用户交互作为面包屑
CurrentActivityIntegration
追踪当前活跃Activity作为上下文

Optional Integrations

可选集成

Add the artifact to your
dependencies {}
block (versions managed by BOM):
IntegrationArtifactWhen to add
Timber
io.sentry:sentry-android-timber
App uses Timber for logging
Fragment
io.sentry:sentry-android-fragment
App uses Jetpack Fragments (lifecycle tracing)
Compose
io.sentry:sentry-compose-android
App uses Jetpack Compose (navigation + masking)
Navigation
io.sentry:sentry-android-navigation
App uses Jetpack Navigation Component
OkHttp
io.sentry:sentry-okhttp
App uses OkHttp or Retrofit
Room/SQLite
io.sentry:sentry-android-sqlite
App uses Room or raw SQLite
Apollo 3
io.sentry:sentry-apollo-3
App uses Apollo GraphQL v3
Apollo 4
io.sentry:sentry-apollo-4
App uses Apollo GraphQL v4
Kotlin Extensions
io.sentry:sentry-kotlin-extensions
Kotlin coroutines context propagation
Ktor Client
io.sentry:sentry-ktor-client
App uses Ktor HTTP client
LaunchDarkly
io.sentry:sentry-launchdarkly-android
App uses LaunchDarkly feature flags
将对应的依赖添加到
dependencies {}
块(版本由BOM统一管理):
集成依赖坐标添加场景
Timber
io.sentry:sentry-android-timber
应用使用Timber做日志打印
Fragment
io.sentry:sentry-android-fragment
应用使用Jetpack Fragments(生命周期追踪)
Compose
io.sentry:sentry-compose-android
应用使用Jetpack Compose(导航+隐私屏蔽)
Navigation
io.sentry:sentry-android-navigation
应用使用Jetpack Navigation组件
OkHttp
io.sentry:sentry-okhttp
应用使用OkHttp或Retrofit
Room/SQLite
io.sentry:sentry-android-sqlite
应用使用Room或原生SQLite
Apollo 3
io.sentry:sentry-apollo-3
应用使用Apollo GraphQL v3
Apollo 4
io.sentry:sentry-apollo-4
应用使用Apollo GraphQL v4
Kotlin扩展
io.sentry:sentry-kotlin-extensions
Kotlin协程上下文传播
Ktor Client
io.sentry:sentry-ktor-client
应用使用Ktor HTTP客户端
LaunchDarkly
io.sentry:sentry-launchdarkly-android
应用使用LaunchDarkly feature flag

Gradle Plugin Bytecode Instrumentation

Gradle插件字节码插桩

The plugin can inject instrumentation automatically (no source changes):
FeatureInstrumentsEnable via
DATABASE
Room DAO, SupportSQLiteOpenHelper
tracingInstrumentation.features
FILE_IO
FileInputStream, FileOutputStream
tracingInstrumentation.features
OKHTTP
OkHttpClient.Builder automatically
tracingInstrumentation.features
COMPOSE
NavHostController auto-instrumentation
tracingInstrumentation.features
LOGCAT
android.util.Log
capturing
tracingInstrumentation.features

插件可以自动注入插桩逻辑(无需修改源码):
功能插桩对象启用方式
DATABASE
Room DAO、SupportSQLiteOpenHelper通过
tracingInstrumentation.features
配置
FILE_IO
FileInputStream、FileOutputStream通过
tracingInstrumentation.features
配置
OKHTTP
OkHttpClient.Builder自动插桩通过
tracingInstrumentation.features
配置
COMPOSE
NavHostController自动插桩通过
tracingInstrumentation.features
配置
LOGCAT
捕获
android.util.Log
输出
通过
tracingInstrumentation.features
配置

Configuration Reference

配置参考

Core
SentryOptions
(via
SentryAndroid.init
)

核心
SentryOptions
(通过
SentryAndroid.init
配置)

OptionTypeDefaultPurpose
dsn
String
Required. Project DSN; SDK silently disabled if empty
environment
String
e.g.,
"production"
,
"staging"
. Env:
SENTRY_ENVIRONMENT
release
String
App version, e.g.,
"my-app@1.0.0+42"
. Env:
SENTRY_RELEASE
dist
String
Build variant / distribution identifier
sendDefaultPii
Boolean
false
Include PII: IP address, user data
sampleRate
Double
1.0
Error event sampling (0.0–1.0)
maxBreadcrumbs
Int
100
Max breadcrumbs per event
isAttachStacktrace
Boolean
true
Auto-attach stack traces to message events
isAttachScreenshot
Boolean
false
Capture screenshot on error
isAttachViewHierarchy
Boolean
false
Attach JSON view hierarchy as attachment
isDebug
Boolean
false
Verbose SDK output. Never use in production
isEnabled
Boolean
true
Disable SDK entirely (e.g., for testing)
beforeSend
SentryOptions.BeforeSendCallback
Modify or drop error events before sending
beforeBreadcrumb
SentryOptions.BeforeBreadcrumbCallback
Filter breadcrumbs before storage
配置项类型默认值用途
dsn
String
必填。 项目DSN;为空时SDK会静默禁用
environment
String
环境标识,如
"production"
,
"staging"
。可读取环境变量
SENTRY_ENVIRONMENT
release
String
应用版本,如
"my-app@1.0.0+42"
。可读取环境变量
SENTRY_RELEASE
dist
String
构建变体/分发标识
sendDefaultPii
Boolean
false
是否包含PII信息:IP地址、用户数据
sampleRate
Double
1.0
错误事件采样率(0.0–1.0)
maxBreadcrumbs
Int
100
每个事件最多携带的面包屑数量
isAttachStacktrace
Boolean
true
自动为消息事件附加堆栈
isAttachScreenshot
Boolean
false
异常时捕获截图
isAttachViewHierarchy
Boolean
false
附加JSON格式的视图层级作为附件
isDebug
Boolean
false
SDK详细日志输出。生产环境绝对不要开启
isEnabled
Boolean
true
完全禁用SDK(比如测试场景)
beforeSend
SentryOptions.BeforeSendCallback
发送错误事件前修改或丢弃事件
beforeBreadcrumb
SentryOptions.BeforeBreadcrumbCallback
存储面包屑前过滤面包屑

Tracing Options

链路追踪配置

OptionTypeDefaultPurpose
tracesSampleRate
Double
0.0
Transaction sample rate (0–1). Use
1.0
in dev
tracesSampler
TracesSamplerCallback
Per-transaction sampling; overrides
tracesSampleRate
tracePropagationTargets
List<String>
[".*"]
Hosts/URLs to receive
sentry-trace
and
baggage
headers
isEnableAutoActivityLifecycleTracing
Boolean
true
Auto-instrument Activity lifecycle
isEnableTimeToFullDisplayTracing
Boolean
false
TTFD spans (requires
Sentry.reportFullyDisplayed()
)
isEnableUserInteractionTracing
Boolean
false
Auto-instrument user gestures as transactions
配置项类型默认值用途
tracesSampleRate
Double
0.0
事务采样率(0–1)。开发环境建议用
1.0
tracesSampler
TracesSamplerCallback
按事务维度自定义采样,优先级高于
tracesSampleRate
tracePropagationTargets
List<String>
[".*"]
需要接收
sentry-trace
baggage
头的主机/URL列表
isEnableAutoActivityLifecycleTracing
Boolean
true
自动插桩Activity生命周期
isEnableTimeToFullDisplayTracing
Boolean
false
TTFD span统计(需要主动调用
Sentry.reportFullyDisplayed()
isEnableUserInteractionTracing
Boolean
false
自动将用户手势作为事务统计

Profiling Options

性能剖析配置

OptionTypeDefaultPurpose
profileSessionSampleRate
Double
0.0
Continuous profiling sample rate (SDK ≥ 8.7.0, API 22+)
profilesSampleRate
Double
0.0
Legacy transaction profiling rate (mutually exclusive with continuous)
isProfilingStartOnAppStart
Boolean
false
Auto-start profiling session on app launch
配置项类型默认值用途
profileSessionSampleRate
Double
0.0
持续性能剖析采样率(SDK ≥ 8.7.0支持,API 22+)
profilesSampleRate
Double
0.0
旧版基于事务的剖析采样率(和持续剖析互斥)
isProfilingStartOnAppStart
Boolean
false
应用启动时自动开启剖析会话

ANR Options

ANR配置

OptionTypeDefaultPurpose
isAnrEnabled
Boolean
true
Enable ANR watchdog thread
anrTimeoutIntervalMillis
Long
5000
Milliseconds before reporting ANR
isAnrReportInDebug
Boolean
false
Report ANRs in debug builds (noisy in debugger)
配置项类型默认值用途
isAnrEnabled
Boolean
true
启用ANR看门狗线程
anrTimeoutIntervalMillis
Long
5000
ANR上报超时时间(毫秒)
isAnrReportInDebug
Boolean
false
debug构建下上报ANR(调试器暂停线程时会产生大量误报)

NDK Options

NDK配置

OptionTypeDefaultPurpose
isEnableNdk
Boolean
true
Enable native crash capture via sentry-native
isEnableScopeSync
Boolean
true
Sync Java scope (user, tags) to NDK layer
isEnableTombstoneFetchJob
Boolean
true
Fetch NDK tombstone files for enrichment
配置项类型默认值用途
isEnableNdk
Boolean
true
通过sentry-native启用原生崩溃捕获
isEnableScopeSync
Boolean
true
将Java层的scope(用户、标签)同步到NDK层
isEnableTombstoneFetchJob
Boolean
true
拉取NDK tombstone文件丰富崩溃信息

Session Replay Options (
options.sessionReplay
)

会话回放配置(
options.sessionReplay
下的属性)

OptionTypeDefaultPurpose
sessionSampleRate
Double
0.0
Fraction of all sessions to record
onErrorSampleRate
Double
0.0
Fraction of error sessions to record
maskAllText
Boolean
true
Mask all text in replays
maskAllImages
Boolean
true
Mask all images in replays
quality
SentryReplayQuality
MEDIUM
Video quality:
LOW
,
MEDIUM
,
HIGH
配置项类型默认值用途
sessionSampleRate
Double
0.0
全量会话录制比例
onErrorSampleRate
Double
0.0
异常会话录制比例
maskAllText
Boolean
true
屏蔽回放中的所有文本
maskAllImages
Boolean
true
屏蔽回放中的所有图片
quality
SentryReplayQuality
MEDIUM
视频质量:
LOW
MEDIUM
HIGH

Logging Options (
options.logs
)

日志配置(
options.logs
下的属性)

OptionTypeDefaultPurpose
isEnabled
Boolean
false
Enable
Sentry.logger()
API (SDK ≥ 8.12.0)
setBeforeSend
BeforeSendLogCallback
Filter/modify log entries before sending

配置项类型默认值用途
isEnabled
Boolean
false
启用
Sentry.logger()
API(SDK ≥ 8.12.0支持)
setBeforeSend
BeforeSendLogCallback
发送日志前过滤/修改日志内容

Environment Variables

环境变量

VariablePurposeNotes
SENTRY_DSN
Data Source NameSet in CI; SDK reads from environment at init
SENTRY_AUTH_TOKEN
Upload ProGuard mappings and source contextNever commit — use CI/CD secrets
SENTRY_ORG
Organization slugUsed by Gradle plugin
sentry.org
SENTRY_PROJECT
Project slugUsed by Gradle plugin
sentry.projectName
SENTRY_RELEASE
Release identifierFalls back from
options.release
SENTRY_ENVIRONMENT
Environment nameFalls back from
options.environment
You can also configure DSN and many options via
AndroidManifest.xml
meta-data:
xml
<application>
    <meta-data android:name="io.sentry.dsn" android:value="YOUR_DSN" />
    <meta-data android:name="io.sentry.traces-sample-rate" android:value="1.0" />
    <meta-data android:name="io.sentry.environment" android:value="production" />
    <meta-data android:name="io.sentry.anr.enable" android:value="true" />
    <meta-data android:name="io.sentry.attach-screenshot" android:value="true" />
    <meta-data android:name="io.sentry.attach-view-hierarchy" android:value="true" />
</application>
⚠️ Manifest meta-data is a convenient alternative but does not support the full option set. For complex configuration (session replay, profiling, hooks), use
SentryAndroid.init()
.

变量名用途备注
SENTRY_DSN
数据源名称在CI中设置;SDK初始化时会从环境变量读取
SENTRY_AUTH_TOKEN
上传ProGuard映射和源码上下文的凭证绝对不要提交到代码仓库 — 存放在CI/CD密钥管理中
SENTRY_ORG
组织slug供Gradle插件的
sentry.org
配置读取
SENTRY_PROJECT
项目slug供Gradle插件的
sentry.projectName
配置读取
SENTRY_RELEASE
版本标识优先级低于
options.release
SENTRY_ENVIRONMENT
环境标识优先级低于
options.environment
你也可以通过
AndroidManifest.xml
的meta-data配置DSN和很多其他选项:
xml
<application>
    <meta-data android:name="io.sentry.dsn" android:value="YOUR_DSN" />
    <meta-data android:name="io.sentry.traces-sample-rate" android:value="1.0" />
    <meta-data android:name="io.sentry.environment" android:value="production" />
    <meta-data android:name="io.sentry.anr.enable" android:value="true" />
    <meta-data android:name="io.sentry.attach-screenshot" android:value="true" />
    <meta-data android:name="io.sentry.attach-view-hierarchy" android:value="true" />
</application>
⚠️ Manifest meta-data是很方便的配置方式,但不支持全量配置项。复杂配置(会话回放、性能剖析、钩子函数)请使用
SentryAndroid.init()

Verification

验证

After setup, verify Sentry is receiving events:
Test error capture:
kotlin
// In an Activity or Fragment
try {
    throw RuntimeException("Sentry Android SDK test")
} catch (e: Exception) {
    Sentry.captureException(e)
}
Test tracing:
kotlin
val transaction = Sentry.startTransaction("test-task", "task")
val span = transaction.startChild("test-span", "description")
span.finish()
transaction.finish()
Test structured logging (SDK ≥ 8.12.0):
kotlin
Sentry.logger().info("Sentry logging test")
Sentry.logger().error("Error log test", Exception("test error"))
Check the Sentry dashboard:
  • Issues → your test exception should appear within seconds
  • Traces → look for
    test-task
    transaction with child span
  • Replays → session recording visible after app interaction (requires API 26+)
  • Logs → structured log entries visible under Logs tab
If nothing appears:
  1. Set
    options.isDebug = true
    — SDK logs to Logcat
  2. Verify DSN is correct and matches your Sentry project
  3. Check that your
    Application
    class is registered in
    AndroidManifest.xml
    as
    android:name
  4. Confirm the device/emulator has internet connectivity
  5. For NDK crashes, ensure
    isEnableNdk = true
    (default) and build with NDK support

配置完成后,请验证Sentry是否正常接收事件:
测试错误捕获:
kotlin
// 在Activity或Fragment中运行
try {
    throw RuntimeException("Sentry Android SDK test")
} catch (e: Exception) {
    Sentry.captureException(e)
}
测试链路追踪:
kotlin
val transaction = Sentry.startTransaction("test-task", "task")
val span = transaction.startChild("test-span", "description")
span.finish()
transaction.finish()
测试结构化日志(SDK ≥ 8.12.0支持):
kotlin
Sentry.logger().info("Sentry logging test")
Sentry.logger().error("Error log test", Exception("test error"))
检查Sentry控制台:
  • Issues → 几秒内应该可以看到你测试的异常
  • Traces → 可以找到带有子span的
    test-task
    事务
  • Replays → 应用交互后可以看到会话录制(需要API 26+)
  • Logs → 结构化日志会展示在Logs标签页下
如果没有收到任何数据:
  1. 设置
    options.isDebug = true
    — SDK会向Logcat输出日志
  2. 确认DSN正确且和你的Sentry项目匹配
  3. 检查你的
    Application
    类已经在
    AndroidManifest.xml
    中通过
    android:name
    注册
  4. 确认设备/模拟器有网络连接
  5. 针对NDK崩溃,确认
    isEnableNdk = true
    (默认开启)且项目配置了NDK支持

Phase 4: Cross-Link

阶段4:跨端关联

After completing Android setup, check for a backend or web frontend missing Sentry coverage:
bash
undefined
完成Android端配置后,检查是否有未配置Sentry的后端或Web前端项目:
bash
undefined

Adjacent backend directories

相邻后端目录

ls ../backend ../server ../api 2>/dev/null cat ../go.mod 2>/dev/null | head -3 cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -5 cat ../Gemfile 2>/dev/null | head -3 ls ../backend/package.json ../server/package.json 2>/dev/null
ls ../backend ../server ../api 2>/dev/null cat ../go.mod 2>/dev/null | head -3 cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -5 cat ../Gemfile 2>/dev/null | head -3 ls ../backend/package.json ../server/package.json 2>/dev/null

iOS counterpart app

对应的iOS应用

ls ../ios ../YourApp-iOS 2>/dev/null find .. -maxdepth 3 -name "*.xcodeproj" 2>/dev/null | head -3

If a backend or related platform exists without Sentry, suggest the matching skill:

| Detected | Suggest skill |
|----------|--------------|
| Go backend (`go.mod`) | `sentry-go-sdk` |
| Python backend (`requirements.txt`, `pyproject.toml`) | `sentry-python-sdk` |
| Ruby backend (`Gemfile`) | `sentry-ruby-sdk` |
| Node.js backend | `@sentry/node` — see [docs.sentry.io/platforms/javascript/guides/express/](https://docs.sentry.io/platforms/javascript/guides/express/) |
| iOS app (`.xcodeproj`) | `sentry-cocoa-sdk` |
| React Native (`package.json` with `react-native`) | `sentry-react-native-sdk` |
| React / Next.js web | `sentry-react-sdk` or `sentry-nextjs-sdk` |

**Distributed tracing setup** — if the backend skill is added, configure `tracePropagationTargets` in Android to propagate trace context to your API:

```kotlin
options.tracePropagationTargets = listOf(
    "api.yourapp.com",
    ".*\\.yourapp\\.com"
)
This links mobile transactions to backend traces in the Sentry waterfall view.

ls ../ios ../YourApp-iOS 2>/dev/null find .. -maxdepth 3 -name "*.xcodeproj" 2>/dev/null | head -3

如果存在未配置Sentry的后端或关联平台,推荐使用对应的技能:

| 检测到的项目 | 推荐技能 |
|----------|--------------|
| Go后端(`go.mod`) | `sentry-go-sdk` |
| Python后端(`requirements.txt`、`pyproject.toml`) | `sentry-python-sdk` |
| Ruby后端(`Gemfile`) | `sentry-ruby-sdk` |
| Node.js后端 | `@sentry/node` — 参考[docs.sentry.io/platforms/javascript/guides/express/](https://docs.sentry.io/platforms/javascript/guides/express/) |
| iOS应用(`.xcodeproj`) | `sentry-cocoa-sdk` |
| React Native(`package.json`包含`react-native`) | `sentry-react-native-sdk` |
| React / Next.js前端 | `sentry-react-sdk`或`sentry-nextjs-sdk` |

**分布式追踪配置** — 如果同时配置了后端技能,在Android端配置`tracePropagationTargets`将链路上下文传播到你的API:

```kotlin
options.tracePropagationTargets = listOf(
    "api.yourapp.com",
    ".*\\\\.yourapp\\\\.com"
)
这会将移动端事务和后端链路在Sentry的瀑布流视图中关联起来。

Troubleshooting

问题排查

IssueSolution
Events not appearing in SentrySet
isDebug = true
, check Logcat for SDK errors; verify DSN is correct and matches your project
SentryAndroid.init()
not called
Confirm
android:name=".MyApplication"
is set in
AndroidManifest.xml
; Application class not abstract
Gradle plugin not foundAdd the plugin to project-level
build.gradle.kts
first, then
apply false
; verify version
6.1.0
ProGuard mapping not uploadingSet
SENTRY_AUTH_TOKEN
env var; ensure
autoUploadProguardMapping = true
in
sentry {}
block
NDK crashes not capturedVerify
isEnableNdk = true
(default); ensure project has NDK configured in
android.ndkVersion
ANR reported in debuggerSet
isAnrReportInDebug = false
(default); ANR watchdog fires when debugger pauses threads
Session replay not recordingRequires API 26+; verify
sessionSampleRate > 0
or
onErrorSampleRate > 0
; check Logcat for replay errors
Session replay shows blank screenPixelCopy (default) requires hardware acceleration; try
SentryReplayOptions.screenshotQuality = CANVAS
Replay masking misalignedViews with
translationX/Y
or
clipToPadding=false
can offset masks; report to github.com/getsentry/sentry-java
beforeSend
not firing
beforeSend
only intercepts managed (Java/Kotlin) events; NDK native crashes bypass it
OkHttp spans not appearingAdd
SentryOkHttpInterceptor
to your
OkHttpClient
, or use Gradle plugin
OKHTTP
bytecode instrumentation
Spans not attached to transactionEnsure
TransactionOptions().setBindToScope(true)
when starting transaction; child spans look for scope root
Tracing not recordingVerify
tracesSampleRate > 0
; Activity instrumentation requires
isEnableAutoActivityLifecycleTracing = true
(default)
Continuous profiling not workingSDK ≥ 8.7.0 required; API 22+ required; set
profileSessionSampleRate > 0
; don't also set
profilesSampleRate
Both profiling modes set
profilesSampleRate
and
profileSessionSampleRate
are mutually exclusive — use only one
TTFD spans missingSet
isEnableTimeToFullDisplayTracing = true
and call
Sentry.reportFullyDisplayed()
when screen is ready
Kotlin coroutine scope lostAdd
sentry-kotlin-extensions
dependency; use
Sentry.cloneMainContext()
to propagate trace context
Release build stack traces unreadableProGuard mapping not uploaded; confirm Gradle plugin
autoUploadProguardMapping = true
and auth token set
Source context not showing in SentryEnable
includeSourceContext = true
in
sentry {}
block (Gradle plugin required)
BOM version conflictUse
implementation(platform("io.sentry:sentry-bom:8.33.0"))
and omit versions from all other
io.sentry:*
entries
SENTRY_AUTH_TOKEN
exposed
Auth token is build-time only — never pass it to
SentryAndroid.init()
or embed in the APK
问题解决方案
Sentry中看不到事件设置
isDebug = true
,检查Logcat中的SDK错误;确认DSN正确且和项目匹配
SentryAndroid.init()
未被调用
确认
AndroidManifest.xml
中配置了
android:name=".MyApplication"
;Application类不是抽象类
找不到Gradle插件先在项目级
build.gradle.kts
中添加插件并设置
apply false
;确认版本是
6.1.0
ProGuard映射未上传设置
SENTRY_AUTH_TOKEN
环境变量;确认
sentry {}
块中
autoUploadProguardMapping = true
捕获不到NDK崩溃确认
isEnableNdk = true
(默认开启);确认项目在
android.ndkVersion
中配置了NDK
调试器中上报ANR设置
isAnrReportInDebug = false
(默认值);调试器暂停线程时会触发ANR看门狗
会话回放不录制需要API 26+;确认
sessionSampleRate > 0
onErrorSampleRate > 0
;检查Logcat中的回放错误
会话回放显示黑屏PixelCopy(默认)需要硬件加速;尝试设置
SentryReplayOptions.screenshotQuality = CANVAS
回放屏蔽位置偏移带有
translationX/Y
clipToPadding=false
的视图会导致屏蔽位置偏移;可向github.com/getsentry/sentry-java反馈问题
beforeSend
不触发
beforeSend
仅拦截托管层(Java/Kotlin)事件;NDK原生崩溃会绕过该钩子
看不到OkHttp span
OkHttpClient
添加
SentryOkHttpInterceptor
,或者使用Gradle插件的
OKHTTP
字节码插桩
Span没有关联到事务启动事务时设置
TransactionOptions().setBindToScope(true)
;子span会查找scope中的根事务
链路追踪不生效确认
tracesSampleRate > 0
;Activity插桩需要
isEnableAutoActivityLifecycleTracing = true
(默认开启)
持续性能剖析不工作需要SDK ≥ 8.7.0;API ≥ 22;设置
profileSessionSampleRate > 0
;不要同时设置
profilesSampleRate
同时配置了两种剖析模式
profilesSampleRate
profileSessionSampleRate
互斥 — 仅使用其中一个
缺少TTFD span设置
isEnableTimeToFullDisplayTracing = true
,页面渲染完成后调用
Sentry.reportFullyDisplayed()
Kotlin协程scope丢失添加
sentry-kotlin-extensions
依赖;使用
Sentry.cloneMainContext()
传播链路上下文
Release构建堆栈不可读ProGuard映射未上传;确认Gradle插件中
autoUploadProguardMapping = true
且配置了auth token
Sentry中看不到源码上下文(需要Gradle插件)在
sentry {}
块中启用
includeSourceContext = true
BOM版本冲突使用
implementation(platform("io.sentry:sentry-bom:8.33.0"))
,其他所有
io.sentry:*
依赖不要指定版本
SENTRY_AUTH_TOKEN
泄露
Auth token仅构建时使用 — 绝对不要传递给
SentryAndroid.init()
或打包到APK中
",