如果您使用了apm包并遇到了SetCustom函数引发的随机恐慌,请尝试使用以下代码修复它:
import (
"go.elastic.co/apm"
"go.elastic.co/apm/module/apmgrpc"
)
func init() {
// 假如要收集HTTP请求头,则使用下面代码
// fmt.Println("Init apm...")
tr := apm.DefaultTracer
tr.RegisterSpanNameFormatter(apm.NewStackTraceNamer())
tr.RegisterSpanFilter(apm.SpanFilterFunc(func(ctx context.Context, span *apm.Span) bool {
select {
case <-ctx.Done():
return true
default:
}
return span.Sampled()
}))
apmgrpc.Register(tr)
if !tr.Active() {
halfLife := 8 * time.Second
go func() {
for range time.Tick(halfLife / 2) {
if tr.Active() {
break
}
fmt.Println("Attempting APM tracer initialization...")
tr.InitDefaultTracer()
time.Sleep(halfLife / 2)
}
}()
}
// 这里设置您的SetCustom方法
}
从上面的代码段中,可以看到我们在apm包的init函数中注册了一个apm的Tracer实例,并且使用了apmgrpc.Register将跨进程调用也加入了配置。此外,我们使用了SetCustom方法完成自定义监控参数的设定。在这个例子中,我们在SetCustom之前定义了一个具有良好配置的tracer实例,这可能是导致随机恐慌的原因之一。我们的解决方案通过默认启用一个不带采样的trcer来’dilute'SetCustom函数的调用,从而最终达到减少任意恐慌事件的效果。