From a7349b5d2d3ce9ef5d2423e539a7179a8cb92705 Mon Sep 17 00:00:00 2001 From: "m.nabokikh" Date: Fri, 7 May 2021 00:20:59 +0400 Subject: [PATCH] Add request count metric with status code label Signed-off-by: m.nabokikh --- instrumentation/net/http/otelhttp/handler.go | 8 ++++++++ instrumentation/net/http/otelhttp/handler_test.go | 14 +++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/instrumentation/net/http/otelhttp/handler.go b/instrumentation/net/http/otelhttp/handler.go index c912548b066..7a3fb8e8da8 100644 --- a/instrumentation/net/http/otelhttp/handler.go +++ b/instrumentation/net/http/otelhttp/handler.go @@ -102,11 +102,15 @@ func (h *Handler) createMeasures() { responseBytesCounter, err := h.meter.NewInt64Counter(ResponseContentLength) handleErr(err) + requestCount, err := h.meter.NewInt64Counter(RequestCount) + handleErr(err) + serverLatencyMeasure, err := h.meter.NewInt64ValueRecorder(ServerLatency) handleErr(err) h.counters[RequestContentLength] = requestBytesCounter h.counters[ResponseContentLength] = responseBytesCounter + h.counters[RequestCount] = requestCount h.valueRecorders[ServerLatency] = serverLatencyMeasure } @@ -185,6 +189,10 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.counters[RequestContentLength].Add(ctx, bw.read, attributes...) h.counters[ResponseContentLength].Add(ctx, rww.written, attributes...) + // Count of request to record errors ratio + requestCountAttributes := append(attributes, semconv.HTTPStatusCodeKey.Int(rww.statusCode)) + h.counters[RequestCount].Add(ctx, 1, requestCountAttributes...) + elapsedTime := time.Since(requestStartTime).Microseconds() h.valueRecorders[ServerLatency].Record(ctx, elapsedTime, attributes...) diff --git a/instrumentation/net/http/otelhttp/handler_test.go b/instrumentation/net/http/otelhttp/handler_test.go index 5565b69eafb..fab186d43e9 100644 --- a/instrumentation/net/http/otelhttp/handler_test.go +++ b/instrumentation/net/http/otelhttp/handler_test.go @@ -81,7 +81,19 @@ func TestHandlerBasics(t *testing.T) { attribute.String("test", "attribute"), } - assertMetricAttributes(t, attributesToVerify, meterimpl.MeasurementBatches) + var statusCodeBatch oteltest.Batch + var measurementBatches []oteltest.Batch + for _, batch := range meterimpl.MeasurementBatches { + batchName := batch.Measurements[0].Instrument.Descriptor().Name() + if batchName == RequestCount { + statusCodeBatch = batch + continue + } + measurementBatches = append(measurementBatches, batch) + } + + assertMetricAttributes(t, attributesToVerify, measurementBatches) + assert.ElementsMatch(t, append(attributesToVerify, semconv.HTTPStatusCodeKey.Int(200)), statusCodeBatch.Labels) if got, expected := rr.Result().StatusCode, http.StatusOK; got != expected { t.Fatalf("got %d, expected %d", got, expected)