From 62db73867415433f63267c46d2566058ed4ccd71 Mon Sep 17 00:00:00 2001 From: Andrew Hobson Date: Mon, 22 Nov 2021 08:40:23 -0500 Subject: [PATCH] Add http status code to attributes and metrics Taken from: https://github.com/open-telemetry/opentelemetry-go-contrib/pull/771 --- handler.go | 8 ++++++++ test/handler_test.go | 15 ++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/handler.go b/handler.go index cadf561..e66371f 100644 --- a/handler.go +++ b/handler.go @@ -105,8 +105,12 @@ func (h *Handler) createMeasures() { serverLatencyMeasure, err := h.meter.NewInt64Histogram(ServerLatency) handleErr(err) + requestCount, err := h.meter.NewInt64Counter(RequestCount) + handleErr(err) + h.counters[RequestContentLength] = requestBytesCounter h.counters[ResponseContentLength] = responseBytesCounter + h.counters[RequestCount] = requestCount h.valueRecorders[ServerLatency] = serverLatencyMeasure } @@ -195,6 +199,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/test/handler_test.go b/test/handler_test.go index ba507de..0bf3a4a 100644 --- a/test/handler_test.go +++ b/test/handler_test.go @@ -85,7 +85,20 @@ func TestHandlerBasics(t *testing.T) { attribute.String("test", "attribute"), } - assertMetricAttributes(t, attributesToVerify, meterProvider.MeasurementBatches) + var statusCodeBatch metrictest.Batch + var measurementBatches []metrictest.Batch + for _, batch := range meterProvider.MeasurementBatches { + batchName := batch.Measurements[0].Instrument.Descriptor().Name() + // separate the status code batch from the rest + if batchName == otelhttp.RequestCount { + statusCodeBatch = batch + } else { + 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)