Last active
February 8, 2021 08:01
-
-
Save yusufcakal/c593d8d92619559675ee90b38f932459 to your computer and use it in GitHub Desktop.
Helps you easy to tracing logs to request and response via Spring
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Component | |
| public class LoggingFilter extends OncePerRequestFilter { | |
| @Override | |
| protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { | |
| MDC.put("requestId", "Request ID: " + UUID.randomUUID().toString()); | |
| String method = request.getMethod(); | |
| String endpoint = request.getRequestURL().toString(); | |
| ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request); | |
| ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response); | |
| filterChain.doFilter(wrappedRequest, wrappedResponse); | |
| String requestBody = getContentAsString(wrappedRequest.getContentAsByteArray()); | |
| if (requestBody.length() > 0) { | |
| this.logger.info("Request: " + method + " - " + endpoint + "\n" + requestBody); | |
| } | |
| String responseBody = getContentAsString(wrappedResponse.getContentAsByteArray()); | |
| this.logger.info("Response: \n" + responseBody); | |
| wrappedResponse.copyBodyToResponse(); | |
| } | |
| private String getContentAsString(byte[] bytes) { | |
| return (bytes != null && bytes.length > 0) ? new String(bytes, 0, bytes.length, StandardCharsets.UTF_8) : Strings.EMPTY; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment