Last active
September 5, 2020 17:01
-
-
Save isopropylcyanide/bf1031d9097fda29f4ff9d3870335def to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* This class delays the logging of request and response events. | |
* @implNote This class uses a thread local to cache request serialization in the form of a builder | |
* If the response received from service passes the supplied predicate, then both request and response | |
* will be logged or else nothing will be logged. | |
*/ | |
public class DelayedRequestResponseLoggingFilter implements ContainerRequestFilter, ContainerResponseFilter, WriterInterceptor { | |
private final ResponseCondition responseCondition; | |
private final ThreadLocal<StringBuilder> requestLogCache = new ThreadLocal<>(); | |
@Override | |
public void filter(ContainerRequestContext requestContext) throws IOException { | |
StringBuilder requestLog = requestResponseBuilder.buildRequestLog(requestContext); | |
//instead of logging here directly, cache the result in the thread local. | |
requestLogCache.set(requestLog); | |
} | |
@Override | |
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { | |
try { | |
int status = responseContext.getStatus(); | |
if (responseCondition.test(status)) { | |
//response matches the user defined predicate..log both requests and responses | |
String requestLog = requestLogCache.get(); | |
log(requestLog); | |
String responseLog = requestResponseBuilder.buildResponseLog(requestContext, responseContext); | |
log(responseLog); | |
} | |
} finally { | |
requestLogCache.remove(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment