github.com/blend/go-sdk@v1.20220411.3/stats/httpstats/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 httpstats
     9  
    10  import (
    11  	"context"
    12  	"strconv"
    13  
    14  	"github.com/blend/go-sdk/logger"
    15  	"github.com/blend/go-sdk/sanitize"
    16  	"github.com/blend/go-sdk/stats"
    17  	"github.com/blend/go-sdk/timeutil"
    18  	"github.com/blend/go-sdk/webutil"
    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(webutil.FlagHTTPRequest,
    32  		stats.FilterNameSanitization,
    33  		webutil.NewHTTPRequestEventFilter(func(_ context.Context, wre webutil.HTTPRequestEvent) (webutil.HTTPRequestEvent, bool) {
    34  			wre.Request = requestSanitizer.Sanitize(wre.Request)
    35  			return wre, false
    36  		}),
    37  	)
    38  
    39  	log.Listen(webutil.FlagHTTPRequest, stats.ListenerNameStats,
    40  		webutil.NewHTTPRequestEventListener(func(ctx context.Context, wre webutil.HTTPRequestEvent) {
    41  			var route string
    42  			if len(wre.Route) > 0 {
    43  				route = stats.Tag(TagRoute, wre.Route)
    44  			} else {
    45  				route = stats.Tag(TagRoute, RouteNotFound)
    46  			}
    47  
    48  			proto := stats.Tag(TagProto, wre.Request.Proto)
    49  			method := stats.Tag(TagMethod, wre.Request.Method)
    50  			status := stats.Tag(TagStatus, strconv.Itoa(wre.StatusCode))
    51  			tags := []string{
    52  				proto, route, method, status,
    53  			}
    54  			tags = append(tags, options.GetLoggerLabelsAsTags(ctx)...)
    55  
    56  			_ = collector.Increment(MetricNameHTTPRequest, tags...)
    57  			_ = collector.Gauge(MetricNameHTTPRequestSize, float64(wre.ContentLength), tags...)
    58  			_ = collector.Histogram(MetricNameHTTPRequestElapsed, timeutil.Milliseconds(wre.Elapsed), tags...)
    59  			_ = collector.Gauge(MetricNameHTTPRequestElapsedLast, timeutil.Milliseconds(wre.Elapsed), tags...)
    60  		}),
    61  	)
    62  }