英文:
APM Tracing with Datadog in Go
问题
我在Go中使用MongoDB作为数据存储构建了一个演示的REST API,使用Gin作为HTTP框架。我按照Datadog网站上的所有说明进行了操作,但是追踪结果中几乎没有任何信息。追踪结果只有http.request
。在Datadog博客上有一张Go追踪的截图(见下图)。
这是我看到的情况 - 请求中没有追踪到执行的MongoDB查询。
是否还有其他配置或手动报告需要进行?
我在主函数中使用以下代码初始化Datadog追踪器:
rules := []tracer.SamplingRule{tracer.RateRule(1)}
tracer.Start(
tracer.WithSamplingRules(rules),
tracer.WithService("Go Mongo"),
tracer.WithEnv("dev"),
)
defer tracer.Stop()
完整的代码可在以下链接找到:https://github.com/NG235/go-mongo
谢谢。
英文:
I have built a demo REST API in Go with MongoDB as the datastore, with Gin as the HTTP framework. I have followed all of the instructions on the Datadog website, however, am getting traces with little to no information. All that is traced is http.request
. On the Datadog blog there is a screenshot with a Go trace (see below).
Here is what I'm seeing - there is no trace of the MongoDB Query performed in the request.
Is there some other configuration or manual reporting that I have to do?
I am initiating the Datadog tracer with the following in my main function:
rules := []tracer.SamplingRule{tracer.RateRule(1)}
tracer.Start(
tracer.WithSamplingRules(rules),
tracer.WithService("Go Mongo"),
tracer.WithEnv("dev"),
)
defer tracer.Stop()
Full code is available at: https://github.com/NG235/go-mongo
Thanks.
答案1
得分: 4
首先,在你的所有处理程序中,你需要使用 request.Context()
:
ctx := c.Request.Context()
除了其他原因外,该上下文包含当前的追踪跨度 ID,这是连接跨度的最佳选项。
使用该上下文,你可以按照官方文档中描述的方式对代码的部分进行仪器化:
newCtx, span := otel.Tracer(name).Start(ctx, "Run")
defer span.End()
最后一部分是对使用的 MongoDB 等库进行仪器化。
import (
"go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/mongo/otelmongo"
)
func Connect() *mongo.Database {
opts := options.Client()
opts.Monitor = otelmongo.NewMonitor()
opts.ApplyURI("mongodb://root:root@localhost:27017")
client, err := mongo.Connect(context.Background(), opts)
现在,每个 MongoDB 操作都被追踪,并且如果你将 request.Context
传递到该操作中,它将与父跨度连接起来。
英文:
Foremost, in all your handlers you need to use request.Context()
:
ctx := c.Request.Context()
Besides other reasons, that context contains current tracing span ID, and it is the best option to connect spans together.
Using that context you can instrument sections of your code as described in official documentation:
newCtx, span := otel.Tracer(name).Start(ctx, "Run")
defer span.End()
Last piece is instrumentation for used libraries like MongoDB.
import (
"go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/mongo/otelmongo"
)
func Connect() *mongo.Database {
opts := options.Client()
opts.Monitor = otelmongo.NewMonitor()
opts.ApplyURI("mongodb://root:root@localhost:27017")
client, err := mongo.Connect(context.Background(), opts)
Now every MongoDB operation is traced, and it is connected to parent span if you propagate request.Context
into that operation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论