github.com/rclone/rclone@v1.66.1-0.20240517100346-7b89735ae726/fs/fshttp/prometheus.go (about)

     1  package fshttp
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/prometheus/client_golang/prometheus"
     8  )
     9  
    10  // Metrics provide Transport HTTP level metrics.
    11  type Metrics struct {
    12  	StatusCode *prometheus.CounterVec
    13  }
    14  
    15  // NewMetrics creates a new metrics instance, the instance shall be assigned to
    16  // DefaultMetrics before any processing takes place.
    17  func NewMetrics(namespace string) *Metrics {
    18  	return &Metrics{
    19  		StatusCode: prometheus.NewCounterVec(prometheus.CounterOpts{
    20  			Namespace: namespace,
    21  			Subsystem: "http",
    22  			Name:      "status_code",
    23  		}, []string{"host", "method", "code"}),
    24  	}
    25  }
    26  
    27  // DefaultMetrics specifies metrics used for new Transports.
    28  var DefaultMetrics = (*Metrics)(nil)
    29  
    30  // Collectors returns all prometheus metrics as collectors for registration.
    31  func (m *Metrics) Collectors() []prometheus.Collector {
    32  	if m == nil {
    33  		return nil
    34  	}
    35  	return []prometheus.Collector{
    36  		m.StatusCode,
    37  	}
    38  }
    39  
    40  func (m *Metrics) onResponse(req *http.Request, resp *http.Response) {
    41  	if m == nil {
    42  		return
    43  	}
    44  
    45  	var statusCode = 0
    46  	if resp != nil {
    47  		statusCode = resp.StatusCode
    48  	}
    49  
    50  	m.StatusCode.WithLabelValues(req.Host, req.Method, fmt.Sprint(statusCode)).Inc()
    51  }