Package org.slf4j
Class MDCAmbit
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
-
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> T
Invoke theCallable.call()
method of the callable object passed as parameter within a try/finally block.void
clear()
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()
}.void
Run 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
-