All Downloads are FREE. Search and download functionalities are using the official Maven repository.

marquez.logging.MdcPropagating Maven / Gradle / Ivy

There is a newer version: 0.49.0
Show newest version
/*
 * 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();
    };
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy