Skip to content

Commit

Permalink
add subrouter to metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
lucaslopezf committed Apr 18, 2024
1 parent 8d2bbe6 commit b1000d7
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 18 deletions.
16 changes: 8 additions & 8 deletions pkg/zrouter/zmiddlewares/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ import (
)

const (
cacheKeyPrefix = "zrouter_cache"
cacheSetsMetric = "cache_sets"
cacheHitsMetric = "cache_hits"
cacheMissesMetric = "cache_misses"
getRequestBodyMetric = "get_request_body"
cacheKeyPrefix = "zrouter_cache"
cacheSetsMetric = "cache_sets"
cacheHitsMetric = "cache_hits"
cacheMissesMetric = "cache_misses"
getRequestBodyErrorMetric = "get_request_body_error"
)

type CacheProcessedPath struct {
Expand Down Expand Up @@ -71,7 +71,7 @@ func constructCacheKey(fullURL string, r *http.Request, metricServer metrics.Tas
if shouldProcessRequestBody(r.Method) {
body, err := getRequestBody(r)
if err != nil {
if metricErr := metricServer.IncrementMetric(getRequestBodyMetric, GetRoutePattern(r)); metricErr != nil {
if metricErr := metricServer.IncrementMetric(getRequestBodyErrorMetric, GetSubRoutePattern(r), GetRoutePattern(r)); metricErr != nil {
logger.GetLoggerFromContext(r.Context()).Errorf("Error incrementing get_request_body metric: %v", metricErr)
}
return "", err
Expand All @@ -91,14 +91,14 @@ func tryServeFromCache(w http.ResponseWriter, r *http.Request, cache zcache.ZCac
w.Header().Set(domain.ContentTypeHeader, domain.ContentTypeApplicationJSON)
_, _ = w.Write(cachedResponse)

if err = metricServer.IncrementMetric(cacheHitsMetric, GetRoutePattern(r)); err != nil {
if err = metricServer.IncrementMetric(cacheHitsMetric, GetSubRoutePattern(r), GetRoutePattern(r)); err != nil {
logger.GetLoggerFromContext(r.Context()).Errorf("Error incrementing cache_hits metric: %v", err)
}

return true
}

if err = metricServer.IncrementMetric(cacheMissesMetric, GetRoutePattern(r)); err != nil {
if err = metricServer.IncrementMetric(cacheMissesMetric, GetSubRoutePattern(r), GetRoutePattern(r)); err != nil {
logger.GetLoggerFromContext(r.Context()).Errorf("Error incrementing cache_misses metric: %v", err)
}

Expand Down
9 changes: 9 additions & 0 deletions pkg/zrouter/zmiddlewares/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ func GetRoutePattern(r *http.Request) string {
return tctx.RoutePattern()
}

func GetSubRoutePattern(r *http.Request) string {
rctx := chi.RouteContext(r.Context())
if rctx == nil {
return undefinedPath
}

return rctx.RoutePattern()
}

func getRequestBody(r *http.Request) ([]byte, error) {
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
Expand Down
24 changes: 14 additions & 10 deletions pkg/zrouter/zmiddlewares/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const (
pathLabel = "path"
methodLabel = "method"
statusLabel = "status"
subRouteLabel = "sub_route"
)

func RegisterRequestMetrics(metricsServer metrics.TaskMetrics) []error {
Expand All @@ -29,17 +30,19 @@ func RegisterRequestMetrics(metricsServer metrics.TaskMetrics) []error {
}
}

register(totalRequestsMetricName, "Total number of HTTP requests made.", []string{"method", "path", "status"}, &collectors.Counter{})
register(durationMillisecondsMetricName, "Duration of HTTP requests in milliseconds.", []string{"method", "path", "status"}, &collectors.Gauge{})
register(responseSizeMetricName, "Size of HTTP response in bytes.", []string{"method", "path", "status"}, &collectors.Histogram{})
register(activeConnectionsMetricName, "Number of active HTTP connections.", []string{"method", "path"}, &collectors.Gauge{})
register(totalRequestsMetricName, "Total number of HTTP requests made.", []string{subRouteLabel, methodLabel, pathLabel, statusLabel}, &collectors.Counter{})
register(durationMillisecondsMetricName, "Duration of HTTP requests in milliseconds.", []string{subRouteLabel, methodLabel, pathLabel, statusLabel}, &collectors.Gauge{})
register(responseSizeMetricName, "Size of HTTP response in bytes.", []string{subRouteLabel, methodLabel, pathLabel, statusLabel}, &collectors.Histogram{})
register(activeConnectionsMetricName, "Number of active HTTP connections.", []string{subRouteLabel, methodLabel, pathLabel}, &collectors.Gauge{})

register(getRequestBodyErrorMetric, "Register get request body error.", []string{subRouteLabel, pathLabel}, &collectors.Counter{})

cacheHitsMetricName := cacheHitsMetric
cacheMissesMetricName := cacheMissesMetric
cacheSetsMetricName := cacheSetsMetric
register(cacheHitsMetricName, "Number of cache hits.", []string{pathLabel}, &collectors.Counter{})
register(cacheMissesMetricName, "Number of cache misses.", []string{pathLabel}, &collectors.Counter{})
register(cacheSetsMetricName, "Number of responses added to the cache.", []string{pathLabel}, &collectors.Counter{})
register(cacheHitsMetricName, "Number of cache hits.", []string{subRouteLabel, pathLabel}, &collectors.Counter{})
register(cacheMissesMetricName, "Number of cache misses.", []string{subRouteLabel, pathLabel}, &collectors.Counter{})
register(cacheSetsMetricName, "Number of responses added to the cache.", []string{subRouteLabel, pathLabel}, &collectors.Counter{})

return errs
}
Expand All @@ -51,11 +54,12 @@ func RequestMetrics(metricsServer metrics.TaskMetrics) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := GetRoutePattern(r)
subRoute := GetSubRoutePattern(r)
startTime := time.Now()

mu.Lock()
activeConnections++
if err := metricsServer.UpdateMetric(activeConnectionsMetricName, float64(activeConnections), r.Method, path); err != nil {
if err := metricsServer.UpdateMetric(activeConnectionsMetricName, float64(activeConnections), subRoute, r.Method, path); err != nil {
logger.GetLoggerFromContext(r.Context()).Errorf("error updating active connections metric: %v", err.Error())
}
mu.Unlock()
Expand All @@ -65,7 +69,7 @@ func RequestMetrics(metricsServer metrics.TaskMetrics) Middleware {

mu.Lock()
activeConnections--
if err := metricsServer.UpdateMetric(activeConnectionsMetricName, float64(activeConnections), r.Method, path); err != nil {
if err := metricsServer.UpdateMetric(activeConnectionsMetricName, float64(activeConnections), subRoute, r.Method, path); err != nil {
logger.GetLoggerFromContext(r.Context()).Errorf("error updating active connections metric: %v", err.Error())
}
mu.Unlock()
Expand All @@ -75,7 +79,7 @@ func RequestMetrics(metricsServer metrics.TaskMetrics) Middleware {
responseStatus := mrw.status
bytesWritten := mrw.written

labels := []string{r.Method, path, strconv.Itoa(responseStatus)}
labels := []string{subRoute, r.Method, path, strconv.Itoa(responseStatus)}

if err := metricsServer.UpdateMetric(durationMillisecondsMetricName, duration, labels...); err != nil {
logger.GetLoggerFromContext(r.Context()).Errorf("error updating request duration metric: %v", err.Error())
Expand Down

0 comments on commit b1000d7

Please sign in to comment.