github.com/blend/go-sdk@v1.20220411.3/stats/redisstats/listeners.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 redisstats
     9  
    10  import (
    11  	"context"
    12  
    13  	"github.com/blend/go-sdk/logger"
    14  	"github.com/blend/go-sdk/redis"
    15  	"github.com/blend/go-sdk/stats"
    16  	"github.com/blend/go-sdk/timeutil"
    17  )
    18  
    19  // AddListeners adds db listeners.
    20  func AddListeners(log logger.Listenable, collector stats.Collector, opts ...stats.AddListenerOption) {
    21  	if log == nil || collector == nil {
    22  		return
    23  	}
    24  
    25  	options := stats.NewAddListenerOptions(opts...)
    26  
    27  	log.Listen(redis.Flag, stats.ListenerNameStats, redis.NewEventListener(func(ctx context.Context, e redis.Event) {
    28  		var tags []string
    29  		if len(e.Network) > 0 {
    30  			tags = append(tags, stats.Tag(TagNetwork, e.Network))
    31  		}
    32  		if len(e.Addr) > 0 {
    33  			tags = append(tags, stats.Tag(TagAddr, e.Addr))
    34  		}
    35  		if len(e.DB) > 0 {
    36  			tags = append(tags, stats.Tag(TagDB, e.DB))
    37  		}
    38  		if len(e.Op) > 0 {
    39  			tags = append(tags, stats.Tag(TagOp, e.Op))
    40  		}
    41  		if e.Err != nil {
    42  			tags = append(tags, stats.TagError)
    43  		}
    44  
    45  		tags = append(tags, options.GetLoggerLabelsAsTags(ctx)...)
    46  
    47  		_ = collector.Increment(MetricName, tags...)
    48  		_ = collector.Gauge(MetricNameElapsedLast, timeutil.Milliseconds(e.Elapsed), tags...)
    49  		_ = collector.Histogram(MetricNameElapsed, timeutil.Milliseconds(e.Elapsed), tags...)
    50  	}))
    51  }