mcpField
S
sentry-cocoa-sdk

sentry-cocoa-sdk

github.com/getsentry开发26330 次安装35 周前更新
代码仓库

关于 sentry-cocoa-sdk

为 Apple 平台应用接入 Sentry Cocoa 提供配置指导,面向在 Swift 或 Objective-C 项目中设置监控的开发者。内容涵盖项目检测、功能选择、安装、配置与验证。

主要功能

  1. 01Apple 项目检查步骤
  2. 02Sentry 功能选择指导
  3. 03Wizard、SPM 与 CocoaPods 安装
  4. 04SwiftUI 和 UIKit 初始化指导
  5. 05配置与验证参考

适用场景

  1. 01为 iOS 应用接入 Sentry
  2. 02配置崩溃与卡顿监控
  3. 03设置追踪或性能分析
  4. 04验证 Sentry 事件是否送达

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/getsentry/sentry-agent-skills --skill sentry-cocoa-sdk

安装后在 Claude Code 中输入/sentry-cocoa-sdk确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
error-monitoring.md
logging.md
profiling.md
session-replay.md
tracing.md
user-feedback.md

详细介绍

Sentry Cocoa SDK

一款带有明确主张的向导,可扫描你的 Apple 项目并引导你完成完整的 Sentry 设置。

在以下情况调用此技能

  • 用户要求为 iOS/macOS/tvOS“添加 Sentry”,或在某个 Apple 应用中“设置 Sentry”
  • 用户希望在 Swift/ObjC 中实现错误监控、追踪、性能分析、会话重放或日志记录
  • 用户提到 sentry-cocoa、SentrySDK 或 Apple/iOS Sentry SDK
  • 用户希望监控崩溃、应用卡顿、看门狗终止或性能

注意: 下文中的 SDK 版本和 API 反映的是撰写本文时的 Sentry 文档(sentry-cocoa 9.5.1)。 在实施前,请务必对照 docs.sentry.io/platforms/apple/ 进行核实。


阶段 1:检测

运行以下命令,在提出任何建议之前先了解该项目:

# Check existing Sentry dependency
grep -i sentry Package.swift Podfile Cartfile 2>/dev/null

# Detect UI framework (SwiftUI vs UIKit)
grep -rE "@main|struct.*App.*:.*App" --include="*.swift" . 2>/dev/null | head -5
grep -rE "AppDelegate|UIApplicationMain" --include="*.swift" . 2>/dev/null | head -5

# Detect platform and deployment targets
grep -E "platforms:|\.iOS|\.macOS|\.tvOS|\.watchOS|\.visionOS" Package.swift 2>/dev/null
grep -E "platform :ios|platform :osx|platform :tvos|platform :watchos" Podfile 2>/dev/null

# Detect logging
grep -rE "import OSLog|os\.log|CocoaLumberjack|DDLog" --include="*.swift" . 2>/dev/null | head -5

# Detect companion backend
ls ../backend ../server ../api 2>/dev/null
ls ../go.mod ../requirements.txt ../Gemfile ../package.json 2>/dev/null

需要注意的事项:

  • sentry-cocoa 是否已在 Package.swift 或 Podfile 中?如果是,跳到阶段 2(配置功能)。
  • 是 SwiftUI(@main App 结构体)还是 UIKit(AppDelegate)?这决定初始化模式。
  • 涉及哪些 Apple 平台?(影响可用功能——参见平台支持矩阵。)
  • 是否已有日志库?(可启用结构化日志捕获。)
  • 是否有配套后端?(会触发阶段 4 的交叉关联,用于分布式追踪。)

阶段 2:推荐

根据你的发现,给出具体建议。不要问开放式问题——先提出方案:

推荐(核心覆盖):

  • ✅ 错误监控 — 始终启用;崩溃上报、应用卡顿、看门狗终止、NSError/Swift 错误
  • ✅ 追踪 — 对应用始终启用;自动埋点应用启动、网络、UIViewController、文件 I/O、Core Data
  • ✅ 性能分析 — 生产应用;以极低开销进行持续性能分析

可选(增强可观测性):

  • ⚡ 会话重放 — 面向用户的应用;⚠️ 在 iOS 26+ 上默认禁用(Liquid Glass 渲染)
  • ⚡ 日志记录 — 在需要结构化日志捕获时
  • ⚡ 用户反馈 — 希望从用户处收集崩溃/错误反馈表单的应用

Cocoa 不可用:

  • ❌ 指标 — 改用自定义 span
  • ❌ 定时任务 — 仅限后端
  • ❌ AI 监控 — 仅限 JS/Python

推荐逻辑:

功能在以下情况推荐……
错误监控始终 — 不可协商的基线
追踪对应用始终启用 — 开箱即用的丰富自动埋点
性能分析性能至关重要的生产应用
会话重放仅 iOS 面向用户的应用(注意 iOS 26+ 的警告;不适用于 tvOS/macOS/watchOS/visionOS)
日志记录已有 os.log / CocoaLumberjack 用法,或需要结构化日志
用户反馈希望提供带截图的应用内缺陷报告的应用

建议:“我推荐错误监控 + 追踪 + 性能分析。要不要我再帮你加上会话重放和日志记录?”


阶段 3:引导

安装

方案 1 — Sentry 向导(推荐): 以交互方式引导你完成登录、组织/项目选择以及认证令牌设置。随后安装 SDK、更新 AppDelegate、添加 dSYM/调试符号上传构建阶段,并自动配置一切。

brew install getsentry/tools/sentry-wizard && sentry-wizard -i ios

方案 2 — Swift Package Manager: File → Add Packages → 输入:

https://github.com/getsentry/sentry-cocoa.git

或在 Package.swift 中:

.package(url: "https://github.com/getsentry/sentry-cocoa", from: "9.5.1"),

SPM 产品 — 每个 target 只能选择其中一个:

产品使用场景
Sentry推荐 — 静态框架,应用启动快
Sentry-Dynamic动态框架替代方案
SentrySwiftUISwiftUI 视图性能追踪(SentryTracedView)
Sentry-WithoutUIKitOrAppKitwatchOS、应用扩展、命令行工具

⚠️ Xcode 允许选择多个产品——只能选一个。

方案 3 — CocoaPods:

platform :ios, '11.0'
use_frameworks!

target 'YourApp' do
  pod 'Sentry', :git => 'https://github.com/getsentry/sentry-cocoa.git', :tag => '9.5.1'
end

已知问题(Xcode 14+): 沙盒 rsync.samba 错误 → Target Settings → “Enable User Script Sandbox” → NO。


快速入门 — 推荐初始化方式

启用大多数功能,并采用合理的默认值。在应用启动时,先于其他代码添加。

SwiftUI — 应用入口:

import SwiftUI
import Sentry

@main
struct MyApp: App {
    init() {
        SentrySDK.start { options in
            options.dsn = ProcessInfo.processInfo.environment["SENTRY_DSN"]
                ?? "https://[email protected]/0"
            options.environment = ProcessInfo.processInfo.environment["SENTRY_ENVIRONMENT"]
            options.releaseName = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String

            // Error monitoring (on by default — explicit for clarity)
            options.enableCrashHandler = true
            options.enableAppHangTrackingV2 = true
            options.enableWatchdogTerminationTracking = true
            options.attachScreenshot = true
            options.attachViewHierarchy = true
            options.sendDefaultPii = true

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

            // Profiling (SDK 9.0.0+ API)
            options.configureProfiling = {
                $0.sessionSampleRate = 1.0
                $0.lifecycle = .trace
            }

            // Session Replay (disabled on iOS 26+ by default — safe to configure)
            options.sessionReplay.sessionSampleRate = 1.0
            options.sessionReplay.onErrorSampleRate = 1.0

            // Logging (SDK 9.0.0+ top-level; use options.experimental.enableLogs in 8.x)
            options.enableLogs = true
        }
    }

    var body: some Scene {
        WindowGroup { ContentView() }
    }
}

UIKit — AppDelegate:

import UIKit
import Sentry

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        SentrySDK.start { options in
            options.dsn = ProcessInfo.processInfo.environment["SENTRY_DSN"]
                ?? "https://[email protected]/0"
            options.environment = ProcessInfo.processInfo.environment["SENTRY_ENVIRONMENT"]
            options.releaseName = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String

            options.enableCrashHandler = true
            options.enableAppHangTrackingV2 = true
            options.enableWatchdogTerminationTracking = true
            options.attachScreenshot = true
            options.attachViewHierarchy = true
            options.sendDefaultPii = true

            options.tracesSampleRate = 1.0

            options.configureProfiling = {
                $0.sessionSampleRate = 1.0
                $0.lifecycle = .trace
            }

            options.sessionReplay.sessionSampleRate = 1.0
            options.sessionReplay.onErrorSampleRate = 1.0

            // Logging (SDK 9.0.0+ top-level; use options.experimental.enableLogs in 8.x)
            options.enableLogs = true
        }
        return true
    }
}

⚠️ SDK 必须在主线程上初始化。


针对每项商定的功能

逐项配置功能。为每项功能加载对应的参考文件,按步骤操作,并在继续下一项之前进行验证:

功能参考文件在以下情况下加载……
错误监控${SKILL_ROOT}/references/error-monitoring.md始终加载(基线功能)
链路追踪${SKILL_ROOT}/references/tracing.md应用启动、网络、UIViewController 性能监控
性能分析${SKILL_ROOT}/references/profiling.md对性能敏感的生产应用
会话回放${SKILL_ROOT}/references/session-replay.md面向用户的 iOS/tvOS 应用
日志记录${SKILL_ROOT}/references/logging.md需要采集结构化日志
用户反馈${SKILL_ROOT}/references/user-feedback.md需要在应用内报告 Bug

对于每项功能:Read ${SKILL_ROOT}/references/<feature>.md,严格按照步骤操作,并验证其是否正常工作。


配置参考

关键 SentryOptions 字段
选项类型默认值用途
dsnString""为空时禁用 SDK;读取 SENTRY_DSN 环境变量
environmentString""例如:"production";读取 SENTRY_ENVIRONMENT
releaseNameString""例如:"[email protected]";读取 SENTRY_RELEASE
debugBoolfalseSDK 详细输出 — 在生产环境中禁用
sendDefaultPiiBoolfalse包含 IP 和活动集成中的用户信息
enableCrashHandlerBooltrue崩溃报告总开关
enableAppHangTrackingV2Booltrue (9.0+)区分完全阻塞和非完全阻塞的卡顿
appHangTimeoutIntervalDouble2.0判定为卡顿前等待的秒数
enableWatchdogTerminationTrackingBooltrue跟踪看门狗终止(iOS、tvOS、Mac Catalyst)
attachScreenshotBoolfalse出错时捕获屏幕截图
attachViewHierarchyBoolfalse出错时捕获视图层级结构
tracesSampleRateNSNumber?nil事务采样率(nil = 禁用链路追踪);Swift 会自动将 Double 字面量装箱(例如,1.0 → NSNumber)
tracesSamplerClosurenil按事务动态采样(优先于采样率)
enableAutoPerformanceTracingBooltrue自动检测的总开关
tracePropagationTargets[String][".*"]接收分布式追踪标头的主机/正则表达式
enableCaptureFailedRequestsBooltrue自动将 HTTP 5xx 错误捕获为事件
enableNetworkBreadcrumbsBooltrue为传出的 HTTP 请求添加面包屑
inAppInclude[String][]作为“应用内”代码处理的模块前缀
maxBreadcrumbsInt100每个事件的面包屑数量上限
sampleRateFloat1.0错误事件采样率
beforeSendClosurenil用于修改或丢弃错误事件的钩子
onCrashedLastRunClosurenil崩溃后在下次启动时调用
环境变量
变量映射到用途
SENTRY_DSNdsn数据源名称
SENTRY_RELEASEreleaseName应用版本(例如,[email protected])
SENTRY_ENVIRONMENTenvironment部署环境
平台功能支持矩阵
功能iOStvOSmacOSwatchOSvisionOS
崩溃报告✅✅✅✅✅
应用卡顿 V2✅✅❌❌❌
看门狗终止✅✅❌❌❌
应用启动跟踪✅✅❌❌✅
UIViewController 跟踪✅✅❌❌✅
SwiftUI 跟踪✅✅✅❌✅
网络跟踪✅✅✅❌✅
性能分析✅✅✅❌✅
会话回放✅❌❌❌❌
MetricKit✅(15+)❌✅(12+)❌❌

验证

测试 Sentry 是否正在接收事件:

// Trigger a test error event:
SentrySDK.capture(message: "Sentry Cocoa SDK test")

// Or test crash reporting (without debugger — crashes are intercepted by debugger):
// SentrySDK.crash()  // uncomment, run without debugger, relaunch to see crash report

几秒钟内检查 Sentry 控制面板。如果没有任何内容显示:

  1. 设置 options.debug = true——在 Xcode 控制台中打印 SDK 内部信息
  2. 确认 DSN 正确且项目存在
  3. 确保在主线程上进行初始化

生产环境设置

降低生产环境的采样率,以控制数据量和成本:

options.tracesSampleRate = 0.2          // 20% of transactions

options.configureProfiling = {
    $0.sessionSampleRate = 0.1          // 10% of sessions
    $0.lifecycle = .trace
}

options.sessionReplay.sessionSampleRate = 0.1   // 10% continuous
options.sessionReplay.onErrorSampleRate = 1.0   // 100% on error (keep high)

options.debug = false                   // never in production

第 4 阶段:交叉关联

完成 Apple 设置后,检查是否有配套后端尚未接入 Sentry:

# Detect companion backend
ls ../backend ../server ../api 2>/dev/null
cat ../go.mod 2>/dev/null | head -5
cat ../requirements.txt ../Pipfile 2>/dev/null | head -5
cat ../Gemfile 2>/dev/null | head -5
cat ../package.json 2>/dev/null | grep -E '"name"|"dependencies"' | head -5

如果发现后端,请配置 tracePropagationTargets 以启用端到端的分布式跟踪,并推荐匹配的技能:

检测到的后端推荐技能跟踪标头支持
Go(go.mod)sentry-go-sdk✅ 自动
Python(requirements.txt)sentry-python-sdk✅ 自动
Ruby(Gemfile)sentry-ruby-sdk✅ 自动
Node.js 后端(package.json)sentry-node-sdk(或 sentry-express-sdk)✅ 自动

故障排除

问题解决方案
未显示事件设置 debug: true,验证 DSN 格式,确保在主线程上初始化
未捕获崩溃在未连接调试器的情况下运行——调试器会拦截信号
未报告应用卡顿连接调试器时会自动禁用;检查 appHangTimeoutInterval
会话回放未录制检查 iOS 版本——在 iOS 26+(Liquid Glass)上默认禁用;确认 sessionSampleRate > 0
缺少跟踪数据确认 tracesSampleRate > 0;检查 enableAutoPerformanceTracing = true
缺少性能分析数据确认 configureProfiling 中的 sessionSampleRate > 0;对于 .trace 生命周期,必须启用跟踪
rsync.samba 构建错误(CocoaPods)Target Settings → “Enable User Script Sandbox” → NO
选择了多个 SPM 产品仅选择一个:Sentry、Sentry-Dynamic、SentrySwiftUI、Sentry-WithoutUIKitOrAppKit
inAppExclude 编译错误已在 SDK 9.0.0 中移除——仅使用 inAppInclude
未跟踪看门狗终止需要 enableCrashHandler = true(默认已启用)
缺少网络面包屑需要 enableSwizzling = true(默认已启用)
profilesSampleRate 编译错误已在 SDK 9.0.0 中移除——改用 configureProfiling 闭包

评论

支持 Markdown