Log Request Body in Jetty Request Log

Guozheng Ge
2 min readJan 26, 2021

Jetty requests can be logged in NCSA format, also known as Common Log Format or Apache Log Format. Request log helps monitor past request history and analyze traffic. It can also serve as the input to replay traffic for debugging production issues in a non-production environment, or replay traffic at a different QPS to run performance testing.

Jetty provides classes such as NCSARequestLog, Slf4jRequestLog (older versions) and CustomRequestLog (newer versions) to log requests. However, it is a bit tricky to log request body since the content for a request object is from a stream and it can be consumed only once when the body is processed to implement the application logic. When the request is used to get body again, IllegalStateException will be thrown.

HttpServletRequestWrapper, as part of the Servlet standard, provides a way to extend HttpServletRequest for custom needs. We extend HttpServletRequestWrapper to cache the request body, then override getInputStream and getReader methods to read from the cache body. In this way, the request body can be read multiple times. See CachedBodyRequestWrapper for details.

Filter is a reusable and pluggable mechanism to pre or post process request and responses. For example, we can use filters to pre-process requests, e.g. validate and filter out invalid requests, check authentication, rate limit requests, etc. We can also use filters to post-process responses after servlet processor logic, e.g. add extra HTTP headers, enhance response body, log the request, etc. In this example, we use the filter to log request with body.

In this github demo project, we’ve implemented two sample Filters to log requests. One to be used by synchronous way of servlet processing, the other to be used by asynchronous way of servlet processing.

github project: https://github.com/guozheng/jetty-request-log

README: https://github.com/guozheng/jetty-request-log/blob/main/README.md

--

--