How to include JSON response body in Spring Boot Actuator's Trace?

前端 未结 3 1869
星月不相逢
星月不相逢 2020-12-16 13:41

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

3条回答
  •  醉梦人生
    2020-12-16 14:15

    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.

    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 getTrace(HttpServletRequest request) {
            Map trace = super.getTrace(request);
    
            byte[] outputBuffer = (byte[]) request.getAttribute("responseBody");
    
            if (outputBuffer != null) {
                trace.put("responseBody", new String(outputBuffer));
            }
    
            return trace;
        }
    }
    

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

提交回复
热议问题