Skip to content

Commit

Permalink
Add request count metric with status code label
Browse files Browse the repository at this point in the history
Signed-off-by: m.nabokikh <maksim.nabokikh@flant.com>
  • Loading branch information
nabokihms committed May 6, 2021
1 parent 13d72c9 commit a7349b5
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
8 changes: 8 additions & 0 deletions instrumentation/net/http/otelhttp/handler.go
Expand Up @@ -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
}

Expand Down Expand Up @@ -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...)
Expand Down
14 changes: 13 additions & 1 deletion instrumentation/net/http/otelhttp/handler_test.go
Expand Up @@ -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)
Expand Down

0 comments on commit a7349b5

Please sign in to comment.