Forked from int128/RequestAndResponseLoggingFilter.java
Last active
September 13, 2020 14:19
-
-
Save tyagiakhilesh/b39290114cd1c33c2d8183edc10fb508 to your computer and use it in GitHub Desktop.
Spring Web filter for logging request and response
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
import lombok.val; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.http.HttpStatus; | |
import org.springframework.http.MediaType; | |
import org.springframework.web.filter.OncePerRequestFilter; | |
import org.springframework.web.util.ContentCachingRequestWrapper; | |
import org.springframework.web.util.ContentCachingResponseWrapper; | |
import javax.servlet.FilterChain; | |
import javax.servlet.ServletException; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
import java.io.IOException; | |
import java.io.UnsupportedEncodingException; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.stream.Stream; | |
/** | |
* Spring Web filter for logging request and response. | |
* | |
* @see org.springframework.web.filter.AbstractRequestLoggingFilter | |
* @see ContentCachingRequestWrapper | |
* @see ContentCachingResponseWrapper | |
*/ | |
public class RequestAndResponseLoggingFilter extends OncePerRequestFilter { | |
private static final Logger log = LoggerFactory.getLogger(RequestAndResponseLoggingFilter.class); | |
private static final List<MediaType> VISIBLE_TYPES = Arrays.asList( | |
MediaType.valueOf("text/*"), | |
MediaType.APPLICATION_FORM_URLENCODED, | |
MediaType.APPLICATION_JSON, | |
MediaType.APPLICATION_XML, | |
MediaType.valueOf("application/*+json"), | |
MediaType.valueOf("application/*+xml"), | |
MediaType.MULTIPART_FORM_DATA | |
); | |
@Override | |
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) | |
throws ServletException, IOException { | |
if (isAsyncDispatch(request)) { | |
filterChain.doFilter(request, response); | |
} else { | |
doFilterWrapped(wrapRequest(request), wrapResponse(response), filterChain); | |
} | |
} | |
protected void doFilterWrapped(ContentCachingRequestWrapper request, ContentCachingResponseWrapper response, | |
FilterChain filterChain) throws ServletException, IOException { | |
try { | |
filterChain.doFilter(request, response); | |
} finally { | |
afterRequest(request, response); | |
response.copyBodyToResponse(); | |
} | |
} | |
protected void afterRequest(ContentCachingRequestWrapper request, ContentCachingResponseWrapper response) { | |
if (log.isInfoEnabled()) { | |
final StringBuilder sb = new StringBuilder(); | |
logRequestHeader(request, "> ", sb); | |
logRequestBody(request, "> ", sb); | |
logResponse(response, "< ", sb); | |
log.info("{}", sb); | |
} | |
} | |
private static void logRequestHeader(ContentCachingRequestWrapper request, String prefix, StringBuilder sb) { | |
val queryString = request.getQueryString(); | |
sb.append(System.lineSeparator()); | |
if (queryString == null) { | |
sb.append(prefix).append(" ").append(request.getMethod()).append(" ") | |
.append(request.getRequestURI()).append(" ").append(System.lineSeparator()); | |
} else { | |
sb.append(prefix).append(" ").append(request.getMethod()).append(" ") | |
.append(request.getRequestURI()).append("?").append(queryString).append(System.lineSeparator()); | |
} | |
Collections.list(request.getHeaderNames()).forEach(headerName -> | |
Collections.list(request.getHeaders(headerName)).forEach(headerValue -> | |
sb.append(prefix).append(" ").append(headerName).append(" ") | |
.append(headerValue).append(System.lineSeparator()))); | |
sb.append(prefix); | |
} | |
private static void logRequestBody(ContentCachingRequestWrapper request, String prefix, StringBuilder sb) { | |
val content = request.getContentAsByteArray(); | |
if (content.length > 0) { | |
logContent(content, request.getContentType(), request.getCharacterEncoding(), prefix, sb); | |
} | |
} | |
private static void logResponse(ContentCachingResponseWrapper response, String prefix, StringBuilder sb) { | |
val status = response.getStatus(); | |
sb.append(System.lineSeparator()); | |
sb.append(prefix).append(" ").append(status).append(" ") | |
.append(HttpStatus.valueOf(status).getReasonPhrase()).append(System.lineSeparator()); | |
response.getHeaderNames().forEach(headerName -> | |
response.getHeaders(headerName).forEach(headerValue -> | |
sb.append(prefix).append(" ").append(headerName).append(":") | |
.append(headerValue).append(System.lineSeparator()))); | |
sb.append(prefix); | |
val content = response.getContentAsByteArray(); | |
if (content.length > 0) { | |
logContent(content, response.getContentType(), response.getCharacterEncoding(), prefix, sb); | |
} | |
} | |
private static void logContent(byte[] content, String contentType, String contentEncoding, String prefix, StringBuilder sb) { | |
val mediaType = MediaType.valueOf(contentType); | |
val visible = VISIBLE_TYPES.stream().anyMatch(visibleType -> visibleType.includes(mediaType)); | |
if (visible) { | |
try { | |
val contentString = new String(content, contentEncoding); | |
sb.append(System.lineSeparator()); | |
Stream.of(contentString.split("\r\n|\r|\n")).forEach(line -> sb.append(prefix).append(line).append(System.lineSeparator())); | |
} catch (UnsupportedEncodingException e) { | |
log.info("{} [{} bytes content]", prefix, content.length); | |
} | |
} else { | |
log.info("{} [{} bytes content]", prefix, content.length); | |
} | |
} | |
private static ContentCachingRequestWrapper wrapRequest(HttpServletRequest request) { | |
if (request instanceof ContentCachingRequestWrapper) { | |
return (ContentCachingRequestWrapper) request; | |
} else { | |
return new ContentCachingRequestWrapper(request); | |
} | |
} | |
private static ContentCachingResponseWrapper wrapResponse(HttpServletResponse response) { | |
if (response instanceof ContentCachingResponseWrapper) { | |
return (ContentCachingResponseWrapper) response; | |
} else { | |
return new ContentCachingResponseWrapper(response); | |
} | |
} | |
} |
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
2020-09-13 19:49:19,706 91f3cbd2-7473-4f2e-af5b-1621d9cb915a [qtp1652764753-205] INFO c.d.f.RequestAndResponseLoggingFilter68 - | |
> POST /internal/api/v1/logger | |
> Accept */* | |
> User-Agent curl/7.54.0 | |
> Host localhost:8080 | |
> Content-Length 101 | |
> Content-Type application/json | |
> | |
> { "logLevel": "DEBUG", "packageName": "org.springframework.web.filter.CommonsRequestLoggingFilter"} | |
< 200 OK | |
< Date:Sun, 13 Sep 2020 14:19:19 GMT | |
< Content-Type:application/json | |
< | |
< "Success" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment