Skip to content
This repository has been archived by the owner on Jul 24, 2023. It is now read-only.

Commit

Permalink
Add http status code to attributes and metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrew Hobson committed Nov 22, 2021
1 parent 0309ae2 commit 48f9ab3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
8 changes: 8 additions & 0 deletions handler.go
Expand Up @@ -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
}

Expand Down Expand Up @@ -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...)
Expand Down
15 changes: 14 additions & 1 deletion test/handler_test.go
Expand Up @@ -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)
Expand Down

0 comments on commit 48f9ab3

Please sign in to comment.