diff --git a/CHANGELOG.md b/CHANGELOG.md index bdaf662e891..09016c05cc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ## [0.21.0] - 2021-06-18 +### Added + +- Add total requests counter by response status code for the `net/http` instrumentation. (#771) + ### Fixed - Dockerfile based examples for `otelgin` and `otelmacaron`. (#767) diff --git a/instrumentation/net/http/otelhttp/handler.go b/instrumentation/net/http/otelhttp/handler.go index 305c4d7661d..f354f5328ce 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 c718b0a36a7..e25e57facbf 100644 --- a/instrumentation/net/http/otelhttp/handler_test.go +++ b/instrumentation/net/http/otelhttp/handler_test.go @@ -82,7 +82,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)