Where to clear the requestId from MDC
Asked Answered
T

1

8

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?

Tongs answered 17/3, 2016 at 10:48 Comment(1)
I'm having the exact same question, did you find a solution yet?Disobedience
H
0

I'm having the same problem. This is how it currently works in code I'm developing

@Order(Ordered.HIGHEST_PRECEDENCE)
public final class RequestFilter implements Filter {
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
      //stuff
      chain.doFilter(request, response);
    } finally {
      // this clears a specific entry from the MDC but not the entire MDC
      RequestContext.clear();
    }
  }
}

I could clear the entire MDC in the finally block here...but I don't know when Spring logs exceptions. Would I be clearing too early? My new plan is to clear the MDC when I start a request.

I'm not sure if this is a full answer, but clearing the MDC in my highest precedence filter should work.

Houseless answered 27/6, 2019 at 15:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.