Video in progress

How do you turn on DEBUG logs in prod for just one user or one request, while everything else stays at INFO?

In Logback, with a TurboFilter: DynamicThresholdFilter changes the log level per request depending on a value in MDC. A filter sets a marker in MDC based on a request header or the user ID, and only those requests write DEBUG.

📖 Answer

Switching a whole package to DEBUG under heavy traffic floods the log pipeline. Often it is enough to see the requests of one problem customer.

The Logback configuration:

<turboFilter class="ch.qos.logback.classic.turbo.DynamicThresholdFilter">
  <Key>debugUser</Key>
  <DefaultThreshold>INFO</DefaultThreshold>
  <OnHigherOrEqual>ACCEPT</OnHigherOrEqual>
  <OnLower>NEUTRAL</OnLower>
  <MDCValueLevelPair>
    <value>on</value>
    <level>DEBUG</level>
  </MDCValueLevelPair>
</turboFilter>

If MDC has debugUser=on, the threshold for the request on that thread becomes DEBUG; for everyone else it stays INFO.

A servlet filter sets the marker:

@Component
class DebugFlagFilter extends OncePerRequestFilter {
    private final Set<String> debugUsers; // from configuration or a feature flag

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
                                    FilterChain chain) throws ServletException, IOException {
        boolean on = debugUsers.contains(currentUserId(req));
        if (on) MDC.put("debugUser", "on");
        try {
            chain.doFilter(req, res);
        } finally {
            MDC.remove("debugUser");
        }
    }
}

A TurboFilter runs before the logger level is checked, so DEBUG lines come out for that request even when the logger itself is at INFO.

Things to watch out for: if you accept the marker from an external header (X-Debug: on), accept it only from the internal network or with a signed token, otherwise anyone can blow up your log volume. If MDC isn't carried over to async threads, the marker is lost there too. And don't forget to clean up the list when you are done.