Video in progress

You've been asked to write a filter that logs HTTP request and response bodies. What technical problems will you run into, and how do you make it safe?

A body stream can be read only once, so you have to cache it with ContentCachingRequestWrapper/ContentCachingResponseWrapper, which costs memory and latency. Large and binary bodies, streaming responses, sensitive fields and log volume are also problems. So I only do it for the endpoints that need it, with a size limit and masking.

📖 Answer

The first trap: if you read request.getInputStream() in the filter, the controller gets an empty body. Spring has wrappers for this:

@Component
class BodyLoggingFilter extends OncePerRequestFilter {
    private static final int MAX = 4 * 1024; // we don't log more than 4 KB

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
                                    FilterChain chain) throws ServletException, IOException {
        var request = new ContentCachingRequestWrapper(req, MAX);
        var response = new ContentCachingResponseWrapper(res);
        try {
            chain.doFilter(request, response);
        } finally {
            log.atDebug().setMessage("HTTP {} {}")
               .addArgument(req.getMethod()).addArgument(req.getRequestURI())
               .addKeyValue("status", response.getStatus())
               .addKeyValue("requestBody", () -> mask(request.getContentAsString()))
               .log();
            response.copyBodyToResponse(); // if you forget this, the client gets an empty response
        }
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest req) {
        return !req.getRequestURI().startsWith("/api/partners/"); // only where it's needed
    }
}

Things to watch:

  • ContentCachingRequestWrapper caches the body only after the controller has read it, so before chain.doFilter it is empty in the filter.
  • copyBodyToResponse() is mandatory. The response wrapper holds the whole response in memory: on an endpoint that serves a 50 MB file download this eats the heap and breaks streaming. Exclude file and SSE endpoints.
  • Masking: a body may contain a password, a card number or a token. Parsing the JSON and replacing known fields is more reliable than a regex.
  • Volume: two bodies per request multiplies the log volume tenfold. I keep this at DEBUG by default and turn it on only while an integration problem is being investigated.

Often the real reason behind the requirement is "proving what the partner sent". In that case it is better to write the body not to the application log but to a separate audit store with restricted access.