java.lang.Object
org.slf4j.MDCAmbit
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 Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionKeep track of a key for later removal by a call toclear().Keep track of several keys for later removal by a call toclear().<T> TInvoke theCallable.call()method of the callable object passed as parameter within a try/finally block.voidclear()Clear tracked keys by callingMDC.remove(java.lang.String)on each key.Put the key/value couple in the MDC and keep track of the key for later removal by a call toclear()}.voidRun the runnable object passed as parameter within a try/finally block.
-
Constructor Details
-
MDCAmbit
public MDCAmbit()
-
-
Method Details
-
put
Put the key/value couple in the MDC and keep track of the key for later removal by a call toclear()}.- Parameters:
key-value-- Returns:
- this instance
-
addKey
Keep track of a key for later removal by a call toclear(). .- Parameters:
key-- Returns:
- this instance
-
addKeys
Keep track of several keys for later removal by a call toclear().- Parameters:
keys-- Returns:
- this instance
-
run
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
Invoke theCallable.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
Clear tracked keys by callingMDC.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
-