我有 2 个异步(非 HTTP)作业在不同的进程中运行。我想使用我自己生成的 TraceID 和 SpanID 来处理所有使用 OpenTelemetry 库的 GO 跟踪和跨度。 (我使用 Signoz 进行可视化,但这并不重要)。
1.) 如何为根跨度设置 TraceID 和 SpanID 2.) 如何设置 spanID 并将其指向我在 (1) 中创建的 TraceId 的自定义根范围
下面是 (2),但我发现缺少痕迹。 `
b3 := []byte("9cec1f9bb461a96e023efebc879da11c")
copy(ptid[:], b3)
b4 := []byte("3fc56ecf2453bda8")
var parentSpanCtx = trace.NewSpanContext(trace.SpanContextConfig{
TraceID: ptid,
SpanID: trace.SpanID(b4),
TraceFlags: trace.FlagsSampled,
Remote: true,
})`
var parentCtx = trace.ContextWithSpanContext(context.Background(), parentsc)
ctx, span := tracer.Start(parentCtx, stage.Name)
我尝试使用正确的 Parent TraceID 和 SpanId 设置 childSpans 的 SpanContext,但它不起作用。它显示为根缺少跨度。
这是一个同时回答(1)和(2)的示例
package main
import (
"context"
"fmt"
"log"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
)
func main() {
// Create a trace provider with a custom exporter (e.g., stdout exporter for testing)
exporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint())
if err != nil {
log.Fatalf("Error creating exporter: %v", err)
}
resources, err := resource.New(
context.Background(),
resource.WithAttributes(
attribute.String("service.name", "serviceName"),
attribute.String("library.language", "go"),
),
)
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exporter),
sdktrace.WithResource(resources),
)
otel.SetTracerProvider(tp)
// Manually create a custom TraceID and SpanID for the root span
traceID := trace.TraceID([16]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10})
spanID := trace.SpanID([8]byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77})
ctx := trace.ContextWithRemoteSpanContext(
context.Background(),
trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
TraceFlags: trace.FlagsSampled,
}),
)
// Create and start the root span with the custom TraceID and SpanID
tracer := otel.GetTracerProvider().Tracer("my-tracer")
_, rootSpan := tracer.Start(ctx, "root-span")
defer rootSpan.End()
// Your code here
fmt.Println("Hello from root span!")
createChildSpan(ctx)
time.Sleep(10*time.Second)
}
// In another part of your code or a different process, you can create child spans
// referencing the custom root span created in step 1.
func createChildSpan(ctx context.Context) {
tracer := otel.GetTracerProvider().Tracer("my-tracer")
_, childSpan := tracer.Start(ctx, "child-span")
defer childSpan.End()
// Your code here
fmt.Println("Hello from child span!")
}