sentry-go-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAll Skills > SDK Setup > Go SDK
所有技能 > SDK配置 > Go SDK
Sentry Go SDK
Sentry Go SDK
Opinionated wizard that scans your Go project and guides you through complete Sentry setup.
这是一个指导性工具,会扫描你的Go项目并引导你完成完整的Sentry配置流程。
Invoke This Skill When
何时调用此技能
- User asks to "add Sentry to Go" or "setup Sentry" in a Go app
- User wants error monitoring, tracing, logging, metrics, or crons in Go
- User mentions ,
sentry-go, or Go Sentry SDKgithub.com/getsentry/sentry-go - User wants to monitor panics, HTTP handlers, or scheduled jobs in Go
Note: SDK versions and APIs below reflect Sentry docs at time of writing (sentry-go v0.43.0). Always verify against docs.sentry.io/platforms/go/ before implementing.
- 用户要求「为Go添加Sentry」或在Go应用中「配置Sentry」
- 用户希望在Go中实现错误监控、链路追踪、日志、指标或定时任务功能
- 用户提及、
sentry-go或Go Sentry SDKgithub.com/getsentry/sentry-go - 用户希望监控Go中的恐慌、HTTP处理器或定时任务
注意: 以下SDK版本和API基于编写时的Sentry文档(sentry-go v0.43.0)。 实施前请务必对照docs.sentry.io/platforms/go/进行验证。
Phase 1: Detect
阶段1:检测
Run these commands to understand the project before making any recommendations:
bash
undefined在给出任何建议前,先运行以下命令了解项目情况:
bash
undefinedCheck existing Sentry dependency
检查已有的Sentry依赖
grep -i sentry go.mod 2>/dev/null
grep -i sentry go.mod 2>/dev/null
Detect web framework
检测Web框架
grep -E "gin-gonic/gin|labstack/echo|gofiber/fiber|valyala/fasthttp|kataras/iris|urfave/negroni" go.mod 2>/dev/null
grep -E "gin-gonic/gin|labstack/echo|gofiber/fiber|valyala/fasthttp|kataras/iris|urfave/negroni" go.mod 2>/dev/null
Detect logging libraries
检测日志库
grep -E "sirupsen/logrus|go.uber.org/zap|rs/zerolog|log/slog" go.mod go.sum 2>/dev/null
grep -E "sirupsen/logrus|go.uber.org/zap|rs/zerolog|log/slog" go.mod go.sum 2>/dev/null
Detect cron / scheduler patterns
检测定时任务/调度器模式
grep -E "robfig/cron|go-co-op/gocron|jasonlvhit/gocron" go.mod 2>/dev/null
grep -E "robfig/cron|go-co-op/gocron|jasonlvhit/gocron" go.mod 2>/dev/null
Detect OpenTelemetry usage
检测OpenTelemetry使用情况
grep "go.opentelemetry.io" go.mod 2>/dev/null
grep "go.opentelemetry.io" go.mod 2>/dev/null
Check for companion frontend
检查是否存在配套前端
ls frontend/ web/ client/ ui/ 2>/dev/null
**What to note:**
- Is `sentry-go` already in `go.mod`? If yes, skip to Phase 2 (configure features).
- Which framework is used? (Determines which sub-package and middleware to install.)
- Which logging library? (Enables automatic log capture.)
- Are cron/scheduler patterns present? (Triggers Crons recommendation.)
- Is there a companion frontend directory? (Triggers Phase 4 cross-link.)
---ls frontend/ web/ client/ ui/ 2>/dev/null
**需要注意的点:**
- `sentry-go`是否已在`go.mod`中?如果是,直接跳至阶段2(配置功能)。
- 使用了哪种框架?(决定要安装的子包和中间件。)
- 使用了哪种日志库?(可启用自动日志捕获。)
- 是否存在定时任务/调度器模式?(触发定时任务功能推荐。)
- 是否存在配套前端目录?(触发阶段4的跨链路建议。)
---Phase 2: Recommend
阶段2:推荐
Based on what you found, present a concrete recommendation. Don't ask open-ended questions — lead with a proposal:
Recommended (core coverage):
- ✅ Error Monitoring — always; captures panics and unhandled errors
- ✅ Tracing — if HTTP handlers, gRPC, or DB calls are detected
- ✅ Logging — if logrus, zap, zerolog, or slog is detected
Optional (enhanced observability):
- ⚡ Metrics — custom counters and gauges for business KPIs / SLOs
- ⚡ Crons — detect silent failures in scheduled jobs
- ⚠️ Profiling — removed in sentry-go v0.31.0; see for alternatives
references/profiling.md
Recommendation logic:
| Feature | Recommend when... |
|---|---|
| Error Monitoring | Always — non-negotiable baseline |
| Tracing | |
| Logging | logrus, zap, zerolog, or |
| Metrics | Business events, SLO tracking, or counters needed |
| Crons | |
| Profiling | ⚠️ Removed in v0.31.0 — do not recommend; see |
Propose: "I recommend setting up Error Monitoring + Tracing [+ Logging if applicable]. Want me to also add Metrics or Crons?"
根据检测结果,给出具体建议。不要提出开放式问题,直接给出方案:
推荐(核心覆盖):
- ✅ 错误监控 — 必选;捕获恐慌和未处理错误
- ✅ 链路追踪 — 若检测到HTTP处理器、gRPC或数据库调用
- ✅ 日志集成 — 若检测到logrus、zap、zerolog或slog
可选(增强可观测性):
- ⚡ 指标监控 — 为业务关键指标/KPI/SLO设置自定义计数器和仪表盘
- ⚡ 定时任务监控 — 检测定时任务的静默失败
- ⚠️ 性能分析 — 在sentry-go v0.31.0中已移除;可查看获取替代方案
references/profiling.md
推荐逻辑:
| 功能 | 推荐场景 |
|---|---|
| 错误监控 | 始终推荐 — 不可缺少的基础功能 |
| 链路追踪 | 检测到 |
| 日志集成 | 检测到logrus、zap、zerolog或 |
| 指标监控 | 需要跟踪业务事件、SLO或计数器时 |
| 定时任务监控 | 检测到 |
| 性能分析 | ⚠️ v0.31.0中已移除 — 不推荐;请查看 |
建议话术:"我建议配置错误监控 + 链路追踪 [+ 日志集成(若适用)]。需要我同时添加指标监控或定时任务监控吗?"
Phase 3: Guide
阶段3:引导
Install
安装
bash
undefinedbash
undefinedCore SDK (always required)
核心SDK(始终需要)
go get github.com/getsentry/sentry-go
go get github.com/getsentry/sentry-go
Framework sub-package — install only what matches detected framework:
框架子包 — 仅安装与检测到的框架匹配的包:
go get github.com/getsentry/sentry-go/http # net/http
go get github.com/getsentry/sentry-go/gin # Gin
go get github.com/getsentry/sentry-go/echo # Echo
go get github.com/getsentry/sentry-go/fiber # Fiber
go get github.com/getsentry/sentry-go/fasthttp # FastHTTP
go get github.com/getsentry/sentry-go/http # net/http
go get github.com/getsentry/sentry-go/gin # Gin
go get github.com/getsentry/sentry-go/echo # Echo
go get github.com/getsentry/sentry-go/fiber # Fiber
go get github.com/getsentry/sentry-go/fasthttp # FastHTTP
Logging sub-packages — install only what matches detected logging lib:
日志子包 — 仅安装与检测到的日志库匹配的包:
go get github.com/getsentry/sentry-go/logrus # Logrus
go get github.com/getsentry/sentry-go/slog # slog (stdlib, Go 1.21+)
go get github.com/getsentry/sentry-go/zap # Zap
go get github.com/getsentry/sentry-go/zerolog # Zerolog
go get github.com/getsentry/sentry-go/logrus # Logrus
go get github.com/getsentry/sentry-go/slog # slog(标准库,Go 1.21+)
go get github.com/getsentry/sentry-go/zap # Zap
go get github.com/getsentry/sentry-go/zerolog # Zerolog
OpenTelemetry bridge (only if OTel is already in use):
OpenTelemetry桥接(仅当已使用OTel时):
go get github.com/getsentry/sentry-go/otel
undefinedgo get github.com/getsentry/sentry-go/otel
undefinedQuick Start — Recommended Init
快速开始 — 推荐初始化方式
Add to before any other code. This config enables the most features with sensible defaults:
main()go
import (
"log"
"os"
"time"
"github.com/getsentry/sentry-go"
)
err := sentry.Init(sentry.ClientOptions{
Dsn: os.Getenv("SENTRY_DSN"),
Environment: os.Getenv("SENTRY_ENVIRONMENT"), // "production", "staging", etc.
Release: release, // inject via -ldflags at build time
SendDefaultPII: true,
AttachStacktrace: true,
// Tracing (adjust sample rate for production)
EnableTracing: true,
TracesSampleRate: 1.0, // lower to 0.1–0.2 in high-traffic production
// Logs
EnableLogs: true,
})
if err != nil {
log.Fatalf("sentry.Init: %s", err)
}
defer sentry.Flush(2 * time.Second)Injecting at build time (recommended):
Releasego
var release string // set by -ldflags
// go build -ldflags="-X main.release=my-app@$(git describe --tags)"在其他代码之前添加到函数中。此配置启用了大部分功能并设置了合理的默认值:
main()go
import (
"log"
"os"
"time"
"github.com/getsentry/sentry-go"
)
err := sentry.Init(sentry.ClientOptions{
Dsn: os.Getenv("SENTRY_DSN"),
Environment: os.Getenv("SENTRY_ENVIRONMENT"), // "production"、"staging"等
Release: release, // 构建时通过-ldflags注入
SendDefaultPII: true,
AttachStacktrace: true,
// 链路追踪(生产环境调整采样率)
EnableTracing: true,
TracesSampleRate: 1.0, // 高流量生产环境可降低至0.1–0.2
// 日志
EnableLogs: true,
})
if err != nil {
log.Fatalf("sentry.Init: %s", err)
}
defer sentry.Flush(2 * time.Second)构建时注入(推荐):
Releasego
var release string // 通过-ldflags设置
// go build -ldflags="-X main.release=my-app@$(git describe --tags)"Framework Middleware
框架中间件
After , register the Sentry middleware for your framework:
sentry.Init| Framework | Import path | Middleware call | | |
|---|---|---|---|---|
| | | | |
| Gin | | | | |
| Echo | | | | |
| Fiber | | | | |
| FastHTTP | | | | |
| Iris | | | | |
| Negroni | | | | |
Note: Fiber and FastHTTP are built onwhich has no built-in recovery. Usevalyala/fasthttpfor those.Repanic: false, WaitForDelivery: true
Hub access in handlers:
go
// net/http, Negroni:
hub := sentry.GetHubFromContext(r.Context())
// Gin:
hub := sentrygin.GetHubFromContext(c)
// Echo:
hub := sentryecho.GetHubFromContext(c)
// Fiber:
hub := sentryfiber.GetHubFromContext(c)在之后,为你的框架注册Sentry中间件:
sentry.Init| 框架 | 导入路径 | 中间件调用 | | |
|---|---|---|---|---|
| | | | |
| Gin | | | | |
| Echo | | | | |
| Fiber | | | | |
| FastHTTP | | | | |
| Iris | | | | |
| Negroni | | | | |
注意: Fiber和FastHTTP基于构建,该库没有内置恢复机制。对于这些框架,请使用valyala/fasthttp配置。Repanic: false, WaitForDelivery: true
处理器中的Hub访问:
go
// net/http、Negroni:
hub := sentry.GetHubFromContext(r.Context())
// Gin:
hub := sentrygin.GetHubFromContext(c)
// Echo:
hub := sentryecho.GetHubFromContext(c)
// Fiber:
hub := sentryfiber.GetHubFromContext(c)For Each Agreed Feature
针对每个确认的功能
Walk through features one at a time. Load the reference file for each, follow its steps, and verify before moving to the next:
| Feature | Reference file | Load when... |
|---|---|---|
| Error Monitoring | | Always (baseline) |
| Tracing | | HTTP handlers / distributed tracing |
| Profiling | | Performance-sensitive production apps |
| Logging | | logrus / zap / zerolog / slog detected |
| Metrics | | Business KPIs / SLO tracking |
| Crons | | Scheduler / cron job patterns detected |
For each feature: , follow steps exactly, verify it works.
Read ${SKILL_ROOT}/references/<feature>.md逐一完成功能配置。加载每个功能的参考文件,按照步骤操作,并在进行下一步前验证功能正常:
| 功能 | 参考文件 | 加载场景 |
|---|---|---|
| 错误监控 | | 始终加载(基础功能) |
| 链路追踪 | | HTTP处理器/分布式追踪场景 |
| 性能分析 | | 对性能敏感的生产环境应用 |
| 日志集成 | | 检测到logrus/zap/zerolog/slog时 |
| 指标监控 | | 业务KPI/SLO追踪场景 |
| 定时任务监控 | | 检测到调度器/定时任务模式时 |
对于每个功能:读取,严格按照步骤操作,验证功能正常。
${SKILL_ROOT}/references/<feature>.mdConfiguration Reference
配置参考
Key ClientOptions
Fields
ClientOptions关键ClientOptions
字段
ClientOptions| Option | Type | Default | Purpose |
|---|---|---|---|
| | | SDK disabled if empty; env: |
| | | e.g., |
| | | e.g., |
| | | Include IP, request headers |
| | | Stack traces on |
| | | Error event sample rate (0.0 treated as 1.0) |
| | | Enable performance tracing |
| | | Transaction sample rate |
| | | Custom per-transaction sampling (overrides rate) |
| | | Enable Sentry Logs feature |
| | | Max breadcrumbs per event |
| | | Max depth for unwrapping error chains |
| | | Verbose SDK debug output |
| | | Hook to mutate/drop error events |
| | | Hook to mutate/drop transaction events |
| | | Regex patterns for errors to drop |
| | | Regex patterns for transactions to drop |
| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 若为空则SDK禁用;环境变量: |
| | | 例如 |
| | | 例如 |
| | | 包含IP、请求头等个人身份信息 |
| | | 为 |
| | | 错误事件采样率(0.0视为1.0) |
| | | 启用性能链路追踪 |
| | | 事务采样率 |
| | | 自定义事务采样逻辑(覆盖采样率) |
| | | 启用Sentry日志功能 |
| | | 每个事件的最大面包屑数量 |
| | | 错误链的最大展开深度 |
| | | 启用SDK详细调试输出 |
| | | 用于修改/丢弃错误事件的钩子函数 |
| | | 用于修改/丢弃事务事件的钩子函数 |
| | | 要丢弃的错误的正则表达式模式 |
| | | 要丢弃的事务的正则表达式模式 |
Environment Variables
环境变量
| Variable | Maps to | Purpose |
|---|---|---|
| | Data Source Name |
| | App version (e.g., |
| | Deployment environment |
| | Outbound proxy |
Options set in override environment variables.
ClientOptions| 变量 | 对应配置项 | 用途 |
|---|---|---|
| | 数据源名称 |
| | 应用版本(例如 |
| | 部署环境 |
| | 出站代理 |
ClientOptionsVerification
验证
Test that Sentry is receiving events:
go
// In a handler or test — triggers a real error event:
sentry.CaptureMessage("Sentry Go SDK test")
// Or trigger a captured panic (with recovery middleware in place):
panic("sentry test panic")Check the Sentry dashboard within a few seconds. If nothing appears:
- Set in
Debug: true— prints SDK internals to stdoutClientOptions - Verify the DSN is correct and the project exists
- Ensure is called (events are async by default)
sentry.Flush(2 * time.Second)
测试Sentry是否接收到事件:
go
// 在处理器或测试代码中 — 触发真实错误事件:
sentry.CaptureMessage("Sentry Go SDK test")
// 或者触发一个被捕获的恐慌(需已配置恢复中间件):
panic("sentry test panic")几秒内查看Sentry控制台。如果没有事件出现:
- 在中设置
ClientOptions— 将SDK内部信息打印到标准输出Debug: true - 验证DSN是否正确,项目是否存在
- 确保调用了(事件默认是异步发送的)
sentry.Flush(2 * time.Second)
Phase 4: Cross-Link
阶段4:跨链路建议
After completing Go setup, check for a companion frontend missing Sentry coverage:
bash
ls frontend/ web/ client/ ui/ 2>/dev/null
cat frontend/package.json web/package.json 2>/dev/null | grep -E '"react"|"svelte"|"vue"|"next"'If a frontend directory exists without Sentry configured, suggest the matching skill:
| Frontend detected | Suggest skill |
|---|---|
| React / Next.js | |
| Svelte / SvelteKit | |
| Vue | Use |
| Other JS/TS | |
完成Go端配置后,检查是否存在未配置Sentry的配套前端:
bash
ls frontend/ web/ client/ ui/ 2>/dev/null
cat frontend/package.json web/package.json 2>/dev/null | grep -E '"react"|"svelte"|"vue"|"next"'如果存在前端目录但未配置Sentry,建议使用匹配的技能:
| 检测到的前端 | 建议技能 |
|---|---|
| React / Next.js | |
| Svelte / SvelteKit | |
| Vue | 使用 |
| 其他JS/TS框架 | |
Troubleshooting
故障排除
| Issue | Solution |
|---|---|
| Events not appearing | Set |
| Malformed DSN — check format: |
| Panics not captured | Ensure framework middleware is registered before handlers |
| |
| Missing stack traces | Set |
| Goroutine events missing context | Clone hub before spawning goroutine: |
| Too many transactions | Lower |
| Fiber/FastHTTP not recovering | Use |
| |
| 问题 | 解决方案 |
|---|---|
| 事件未出现 | 设置 |
| DSN格式错误 — 检查格式: |
| 恐慌未被捕获 | 确保框架中间件在处理器之前注册 |
| |
| 缺少堆栈跟踪 | 为 |
| Goroutine事件缺少上下文 | 在启动goroutine前克隆hub: |
| 事务数量过多 | 降低 |
| Fiber/FastHTTP未恢复 | 对于基于fasthttp的框架,使用 |
| |