marquez.logging.MdcPropagating Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of marquez-api Show documentation
Show all versions of marquez-api Show documentation
Collect, aggregate, and visualize a data ecosystem's metadata
/*
* Copyright 2018-2023 contributors to the Marquez project
* SPDX-License-Identifier: Apache-2.0
*/
package marquez.logging;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.slf4j.MDC;
/**
* MDC uses ThreadLocal to store the context, and this is not propagated when the logic runs in
* separate thread. This class provides static wrapper methods to propagate the MDC context to the
* thread where the logic runs.
*/
public class MdcPropagating {
public static Supplier withMdc(Supplier supplier) {
Map mdcContext = MDC.getCopyOfContextMap();
return () -> {
if (mdcContext != null) {
MDC.setContextMap(mdcContext);
}
return supplier.get();
};
}
public static Consumer withMdc(Consumer consumer) {
Map mdcContext = MDC.getCopyOfContextMap();
return (t) -> {
if (mdcContext != null) {
MDC.setContextMap(mdcContext);
}
consumer.accept(t);
};
}
public static Runnable withMdc(Runnable runnable) {
Map mdcContext = MDC.getCopyOfContextMap();
return () -> {
if (mdcContext != null) {
MDC.setContextMap(mdcContext);
}
runnable.run();
};
}
}