TracingFilter extends Filter { @Override public CompletionStage<Result> apply(Function<Http.RequestHeader, CompletionStage<Result>> next, Http.RequestHeader request) { HandlerDef def = null; try { def = request.attrs().get(Router.Attrs.HANDLER_DEF); } catch (Throwable t) { } if (Objects.nonNull(def)) { final ContextCarrier carrier = new ContextCarrier(); CarrierItem items = carrier.items(); while (items.hasNext()) { items = items.next(); Optional<String> value = request.getHeaders().get(items.getHeadKey()); if (value.isPresent()) { items.setHeadValue(value.get()); } } final String operationName = routePattern.matcher(def.path()).replaceAll("{$1}"); final AbstractSpan span = ContextManager.createEntrySpan(operationName, carrier); final String url = request.host() + request.uri(); Tags.URL.set(span, url); Tags.HTTP.METHOD.set(span, request.method()); span.setComponent(ComponentsDefine.PLAY); SpanLayer.asHttp(span); span.prepareForAsync(); CompletionStage<Result> stage = next.apply(request).thenApply(result -> { if (result.status() >= 400) { span.errorOccurred(); Tags.STATUS_CODE.set(span, Integer.toString(result.status())); } try { span.asyncFinish(); } catch (Throwable t) { ContextManager.activeSpan().log(t); } return result; }); ContextManager.stopSpan(span); return stage; } return next.apply(request); } @Inject  TracingFilter(Materializer mat); @Override CompletionStage<Result> apply(Function<Http.RequestHeader, CompletionStage<Result>> next,
        Http.RequestHeader request);  }
@Test public void testStatusCodeIsOk() throws Exception { TracingFilter filter = new TracingFilter(materializer); Function<Http.RequestHeader, CompletionStage<Result>> next = requestHeader -> CompletableFuture.supplyAsync(() -> ok("Hello")); CompletionStage<Result> result = filter.apply(next, request); result.toCompletableFuture().get(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertHttpSpan(spans.get(0)); }
@Test public void testStatusCodeIsNotOk() throws Exception { TracingFilter filter = new TracingFilter(materializer); Function<Http.RequestHeader, CompletionStage<Result>> next = requestHeader -> CompletableFuture.supplyAsync(() -> badRequest("Hello")); CompletionStage<Result> result = filter.apply(next, request); result.toCompletableFuture().get(); assertThat(segmentStorage.getTraceSegments().size(), is(1)); TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0); List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment); assertHttpSpan(spans.get(0)); assertThat(SpanHelper.getErrorOccurred(spans.get(0)), is(true)); }