Module org.slf4j
Package org.slf4j

Class MDCAmbit

java.lang.Object
org.slf4j.MDCAmbit

public class MDCAmbit extends Object

This class assists in the creation and removal (aka closing) of MDC entries.

Typical Usage example:

  MDCAmbit mdca = new MDCAmbit();
  try {
    mdca.put("k0", "v0");
    doSomething();
  } catch (RuntimeException e) {
    // here MDC.get("k0") would return "v0"
  } finally {
    // MDC remove "k0"
    mdca.clear();
  }
 

It is also possible to chain put(java.lang.String, java.lang.String), addKeys(String...) and addKey(String) invocations.

For example:

   MDCAmbit mdca = new MDCAmbit();
   try {
     // assume "k0" was added to MDC at an earlier stage
     mdca.addKey("k0").put("k1", "v1").put("k2, "v2");
     doSomething();
   } finally {
     // MDC remove "k0", "k1", "k2", clear the set of tracked keys
     mdch.clear();
   }
 

The run(Runnable) and call(Callable) methods invoke the run/callable methods of objects passed as parameter in a try/finally block, and afterwards invoking clear() method from within finally.

    DCAmbit mdca = new MDCAmbit();
    Runnable runnable = ...;
    mdca.put("k0", "v0").run(runnable);
 
Since:
2.1.0
  • Constructor Details

  • Method Details

    • put

      public MDCAmbit put(String key, String value)
      Put the key/value couple in the MDC and keep track of the key for later removal by a call to clear() }.
      Parameters:
      key -
      value -
      Returns:
      this instance
    • addKey

      public MDCAmbit addKey(String key)
      Keep track of a key for later removal by a call to clear(). .
      Parameters:
      key -
      Returns:
      this instance
    • addKeys

      public MDCAmbit addKeys(String... keys)
      Keep track of several keys for later removal by a call to clear() .
      Parameters:
      keys -
      Returns:
      this instance
    • run

      public void run(Runnable runnable)
      Run the runnable object passed as parameter within a try/finally block.

      Afterwards, the clear() method will be called within the `finally` block.

      Parameters:
      runnable -
    • call

      public <T> T call(Callable<? extends T> callable) throws Exception
      Invoke the Callable.call() method of the callable object passed as parameter within a try/finally block.

      Afterwards, the clear() method will be invoked within the `finally` block.

      Parameters:
      callable -
      Throws:
      Exception
    • clear

      public void clear()
      Clear tracked keys by calling MDC.remove(java.lang.String) on each key.

      In addition, the set of tracked keys is cleared.

      This method is usually called from within finally statement of a try/catch/finally block