Skip to content

Instantly share code, notes, and snippets.

@yusufcakal
Last active February 8, 2021 08:01
Show Gist options
  • Select an option

  • Save yusufcakal/c593d8d92619559675ee90b38f932459 to your computer and use it in GitHub Desktop.

Select an option

Save yusufcakal/c593d8d92619559675ee90b38f932459 to your computer and use it in GitHub Desktop.
Helps you easy to tracing logs to request and response via Spring
logging:
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss.SSS} %clr([%thread]){magenta} %yellow([%X{requestId}]) %highlight(%-5level) %cyan(%-40.40logger{40}) - %msg %n"
@Component
public class LoggingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
MDC.put("requestId", "Correlation 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