github.com/blend/go-sdk@v1.20220411.3/tracing/redistrace/tracer.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package redistrace
     9  
    10  import (
    11  	"context"
    12  	"strings"
    13  	"time"
    14  
    15  	opentracing "github.com/opentracing/opentracing-go"
    16  
    17  	"github.com/blend/go-sdk/redis"
    18  	"github.com/blend/go-sdk/tracing"
    19  )
    20  
    21  var (
    22  	_ redis.Tracer = (*redisTracer)(nil)
    23  )
    24  
    25  // Tracer returns a new redis tracer.
    26  func Tracer(tracer opentracing.Tracer) redis.Tracer {
    27  	return redisTracer{tracer: tracer}
    28  }
    29  
    30  type redisTracer struct {
    31  	tracer opentracing.Tracer
    32  }
    33  
    34  func (rt redisTracer) Do(ctx context.Context, cfg redis.Config, op string, args []string) redis.TraceFinisher {
    35  	host, port := splitHostPort(cfg.Addr)
    36  	startOptions := []opentracing.StartSpanOption{
    37  		opentracing.Tag{Key: tracing.TagKeyResourceName, Value: op},
    38  		opentracing.Tag{Key: tracing.TagKeySpanType, Value: tracing.SpanTypeRedis},
    39  		opentracing.Tag{Key: tracing.TagKeyTargetHost, Value: host},
    40  		opentracing.Tag{Key: tracing.TagKeyTargetPort, Value: port},
    41  		opentracing.Tag{Key: "out.db", Value: cfg.DB},
    42  		tracing.TagMeasured(),
    43  		opentracing.StartTime(time.Now().UTC()),
    44  	}
    45  	span, _ := tracing.StartSpanFromContext(ctx, rt.tracer, tracing.OperationRedisCommand, startOptions...)
    46  	return redisTraceFinisher{span: span}
    47  }
    48  
    49  type redisTraceFinisher struct {
    50  	span opentracing.Span
    51  }
    52  
    53  func (rtf redisTraceFinisher) Finish(ctx context.Context, err error) {
    54  	if rtf.span == nil {
    55  		return
    56  	}
    57  	tracing.SpanError(rtf.span, err)
    58  	rtf.span.Finish()
    59  }
    60  
    61  func splitHostPort(addr string) (host, port string) {
    62  	parts := strings.SplitN(addr, ":", 2)
    63  	if len(parts) > 0 {
    64  		host = parts[0]
    65  	}
    66  	if len(parts) > 1 {
    67  		port = parts[1]
    68  	}
    69  	return
    70  }