在响应中注入跟踪头

rks48beu  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(420)

我已将sleuth集成添加到应用程序中。现在日志显示了traceid和spanid。

INFO [AppName,5dd62861a751e1b0,5dd62861a751e1b0,true]

我可以使用打开的跟踪头发送http请求

X-B3-TraceId
X-B3-SpanId

跟踪程序使用的,我可以在日志中看到。但是我想在回复中返回它们。
我有一个过滤器,我想在响应中添加这些标题

public class RequestResponseFilter implements Filter {

    private final Tracer tracer;
    private final Injector<HttpServletResponse> tracingInjector;

    public RequestResponseFilter(final Tracing tracing, final Tracer tracer) {
        this.tracer = tracer;
        this.tracingInjector = tracing.propagation().injector(HttpServletResponse::addHeader);
    }

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain chain) throws IOException, ServletException {

        final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        final HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        ....

        // inject tracing header
        Span currentSpan = tracer.currentSpan();
        tracingInjector.inject(currentSpan.context(), httpServletResponse);

        chain.doFilter(httpServletRequest, httpServletResponse);
    }
}

但它们并没有以我预期的方式添加。在我看到的回答中

b3: 5dd62861a751e1b0,5dd62861a751e1b0-1

怎么了?

dpiehjr4

dpiehjr41#

如果您查看文档,了解如何自定义http服务器跨度-https://docs.spring.io/spring-cloud-sleuth/docs/current/reference/html/howto.html#how-要剪切http服务器跨度,因为您有权访问 HttpServletResponseTraceContext 您可以检索跟踪id/span id并将其放入响应中。
侦探3.x

@Configuration(proxyBeanMethods = false)
public static class ServerParserConfiguration {

    @Bean(name = HttpServerRequestParser.NAME)
    HttpRequestParser myHttpRequestParser() {
        return (request, context, span) -> {
            // Span customization
            span.tag("ServerRequest", "Tag");
            Object unwrap = request.unwrap();
            if (unwrap instanceof HttpServletRequest) {
                HttpServletRequest req = (HttpServletRequest) unwrap;
                // Span customization
                span.tag("ServerRequestServlet", req.getMethod());
            }
        };
    }

    @Bean(name = HttpServerResponseParser.NAME)
    HttpResponseParser myHttpResponseParser() {
        return (response, context, span) -> {
            // Span customization
            span.tag("ServerResponse", "Tag");
            Object unwrap = response.unwrap();
            if (unwrap instanceof HttpServletResponse) {
                HttpServletResponse resp = (HttpServletResponse) unwrap;
                // Span customization
                span.tag("ServerResponseServlet", String.valueOf(resp.getStatus()));
            }
        };
    }

}

sleuth 2.x(几乎完全相同)——https://docs.spring.io/spring-cloud-sleuth/docs/2.2.x/reference/html/#data-政策

相关问题