OpenTelemetry-2.Go接入Jaeger(grpc,gin-http)
package main
import (
"context"
"log"
"net/http"
"os"
"go.opentelemetry.io/otel"
"go.opentelemetry.�r.io/otel/exporters/jaeger"
"go.opentelemetry.io/otel/propagation"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc/credentials/insecure"
"github.com/gin-gonic/gin"
"google.golang.org/grpc"
)
func initTracer(service string) {
// 创建Jaeger tracer
exp, err := jaeger.New(jaeger.WithCollectorEndpoint(
jaeger.WithEndpoint("http://localhost:14268/api/traces"),
))
if err != nil {
log.Fatal(err)
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp),
sdktrace.WithSampler(sdktrace.AlwaysSample()),
)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{},
propagation.Baggage{},
))
// 设置TracerProvider为全局
otel.SetTracerProvider(tp)
}
func setupGinRouter() *gin.Engine {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
_, span := otel.Tracer("server-tracer").Start(context.Background(), "helloHandler")
defer span.End()
c.JSON(http.StatusOK, gin.H{"message": "Hello!"})
})
return r
}
func setupGRPCServer() {
// 假设有一个gRPC服务器
// 在gRPC服务中使用OpenTelemetry
}
func main() {
initTracer("my-service")
go func() {
setupGRPCServer()
}()
r := setupGinRouter()
// 监听并服务HTTP请求
if err := r.Run(":8080"); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}
这个示例代码展示了如何在Go应用程序中初始化OpenTelemetry,并将其用于gRPC和Gin HTTP服务的请求跟踪。它创建了一个新的Jaeger tracer,并将其设置为全局TracerProvider。在gRPC服务器和Gin HTTP服务器中,它创建了新的span来跟踪请求处理。这个例子是简化的,但它展示了如何将OpenTelemetry集成到实际的应用程序中。
评论已关闭