github.com/blend/go-sdk@v1.20220411.3/stats/dbstats/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 dbstats
     9  
    10  import (
    11  	"context"
    12  
    13  	"github.com/blend/go-sdk/db"
    14  	"github.com/blend/go-sdk/logger"
    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(db.QueryFlag, stats.ListenerNameStats, db.NewQueryEventListener(func(ctx context.Context, qe db.QueryEvent) {
    28  		engine := stats.Tag(TagEngine, qe.Engine)
    29  		database := stats.Tag(TagDatabase, qe.Database)
    30  
    31  		tags := []string{
    32  			engine, database,
    33  		}
    34  		if len(qe.Label) > 0 {
    35  			tags = append(tags, stats.Tag(TagQuery, qe.Label))
    36  		}
    37  		if qe.Err != nil {
    38  			tags = append(tags, stats.TagError)
    39  		}
    40  
    41  		tags = append(tags, options.GetLoggerLabelsAsTags(ctx)...)
    42  
    43  		_ = collector.Increment(MetricNameDBQuery, tags...)
    44  		_ = collector.Gauge(MetricNameDBQueryElapsedLast, timeutil.Milliseconds(qe.Elapsed), tags...)
    45  		_ = collector.Histogram(MetricNameDBQueryElapsed, timeutil.Milliseconds(qe.Elapsed), tags...)
    46  	}))
    47  }