github.com/blend/go-sdk@v1.20220411.3/stats/r2stats/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 r2stats
     9  
    10  import (
    11  	"context"
    12  	"strconv"
    13  
    14  	"github.com/blend/go-sdk/logger"
    15  	"github.com/blend/go-sdk/r2"
    16  	"github.com/blend/go-sdk/sanitize"
    17  	"github.com/blend/go-sdk/stats"
    18  	"github.com/blend/go-sdk/timeutil"
    19  )
    20  
    21  // AddListeners adds web listeners.
    22  func AddListeners(log logger.FilterListenable, collector stats.Collector, opts ...stats.AddListenerOption) {
    23  	if log == nil || collector == nil {
    24  		return
    25  	}
    26  
    27  	options := stats.NewAddListenerOptions(opts...)
    28  
    29  	requestSanitizer := sanitize.NewRequestSanitizer(options.RequestSanitizeDefaults...)
    30  
    31  	log.Filter(r2.Flag,
    32  		stats.FilterNameSanitization,
    33  		r2.NewEventFilter(func(_ context.Context, r2e r2.Event) (r2.Event, bool) {
    34  			r2e.Request = requestSanitizer.Sanitize(r2e.Request)
    35  			return r2e, false
    36  		}),
    37  	)
    38  	log.Filter(r2.FlagResponse,
    39  		stats.FilterNameSanitization,
    40  		r2.NewEventFilter(func(_ context.Context, r2e r2.Event) (r2.Event, bool) {
    41  			r2e.Request = requestSanitizer.Sanitize(r2e.Request)
    42  			return r2e, false
    43  		}),
    44  	)
    45  
    46  	log.Listen(r2.FlagResponse, stats.ListenerNameStats,
    47  		r2.NewEventListener(func(ctx context.Context, r2e r2.Event) {
    48  			hostname := stats.Tag(TagHostname, r2e.Request.URL.Hostname())
    49  			target := stats.Tag(TagTarget, r2e.Request.URL.Hostname())
    50  			method := stats.Tag(TagMethod, r2e.Request.Method)
    51  			status := stats.Tag(TagStatus, strconv.Itoa(r2e.Response.StatusCode))
    52  			tags := []string{
    53  				hostname, target, method, status,
    54  			}
    55  			tags = append(tags, options.GetLoggerLabelsAsTags(ctx)...)
    56  			_ = collector.Increment(MetricNameHTTPClientRequest, tags...)
    57  			_ = collector.Gauge(MetricNameHTTPClientRequestElapsedLast, timeutil.Milliseconds(r2e.Elapsed), tags...)
    58  			_ = collector.Histogram(MetricNameHTTPClientRequestElapsed, timeutil.Milliseconds(r2e.Elapsed), tags...)
    59  		}),
    60  	)
    61  }