sentry-go-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

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
    ,
    github.com/getsentry/sentry-go
    , or Go Sentry SDK
  • 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"或"配置Sentry"
  • 用户希望在Go中实现错误监控、链路追踪、日志采集、指标统计或定时任务监控
  • 用户提到
    sentry-go
    github.com/getsentry/sentry-go
    或Go Sentry SDK
  • 用户希望监控Go中的恐慌(panic)、HTTP处理器或定时任务
注意: 以下SDK版本和API基于编写时的Sentry文档(sentry-go v0.43.0)。 实施前请务必对照Sentry官方文档进行验证。

Phase 1: Detect

阶段1:项目检测

Run these commands to understand the project before making any recommendations:
bash
undefined
在给出任何建议前,先运行以下命令了解项目情况:
bash
undefined

Check 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
    references/profiling.md
    for alternatives
Recommendation logic:
FeatureRecommend when...
Error MonitoringAlways — non-negotiable baseline
Tracing
net/http
, gin, echo, fiber, or gRPC imports detected
Logginglogrus, zap, zerolog, or
log/slog
imports detected
MetricsBusiness events, SLO tracking, or counters needed
Crons
robfig/cron
,
gocron
, or scheduled job patterns detected
Profiling⚠️ Removed in v0.31.0 — do not recommend; see
references/profiling.md
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
    获取替代方案
推荐逻辑:
功能推荐场景
错误监控始终推荐 — 不可缺少的基础配置
链路追踪检测到
net/http
、gin、echo、fiber或gRPC导入
日志采集检测到logrus、zap、zerolog或
log/slog
导入
指标统计需要追踪业务事件、SLO或计数器时
定时任务监控检测到
robfig/cron
gocron
或定时任务模式
性能剖析⚠️ v0.31.0中已移除 — 不推荐;请查看
references/profiling.md
建议话术:"我推荐配置错误监控 + 链路追踪 [+ 日志采集(如果适用)]。需要我同时添加指标统计或定时任务监控吗?"

Phase 3: Guide

阶段3:配置指导

Install

安装SDK

bash
undefined
bash
undefined

Core 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
undefined
go get github.com/getsentry/sentry-go/otel
undefined

Quick Start — Recommended Init

快速开始 — 推荐初始化配置

Add to
main()
before any other code. This config enables the most features with sensible defaults:
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
Release
at build time (recommended):
go
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)
构建时注入
Release
(推荐):
go
var release string // 通过-ldflags设置

// go build -ldflags="-X main.release=my-app@$(git describe --tags)"

Framework Middleware

框架中间件配置

After
sentry.Init
, register the Sentry middleware for your framework:
FrameworkImport pathMiddleware call
Repanic
WaitForDelivery
net/http
.../sentry-go/http
sentryhttp.New(opts).Handle(h)
true
false
Gin
.../sentry-go/gin
router.Use(sentrygin.New(opts))
true
false
Echo
.../sentry-go/echo
e.Use(sentryecho.New(opts))
true
false
Fiber
.../sentry-go/fiber
app.Use(sentryfiber.New(opts))
false
true
FastHTTP
.../sentry-go/fasthttp
sentryfasthttp.New(opts).Handle(h)
false
true
Iris
.../sentry-go/iris
app.Use(sentryiris.New(opts))
true
false
Negroni
.../sentry-go/negroni
n.Use(sentrynegroni.New(opts))
true
false
Note: Fiber and FastHTTP are built on
valyala/fasthttp
which has no built-in recovery. Use
Repanic: false, WaitForDelivery: true
for those.
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.Init
后,为你的框架注册Sentry中间件:
框架导入路径中间件调用
Repanic
WaitForDelivery
net/http
.../sentry-go/http
sentryhttp.New(opts).Handle(h)
true
false
Gin
.../sentry-go/gin
router.Use(sentrygin.New(opts))
true
false
Echo
.../sentry-go/echo
e.Use(sentryecho.New(opts))
true
false
Fiber
.../sentry-go/fiber
app.Use(sentryfiber.New(opts))
false
true
FastHTTP
.../sentry-go/fasthttp
sentryfasthttp.New(opts).Handle(h)
false
true
Iris
.../sentry-go/iris
app.Use(sentryiris.New(opts))
true
false
Negroni
.../sentry-go/negroni
n.Use(sentrynegroni.New(opts))
true
false
注意: 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:
FeatureReference fileLoad when...
Error Monitoring
${SKILL_ROOT}/references/error-monitoring.md
Always (baseline)
Tracing
${SKILL_ROOT}/references/tracing.md
HTTP handlers / distributed tracing
Profiling
${SKILL_ROOT}/references/profiling.md
Performance-sensitive production apps
Logging
${SKILL_ROOT}/references/logging.md
logrus / zap / zerolog / slog detected
Metrics
${SKILL_ROOT}/references/metrics.md
Business KPIs / SLO tracking
Crons
${SKILL_ROOT}/references/crons.md
Scheduler / cron job patterns detected
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
HTTP处理器/分布式追踪场景
性能剖析
${SKILL_ROOT}/references/profiling.md
对性能敏感的生产环境应用
日志采集
${SKILL_ROOT}/references/logging.md
检测到logrus/zap/zerolog/slog时
指标统计
${SKILL_ROOT}/references/metrics.md
业务KPI/SLO追踪场景
定时任务监控
${SKILL_ROOT}/references/crons.md
检测到调度器/定时任务模式时
对于每个功能:读取
${SKILL_ROOT}/references/<feature>.md
,严格按照步骤操作,验证功能正常运行后再进行下一步。

Configuration Reference

配置参考

Key
ClientOptions
Fields

关键
ClientOptions
字段

OptionTypeDefaultPurpose
Dsn
string
""
SDK disabled if empty; env:
SENTRY_DSN
Environment
string
""
e.g.,
"production"
; env:
SENTRY_ENVIRONMENT
Release
string
""
e.g.,
"my-app@1.0.0"
; env:
SENTRY_RELEASE
SendDefaultPII
bool
false
Include IP, request headers
AttachStacktrace
bool
false
Stack traces on
CaptureMessage
calls
SampleRate
float64
1.0
Error event sample rate (0.0 treated as 1.0)
EnableTracing
bool
false
Enable performance tracing
TracesSampleRate
float64
0.0
Transaction sample rate
TracesSampler
TracesSampler
nil
Custom per-transaction sampling (overrides rate)
EnableLogs
bool
false
Enable Sentry Logs feature
MaxBreadcrumbs
int
100
Max breadcrumbs per event
MaxErrorDepth
int
100
Max depth for unwrapping error chains
Debug
bool
false
Verbose SDK debug output
BeforeSend
func
nil
Hook to mutate/drop error events
BeforeSendTransaction
func
nil
Hook to mutate/drop transaction events
IgnoreErrors
[]string
nil
Regex patterns for errors to drop
IgnoreTransactions
[]string
nil
Regex patterns for transactions to drop
选项类型默认值用途
Dsn
string
""
为空时SDK禁用;环境变量:
SENTRY_DSN
Environment
string
""
例如
"production"
;环境变量:
SENTRY_ENVIRONMENT
Release
string
""
例如
"my-app@1.0.0"
;环境变量:
SENTRY_RELEASE
SendDefaultPII
bool
false
是否包含IP、请求头等个人可识别信息
AttachStacktrace
bool
false
调用
CaptureMessage
时是否附加堆栈跟踪
SampleRate
float64
1.0
错误事件采样率(0.0视为1.0)
EnableTracing
bool
false
是否启用性能追踪
TracesSampleRate
float64
0.0
事务采样率
TracesSampler
TracesSampler
nil
自定义事务采样逻辑(覆盖采样率)
EnableLogs
bool
false
是否启用Sentry日志功能
MaxBreadcrumbs
int
100
每个事件允许的最大面包屑(Breadcrumbs)数量
MaxErrorDepth
int
100
错误链的最大展开深度
Debug
bool
false
是否启用SDK详细调试输出
BeforeSend
func
nil
错误事件发送前的钩子函数,可修改或丢弃事件
BeforeSendTransaction
func
nil
事务事件发送前的钩子函数,可修改或丢弃事件
IgnoreErrors
[]string
nil
需要忽略的错误的正则表达式模式
IgnoreTransactions
[]string
nil
需要忽略的事务的正则表达式模式

Environment Variables

环境变量

VariableMaps toPurpose
SENTRY_DSN
Dsn
Data Source Name
SENTRY_RELEASE
Release
App version (e.g.,
my-app@1.0.0
)
SENTRY_ENVIRONMENT
Environment
Deployment environment
HTTP_PROXY
/
HTTPS_PROXY
HTTPProxy
/
HTTPSProxy
Outbound proxy
Options set in
ClientOptions
override environment variables.

变量名对应配置项用途
SENTRY_DSN
Dsn
数据源名称
SENTRY_RELEASE
Release
应用版本(例如
my-app@1.0.0
SENTRY_ENVIRONMENT
Environment
部署环境
HTTP_PROXY
/
HTTPS_PROXY
HTTPProxy
/
HTTPSProxy
出站代理
ClientOptions
中设置的选项优先级高于环境变量。

Verification

验证配置

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:
  1. Set
    Debug: true
    in
    ClientOptions
    — prints SDK internals to stdout
  2. Verify the DSN is correct and the project exists
  3. Ensure
    sentry.Flush(2 * time.Second)
    is called (events are async by default)

测试Sentry是否能接收事件:
go
// 在处理器或测试代码中 — 触发一个真实的错误事件:
sentry.CaptureMessage("Sentry Go SDK test")

// 或者触发一个被捕获的恐慌(需已配置恢复中间件):
panic("sentry test panic")
几秒内查看Sentry控制台。如果没有收到事件:
  1. ClientOptions
    中设置
    Debug: true
    — 将SDK内部信息输出到标准输出
  2. 验证DSN是否正确,且项目存在
  3. 确保调用了
    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 detectedSuggest skill
React / Next.js
sentry-react-setup
Svelte / SvelteKit
sentry-svelte-sdk
VueUse
@sentry/vue
— see docs.sentry.io/platforms/javascript/guides/vue/
Other JS/TS
sentry-react-setup
(covers generic JS patterns)

完成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
sentry-react-setup
Svelte / SvelteKit
sentry-svelte-sdk
Vue使用
@sentry/vue
— 查看Sentry官方文档
其他JS/TS框架
sentry-react-setup
(覆盖通用JS场景)

Troubleshooting

故障排查

IssueSolution
Events not appearingSet
Debug: true
, check DSN, verify
sentry.Flush()
is called
sentry.Init
returns error
Malformed DSN — check format:
https://<key>@o<org>.ingest.sentry.io/<project>
Panics not capturedEnsure framework middleware is registered before handlers
defer sentry.Flush
not running
os.Exit()
skips
defer
— call
sentry.Flush()
explicitly before
os.Exit()
Missing stack tracesSet
AttachStacktrace: true
for
CaptureMessage
; works automatically for
CaptureException
Goroutine events missing contextClone hub before spawning goroutine:
hub := sentry.CurrentHub().Clone()
Too many transactionsLower
TracesSampleRate
or use
TracesSampler
to drop health checks / metrics endpoints
Fiber/FastHTTP not recoveringUse
Repanic: false, WaitForDelivery: true
for fasthttp-based frameworks
SampleRate: 0.0
sending all events
0.0
is treated as
1.0
; to drop all, set
Dsn: ""
instead
问题解决方案
事件未出现在控制台设置
Debug: true
,检查DSN是否正确,验证是否调用了
sentry.Flush()
sentry.Init
返回错误
DSN格式错误 — 检查格式:
https://<key>@o<org>.ingest.sentry.io/<project>
恐慌未被捕获�确保框架中间件在处理器之前注册
defer sentry.Flush
未执行
os.Exit()
会跳过
defer
语句 — 在
os.Exit()
前显式调用
sentry.Flush()
缺少堆栈跟踪调用
CaptureMessage
时设置
AttachStacktrace: true
CaptureException
会自动附加堆栈跟踪
Goroutine事件缺少上下文启动Goroutine前克隆Hub:
hub := sentry.CurrentHub().Clone()
事务数量过多降低
TracesSampleRate
或使用
TracesSampler
忽略健康检查/指标端点
Fiber/FastHTTP未恢复错误基于fasthttp的框架使用
Repanic: false, WaitForDelivery: true
配置
SampleRate: 0.0
仍发送所有事件
0.0
会被视为
1.0
;要禁用所有事件,需设置
Dsn: ""