Class RequestScopedMdc

java.lang.Object
com.linecorp.armeria.common.logging.RequestScopedMdc

public final class RequestScopedMdc extends Object
Provides the access to request-scoped MDC properties. All properties set via the access methods in this class are bound to a RequestContext, unlike the traditional thread-local MDC properties.

Updating the request-scoped context map

Update the request-scoped context map using put(RequestContext, String, String), putAll(RequestContext, Map), remove(RequestContext, String) and clear(RequestContext):


 RequestContext ctx = ...;
 RequestScopedMdc.put(ctx, "transactionId", "1234");
 RequestScopedMdc.putAll(ctx, Map.of("foo", "1", "bar", "2"));
 

Transferring thread-local properties

Use copy(RequestContext, String) or copyAll(RequestContext) to copy some or all of thread-local MDC properties to the request-scoped context map:


 RequestContext ctx = ...;
 MDC.put("transactionId", "1234");
 RequestScopedMdc.copy(ctx, "transactionId");
 

Retrieving a value from the request-scoped context map

You can explicitly retrieve request-scoped properties using get(RequestContext, String) or getAll(RequestContext):


 RequestContext ctx = ...;
 String transactionId = RequestScopedMdc.get(ctx, "transactionId");
 

RequestScopedMdc replaces SLF4J's underlying MDCAdapter implementation so that MDC.get(String) and MDC.getCopyOfContextMap() look into the request-scoped context map before the thread-local context map:


 RequestContext ctx = ...;
 RequestScopedMdc.put(ctx, "transactionId", "1234");
 try (SafeCloseable ignored = ctx.push()) {
     assert MDC.get("transactionId").equals("1234");

     // A request-scoped property always gets higher priority:
     MDC.put("transactionId", "5678");
     assert MDC.get("transactionId").equals("1234");
 }

 // Now using the thread-local property
 // because not in a request scope anymore
 assert MDC.get("transactionId").equals("5678");