在 Go 中,如何追踪哪个导入导致了变量初始化时发生的错误?

In Go, how to track down which import is causing an error which occurs upon variable initialization?

我正在尝试 运行 存储库的 main() 函数,但 运行 陷入变量初始化时发生的棘手恐慌:

> go run main.go
go: finding github.com/myorg/some-repo/emulator latest
go: finding github.com/myorg/some-repo latest
panic: duplicate metrics collector registration attempted

goroutine 1 [running]:
github.com/prometheus/client_golang/prometheus.(*Registry).MustRegister(0xc0002a09b0, 0xc00033a1d0, 0x1, 0x1)
    /Users/kurt/go/pkg/mod/github.com/prometheus/client_golang@v1.5.1/prometheus/registry.go:400 +0xad
github.com/prometheus/client_golang/prometheus/promauto.Factory.NewGaugeVec(0x1acee40, 0xc0002a09b0, 0x0, 0x0, 0x0, 0x0, 0x19ade0e, 0x21, 0x19c60fa, 0x56, ...)
    /Users/kurt/go/pkg/mod/github.com/prometheus/client_golang@v1.5.1/prometheus/promauto/auto.go:306 +0x118
github.com/prometheus/client_golang/prometheus/promauto.NewGaugeVec(0x0, 0x0, 0x0, 0x0, 0x19ade0e, 0x21, 0x19c60fa, 0x56, 0x0, 0xc000370160, ...)
    /Users/kurt/go/pkg/mod/github.com/prometheus/client_golang@v1.5.1/prometheus/promauto/auto.go:197 +0xa9
github.com/myorg/some-library/pubsub.init.ializers()
    /Users/kurt/go/pkg/mod/github.com/myorg/some-library@v0.0.0-20200404213659-0e93c264015a/pubsub/gcp.go:30 +0xcd
exit status 2

错误归结为这行代码:

var inFlightMetric     = promauto.NewGauge(prometheus.GaugeOpts{Name: "gcp_pubsub_handlers_running_count"})

我认为问题在于,同一个库也有一个 pubsub/v2/gcp.go 同一行,所以程序试图同时导入 github.com/myorg/some-library/pubsubgithub.com/myorg/some-library/pubsub/v2 运行 陷入由 Prometheus 指标收集器中的 'name collision' 引起的恐慌。

我想做的是找到哪个依赖项正在导入 github.com/myorg/some-library/pubsub 并将其替换为 pubsub/v2 以避免此名称冲突。但是,我无法弄清楚如何从这个堆栈跟踪中确定它。关于如何实现这一点有什么想法吗?

我最终通过在库模块中创建一个分支 avoid-registering-duplicate-metrics-collector 并从该分支导入它来解决这个问题:

go get github.com/myorg/some-lib@avoid-registering-duplicate-metrics-collector

在该分支中,我为 pubsub 包中注册的所有指标附加了一个 _v1 后缀,以避免与 pusub/v2 的名称冲突。虽然这有点 hack,但需要定期将 master 分支合并到该分支以使其保持最新。找出导入中哪个文件实际上试图导入 pubsub 包的方法仍然有用。