Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A support engineer needs DEBUG logs for one tenant that is having problems, in production, for one hour, without restarting and without turning on DEBUG for all 2,000 requests per second. How would you implement this with logging filters?

Put the tenant id into the MDC at the start of every request, then add a filter that runs before the logger level check and lowers the threshold to DEBUG only when the MDC tenant matches: Log4j2's context-wide DynamicThresholdFilter or Logback's DynamicThresholdFilter or MDCFilter turbo filter. Keep the list of debugged tenants changeable at runtime with an expiry of one hour, and protect the service with a rate limit, no personal data in the debug output and an audit record of who switched it on.

Why this question is asked

Production debugging is where logging design meets real pressure. A customer is unhappy, support needs detail, and the obvious fix, setting the level to DEBUG, would multiply log volume for all 2,000 requests per second and might hurt the very service we are trying to debug. Interviewers ask this scenario to see whether we know that logging frameworks can make decisions per request, and whether we think about the safety around such a switch. In this answer, we will put the tenant into the MDC, configure a per-tenant threshold in both Log4j2 and Logback, see why the filter's position before the level check matters, make the switch changeable at runtime with an expiry, and look at the protections that make it safe to use.

1Put the Tenant Into the MDC

The MDC (Mapped Diagnostic Context, called ThreadContext in Log4j2) is a map stored per thread. Whatever we put there is attached to every log event created on that thread until we remove it. So the first step is to read the tenant id as early as possible in each request and put it in the MDC, and, just as important, to remove it when the request ends. Servlet containers reuse threads, so a value we forget to clear will leak into the next request on that thread.

Java
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
class TenantMdcFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
String tenant = req.getHeader("X-Tenant-Id"); // or from the authenticated principal
try {
if (tenant != null) MDC.put("tenantId", tenant);
chain.doFilter(req, res);
} finally {
MDC.remove("tenantId"); // the thread goes back to the pool clean
}
}
}

For Kafka consumers or scheduled jobs, the same put-and-remove pattern goes around each message or each job run, because there is no servlet filter on that path.

2A Per-Tenant Threshold With Log4j2

Log4j2's DynamicThresholdFilter reads one ThreadContext key and compares the event's level with a threshold chosen by the key's value. For tenants that are not listed, a default threshold applies. Placed at the top of the configuration, as a context-wide filter, it runs before the logger level check.

XML
<Configuration monitorInterval="30">
<DynamicThresholdFilter key="tenantId" defaultThreshold="ERROR"
onMatch="ACCEPT" onMismatch="NEUTRAL">
<KeyValuePair key="acme-gmbh" value="DEBUG"/>
</DynamicThresholdFilter>
<Loggers>
<Logger name="com.shop" level="INFO"/>
<Root level="WARN"><AppenderRef ref="JSON"/></Root>
</Loggers>
</Configuration>
// tenantId=acme-gmbh: log.debug("price rule {}", rule) -> ACCEPT, written although com.shop is INFO
// tenantId=other: log.debug("price rule {}", rule) -> NEUTRAL, then INFO level drops it
// tenantId=other: log.error("failed") -> ACCEPT (at or above ERROR), written

Notice the combination of onMatch=ACCEPT and onMismatch=NEUTRAL. For the debugged tenant, ACCEPT lets the event through and skips the logger level. For everyone else, NEUTRAL hands the decision back to the normal levels, so nothing changes for the other 1,999 requests per second.

3Step 2 With Logback: A TurboFilter

Logback has the same idea as a turbo filter. TurboFilters are attached to the whole logger context and run before the event is created and before the level check. Logback ships its own DynamicThresholdFilter turbo filter keyed on an MDC value, and the simpler MDCFilter can accept everything for one value. If neither fits, a custom TurboFilter of about twenty lines can read a set of tenants from memory and decide.

Java
public class TenantDebugFilter extends TurboFilter {
private final Map<String, Instant> debugUntil = new ConcurrentHashMap<>();
public void enable(String tenant, Duration d) { debugUntil.put(tenant, Instant.now().plus(d)); }
@Override
public FilterReply decide(Marker m, Logger logger, Level level, String fmt, Object[] p, Throwable t) {
String tenant = MDC.get("tenantId");
if (tenant == null) return FilterReply.NEUTRAL;
Instant until = debugUntil.get(tenant);
if (until == null) return FilterReply.NEUTRAL;
if (Instant.now().isAfter(until)) { debugUntil.remove(tenant); return FilterReply.NEUTRAL; } // expired
return level.isGreaterOrEqual(Level.DEBUG) && logger.getName().startsWith("com.shop")
? FilterReply.ACCEPT : FilterReply.NEUTRAL;
}
}

The expiry is built into the filter itself, so even if nobody remembers to switch it off, DEBUG for that tenant ends after one hour.

4Why the Filter Must Run Before the Level Check

This is the detail that decides whether the design is cheap. If we put the tenant filter on an appender instead, the logger level would have to be DEBUG for the events to reach the appender at all. Every DEBUG call for every tenant would then create an event, format its message and travel to the appender, only to be thrown away there. At 2,000 requests per second with perhaps 20 debug lines each, that is 40,000 wasted events per second.

A turbo filter or a context-wide filter avoids this. For a tenant that is not being debugged it returns NEUTRAL after one map lookup, the INFO level drops the call, and no event is ever built. So the cost for everybody else is a map read per log call, which is negligible.

Step throughDeciding one debug call
  1. log.debug(...) on a request thread
  2. Context filter reads tenantId from MDC
  3. Tenant enabled and not expired?
    YesACCEPT: write the DEBUG lineNoNEUTRAL: go to level check
  4. Logger level INFO drops the DEBUG callno event object is created

4 steps in order. Play them, or step through them one at a time.

5Changing the Tenant List at Runtime

Support must be able to switch this on without a restart. There are a few ways. With Log4j2 and monitorInterval, editing the KeyValuePair in a mounted ConfigMap reloads the configuration within the interval, though a reload recreates appenders and the change has no built-in expiry. A cleaner option is a small admin endpoint, protected by authentication, that calls enable(tenant, Duration.ofHours(1)) on the filter. Because the service runs several pods, the endpoint should be driven from a shared source: a feature flag system or a config service that every pod reads, so all instances agree. Whatever the mechanism, the expiry should be mandatory and the maximum duration capped.

6Protecting the Service and the Data

Even for one tenant, debug output can be large. A big tenant might send 300 requests per second, so a BurstFilter in Log4j2, or a rate check inside our custom filter, should cap debug events to something like 500 per second and drop the rest. Debug messages also tend to print whole objects, so the masking rules of the logging setup must apply to them, and developers should know that debug lines are not exempt from data protection. Finally, every switch should be recorded: who enabled DEBUG for which tenant, when, why and until when. Posting that record to the incident or support ticket makes it easy to review later.

7Follow-up questions

What changes when part of the work runs on other threads or virtual threads?

The MDC is stored per thread, so work handed to an executor, a CompletableFuture or a reactive pipeline does not see the tenant id unless we copy it. We can wrap tasks with a decorator that captures MDC.getCopyOfContextMap() and restores it on the worker, use Spring's TaskDecorator for @Async executors, or use Micrometer's context propagation for Reactor. Virtual threads behave like platform threads here: each has its own MDC, so a virtual thread started per task also needs the value copied in, and it is cleared when the virtual thread ends, which removes the leak risk but not the copy step.

Why not just use the Actuator loggers endpoint to set DEBUG for an hour?

Because Actuator changes the level for a logger on all requests, not for one tenant. At 2,000 requests per second that multiplies volume for everyone, costs CPU and storage, and may hide the very problem by making the service slower. Actuator is the right tool when the problem is not tied to one tenant.

How do you make sure the tenant id is trustworthy?

Take it from the authenticated principal or a header that the gateway sets after authentication, not from a header any client can send. Otherwise a client could put another tenant's id in the header and switch on debug output for itself.

8Conclusion

In this answer, we enabled DEBUG for a single tenant without a restart. We put the tenant id into the MDC at the start of each request and cleared it at the end, used a Log4j2 context-wide DynamicThresholdFilter or a Logback turbo filter so the decision happens before the level check and costs almost nothing for other tenants, made the tenant list changeable at runtime with a mandatory one-hour expiry, and protected the service with a rate limit, masking and an audit record.

What to say in the interviewAbout 90 seconds aloud

Open with

First I would make sure every request puts the tenant id into the MDC early, in a servlet filter or interceptor, and removes it in a finally block, and do the same around each Kafka message or job.

Then, if they want more

Then I would add a filter that runs before the logger level check. In Log4j2 that is a context-wide DynamicThresholdFilter keyed on tenantId, with the default threshold left high and a key-value pair that sets DEBUG for the affected tenant, onMatch ACCEPT and onMismatch NEUTRAL.

In Logback it is a turbo filter, either the built-in DynamicThresholdFilter or MDCFilter, or a short custom TurboFilter. The position matters: a turbo or context-wide filter can accept DEBUG while the loggers stay at INFO, and for the other tenants it costs one map lookup and no event is ever built.

If I put the filter on an appender instead, I would need DEBUG on the logger for everyone, which is exactly what we want to avoid at 2,000 requests per second.

To switch it on without a restart, I would expose an authenticated admin action or a feature flag that every pod reads, with an expiry of one hour built into the filter. And I would protect it: a rate limit on debug events, masking still applied, and an audit record of who enabled it, for which tenant and until when.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A support engineer needs DEBUG logs for one tenant that is having problems, in...": https://scrivio-interview-library.netlify.app/java/java-logging/00c5c6972d/