Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isopropylcyanide/bf1031d9097fda29f4ff9d3870335def to your computer and use it in GitHub Desktop.
Save isopropylcyanide/bf1031d9097fda29f4ff9d3870335def to your computer and use it in GitHub Desktop.
/**
* 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