2

OpenTelemetry 入门

 2 years ago
source link: https://forrestsu.github.io/posts/architecture/microservice/go-opentelemetry-tracing/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

OpenTelemetry 入门

2022年1月8日
| 字数 990

1 Preface

云原生微服务可观测性,OpenTelemetry 组件实践指南。

1.1 构造一个新的 span

import (
    "context"

    "go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/trace"
)

// WithSpan create span if sampled
func WithSpan(ctx context.Context, spanName string, key string, val interface{}) {
	if trace.SpanContextFromContext(ctx).IsSampled() {
		_, span := telemetry.Start(ctx, spanName)
		defer span.End()
		span.AddEvent("custom", trace.WithAttributes(
			attribute.Key(key).String(traces.DefaulMsgMarshaler(val)),
		))
        // 增加自定义 tags
        span.SetAttributes("自定义Key", "自定义Value")
        span.SetStatus(codes.Error, "timeout")
	}
}

1.2 在当前的 span 上追加 event

// AddEvent add event
func AddEvent(ctx context.Context, req interface{}, rsp interface{}) {
	if span := trace.SpanFromContext(ctx); span.SpanContext().IsSampled() {
		span.AddEvent("msg", trace.WithAttributes(
			attribute.Key("req").String(traces.DefaulMsgMarshaler(req)),
			attribute.Key("rsp").String(traces.DefaulMsgMarshaler(rsp)),
		))
	}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK