Skip to content

Commit

Permalink
Best effort at recording the content length on a http response. (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
jkwatson authored Jul 1, 2021
1 parent 2a521ba commit cecfc34
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.semconv.trace.attributes.SemanticAttributes;
import okhttp3.Call;
import okhttp3.Connection;
import okhttp3.Interceptor;
Expand Down Expand Up @@ -78,13 +79,14 @@ public Response proceed(@NotNull Request request) throws IOException {
Span span = Span.current();
span.setAttribute(SplunkRum.COMPONENT_KEY, "http");

Response response = null;
Response response;
try {
response = chain.proceed(request);
} catch (IOException e) {
SplunkRum.addExceptionAttributes(span, e);
throw e;
}
recordContentLength(span, response);

String serverTimingHeader = response.header("Server-Timing");

Expand All @@ -96,6 +98,21 @@ public Response proceed(@NotNull Request request) throws IOException {
return response;
}

private void recordContentLength(Span span, Response response) {
//make a best low-impact effort at getting the content length on the response.
String contentLengthHeader = response.header("Content-Length");
if (contentLengthHeader != null) {
try {
long contentLength = Long.parseLong(contentLengthHeader);
if (contentLength > 0) {
span.setAttribute(SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH, contentLength);
}
} catch (NumberFormatException e) {
//who knows what we got back? It wasn't a number!
}
}
}

@Override
public Connection connection() {
return chain.connection();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ public void spanDecoration() throws IOException {
.message("hello")
.code(200)
.addHeader("Server-Timing", "headerValue")
.addHeader("Content-Length", "101")
.build());

OkHttpRumInterceptor interceptor = new OkHttpRumInterceptor(new TestTracingInterceptor(tracer), headerParser);
Expand All @@ -78,6 +79,7 @@ public void spanDecoration() throws IOException {
assertEquals("http", spanData.getAttributes().get(SplunkRum.COMPONENT_KEY));
assertEquals("9499195c502eb217c448a68bfe0f967c", spanData.getAttributes().get(OkHttpRumInterceptor.LINK_TRACE_ID_KEY));
assertEquals("fe16eca542cd5d86", spanData.getAttributes().get(OkHttpRumInterceptor.LINK_SPAN_ID_KEY));
assertEquals(101L, (long) spanData.getAttributes().get(SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH));
}

@Test
Expand Down

0 comments on commit cecfc34

Please sign in to comment.