Video in progress

Strong Middle 🌱 Spring

You wrote a filter to log the request body, and now the controller gets an empty body. Why, and how do you do it properly?

The request body is an InputStream that can only be read once; after the filter reads it, nothing is left for the controller. ContentCachingRequestWrapper copies the body as the controller reads it, and you log it after the request completes.

📖 Answer

The wrong version:

String body = new String(req.getInputStream().readAllBytes(), UTF_8);
log.info("body={}", body);
chain.doFilter(req, res);   // controller: Required request body is missing

The right way is a wrapper, with the log written after the chain:

@Component
class PayloadLoggingFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
                                    FilterChain chain) throws ServletException, IOException {
        var request = new ContentCachingRequestWrapper(req, 10_000);   // up to 10 KB
        var response = new ContentCachingResponseWrapper(res);
        try {
            chain.doFilter(request, response);
        } finally {
            log.debug("{} {} -> {} body={}", req.getMethod(), req.getRequestURI(),
                      response.getStatus(), mask(new String(request.getContentAsByteArray(), UTF_8)));
            response.copyBodyToResponse();   // if you forget, the client gets an empty response
        }
    }
}

Subtle points:

  • ContentCachingRequestWrapper doesn't read the body ahead of time; it copies it when someone reads it. So getContentAsByteArray() is complete only after doFilter;
  • copyBodyToResponse() is mandatory, otherwise the response stays stuck inside the wrapper;
  • on file upload, SSE and big download endpoints this filter eats memory and breaks streaming, so exclude them with shouldNotFilter;
  • mask password, card and token fields. Permanently logging the full body at INFO is both a cost problem and a security problem.

Often, instead of body logs, tracing and the important fields in structured logs are enough. I turn on body logging only for debugging, and only temporarily.