You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.8 KiB
62 lines
1.8 KiB
package tracing
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/go-kratos/kratos/v2/middleware"
|
|
"github.com/go-kratos/kratos/v2/transport"
|
|
"go.opentelemetry.io/otel/propagation"
|
|
"go.opentelemetry.io/otel/trace"
|
|
)
|
|
|
|
// Option is tracing option.
|
|
type Option func(*options)
|
|
|
|
type options struct {
|
|
TracerProvider trace.TracerProvider
|
|
Propagators propagation.TextMapPropagator
|
|
}
|
|
|
|
// WithPropagators with tracer proagators.
|
|
func WithPropagators(propagators propagation.TextMapPropagator) Option {
|
|
return func(opts *options) {
|
|
opts.Propagators = propagators
|
|
}
|
|
}
|
|
|
|
// WithTracerProvider with tracer privoder.
|
|
func WithTracerProvider(provider trace.TracerProvider) Option {
|
|
return func(opts *options) {
|
|
opts.TracerProvider = provider
|
|
}
|
|
}
|
|
|
|
// Server returns a new server middleware for OpenTelemetry.
|
|
func Server(opts ...Option) middleware.Middleware {
|
|
tracer := NewTracer(trace.SpanKindServer, opts...)
|
|
return func(handler middleware.Handler) middleware.Handler {
|
|
return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
|
|
if tr, ok := transport.FromServerContext(ctx); ok {
|
|
var span trace.Span
|
|
ctx, span = tracer.Start(ctx, tr.Kind(), tr.Operation(), tr.Metadata())
|
|
defer func() { tracer.End(ctx, span, err) }()
|
|
}
|
|
return handler(ctx, req)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Client returns a new client middleware for OpenTelemetry.
|
|
func Client(opts ...Option) middleware.Middleware {
|
|
tracer := NewTracer(trace.SpanKindClient, opts...)
|
|
return func(handler middleware.Handler) middleware.Handler {
|
|
return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
|
|
if tr, ok := transport.FromClientContext(ctx); ok {
|
|
var span trace.Span
|
|
ctx, span = tracer.Start(ctx, tr.Kind(), tr.Operation(), tr.Metadata())
|
|
defer func() { tracer.End(ctx, span, err) }()
|
|
}
|
|
return handler(ctx, req)
|
|
}
|
|
}
|
|
}
|
|
|