I'm trying to add a requestId
to my web app's logs, as shown here.
public class MDCFilter implements ContainerRequestFilter, ContainerResponseFilter
{
private static final String CLIENT_ID = "client-id";
@Context
protected HttpServletRequest r;
@Override
public void filter(ContainerRequestContext req) throws IOException
{
Optional<String> clientId = Optional.fromNullable(r.getHeader("X-Forwarded-For"));
MDC.put(CLIENT_ID, clientId.or(defaultClientId()));
}
@Override
public void filter(ContainerRequestContext req, ContainerResponseContext resp) throws IOException
{
MDC.remove(CLIENT_ID);
}
private String defaultClientId()
{
return "Direct:" + r.getRemoteAddr();
}
}
The problem with this is that it sets and removes requestId
from MDC
in the above filter. I also log the bodies of the responses my application generates with a WriterInterceptor
. The problem is that, since interceptors run after filters, by the time my WriterInterceptor
executes, there is no requestId in MDC
.
My question is, is it ok to call MDC.clear()
at the end of WriterInterceptor
(which feels somehow hacky), or is there a better way of achieving this?