如何在Spring Boot Actuator的Trace中包括JSON响应主体? [英] How to include JSON response body in Spring Boot Actuator's Trace?

查看:327
本文介绍了如何在Spring Boot Actuator的Trace中包括JSON响应主体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring Boot Actuator的Trace在捕获输入/输出HTTP参数,标头,用户等方面做得很好.我想扩展它以捕获HTTP响应的主体,这样我就可以全面了解Web层中进出的内容.看着TraceProperties,似乎没有一种方法可以配置响应正文捕获.是否有一种安全"的方式来捕获响应主体,而不会弄乱它发回的任何字符流?

Spring Boot Actuator's Trace does a good job of capturing input/output HTTP params, headers, users, etc. I'd like to expand it to also capture the body of the HTTP response, that way I can have a full view of what is coming in and going out of the the web layer. Looking at the TraceProperties, doesn't look like there is a way to configure response body capturing. Is there a "safe" way to capture the response body without messing up whatever character stream it is sending back?

推荐答案

最近,我写了一个

Recently, I wrote a blog post about customization of Spring Boot Actuator's trace endpoint and while playing with Actuator, I was kinda surprised that response body isn't one of the supported properties to trace.

由于Logback的> TeeFilter .

I thought I may need this feature and came up with a quick solution thanks to Logback's TeeFilter.

要复制响应的输出流,我复制并使用了

To duplicate output stream of the response, I copied and used TeeHttpServletResponse and TeeServletOutputStream without too much examination.

然后,就像我在博客文章中所解释的那样,扩展了

Then, just like I explained in the blog post, extended WebRequestTraceFilter like:

@Component
public class RequestTraceFilter extends WebRequestTraceFilter {

    RequestTraceFilter(TraceRepository repository, TraceProperties properties) {
        super(repository, properties);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        TeeHttpServletResponse teeResponse = new TeeHttpServletResponse(response);

        filterChain.doFilter(request, teeResponse);

        teeResponse.finish();

        request.setAttribute("responseBody", teeResponse.getOutputBuffer());

        super.doFilterInternal(request, teeResponse, filterChain);
    }

    @Override
    protected Map<String, Object> getTrace(HttpServletRequest request) {
        Map<String, Object> trace = super.getTrace(request);

        byte[] outputBuffer = (byte[]) request.getAttribute("responseBody");

        if (outputBuffer != null) {
            trace.put("responseBody", new String(outputBuffer));
        }

        return trace;
    }
}

现在,您可以在JSON trace端点服务中看到responseBody.

Now, you can see responseBody in the JSON trace endpoint serves.

这篇关于如何在Spring Boot Actuator的Trace中包括JSON响应主体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆