Skip to content

Commit

Permalink
⚡ Small performance improvement when tracing headers are not used
Browse files Browse the repository at this point in the history
  • Loading branch information
ujibang committed Apr 4, 2023
1 parent 0413ca1 commit afb7858
Showing 1 changed file with 22 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,37 +31,44 @@
import org.slf4j.MDC;
public class TracingInstrumentationHandler extends PipelinedHandler {
private final List<String> traceHeaders;
final private boolean emptyTraceHeaders;

public TracingInstrumentationHandler() {
var _th = Bootstrapper.getConfiguration().logging().tracingHeaders();
this.traceHeaders = _th == null ? new ArrayList<>() : _th;
this.emptyTraceHeaders = this.traceHeaders.isEmpty();
}

public TracingInstrumentationHandler(final PipelinedHandler next) {
super(next);
var _th = Bootstrapper.getConfiguration().logging().tracingHeaders();
this.traceHeaders = _th == null ? new ArrayList<>() : _th;
this.emptyTraceHeaders = this.traceHeaders.isEmpty();
}

@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
this.traceHeaders
.forEach((traceIdHeader) -> {Optional.ofNullable(exchange.getRequestHeaders()
.get(traceIdHeader))
.flatMap(x -> Optional.ofNullable(x.peekFirst()))
.ifPresent(value -> {
// saves the MDC Context
// see response.getMDCContext() javadoc
MDC.put(traceIdHeader, value);
ByteArrayProxyResponse.of(exchange).setMDCContext(MDC.getCopyOfContextMap());
exchange.getResponseHeaders().put(HttpString.tryFromString(traceIdHeader), value);
if (emptyTraceHeaders) {
next(exchange);
} else {
this.traceHeaders
.forEach((traceIdHeader) -> {Optional.ofNullable(exchange.getRequestHeaders()
.get(traceIdHeader))
.flatMap(x -> Optional.ofNullable(x.peekFirst()))
.ifPresent(value -> {
// saves the MDC Context
// see response.getMDCContext() javadoc
MDC.put(traceIdHeader, value);
ByteArrayProxyResponse.of(exchange).setMDCContext(MDC.getCopyOfContextMap());
exchange.getResponseHeaders().put(HttpString.tryFromString(traceIdHeader), value);
});
});
});

if (!exchange.isResponseComplete() && getNext() != null) {
next(exchange);
}
if (!exchange.isResponseComplete() && getNext() != null) {
next(exchange);
}

Bootstrapper.getConfiguration().logging().tracingHeaders().forEach((traceIdHeader) -> MDC.remove(traceIdHeader));
this.traceHeaders.forEach((traceIdHeader) -> MDC.remove(traceIdHeader));
}
}
}

0 comments on commit afb7858

Please sign in to comment.