Golang链路追踪:实现高效可靠的分布式系统监控_golang 链路追踪
package main
import (
"context"
"fmt"
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
"io"
"log"
)
func main() {
tracer, closer := NewJaegerTracer("your-service-name", "localhost:6831")
defer closer.Close()
span := tracer.StartSpan("some-operation")
defer span.Finish()
// 将Span设置为当前Span
ctx := opentracing.ContextWithSpan(context.Background(), span)
err := DoOperation(ctx)
if err != nil {
span.LogFields(opentracing.LogTags{
opentracing.Error: err,
})
}
}
// NewJaegerTracer 创建一个新的Jaeger tracer
func NewJaegerTracer(service string, addr string) (opentracing.Tracer, io.Closer) {
cfg := &jaeger.Configuration{
ServiceName: service,
Sampler: &jaeger.SamplerConfig{
Type: jaeger.SamplerTypeConst,
Param: 1,
},
Reporter: &jaeger.ReporterConfig{
LogSpans: true,
LocalAgentHostPort: addr,
},
}
tracer, closer, err := cfg.NewTracer(jaeger.Logger(jaeger.StdLogger))
if err != nil {
log.Fatal("Cannot init Jaeger: ", err)
}
return tracer, closer
}
// DoOperation 执行一些操作,并追踪这个过程
func DoOperation(ctx context.Context) error {
span, ok := opentracing.SpanFromContext(ctx)
if !ok {
span = opentracing.StartSpan("DoOperation")
defer span.Finish()
}
// 执行操作...
fmt.Println("Operation is done")
return nil
}
这个简单的例子展示了如何在Go程序中使用Jaeger来创建和管理链路追踪。它首先配置了一个新的Jaeger tracer,然后开始一个新的span,并将其设置为当前span。接着,它执行了一个模拟的操作,并将操作包裹在span的上下文中。如果操作失败,它会在span的日志中记录错误。最后,代码展示了如何优雅地关闭tracer。
评论已关闭