Junior — Middle
How do you implement logging of the incoming request content in the controller?
sobes.tech AI
Answer from AI
To log the contents of incoming HTTP requests in a Java controller, filters or aspects are often used to avoid cluttering the controller itself. In a simple case, you can log the request body and headers, for example, using Spring Boot and OncePerRequestFilter:
@Component
public class RequestLoggingFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(RequestLoggingFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// Wrapper for multiple reads of the request body
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
filterChain.doFilter(wrappedRequest, response);
String requestBody = new String(wrappedRequest.getContentAsByteArray(), request.getCharacterEncoding());
logger.info("Request URI: {}", request.getRequestURI());
logger.info("Request Method: {}", request.getMethod());
logger.info("Request Body: {}", requestBody);
}
}
This approach allows centralized logging of requests without modifying controllers. You can also log parameters or headers in the controller if needed, but it's better to separate logging logic from business logic.