【发布时间】:2020-06-01 06:21:18
【问题描述】:
我围绕 Scala ExecutionContext 编写了一个小型实用程序包装器,以实现跨 Future 实例的 MDC 上下文传输。它按预期工作,但一个不受欢迎的副作用是我们现在似乎没有得到穿过Futures 的堆栈跟踪。如何确保堆栈跟踪与 MDC 一起传播?
这是我的参考代码:
import org.slf4j.MDC
import scala.concurrent.ExecutionContext
import scala.jdk.CollectionConverters._
object MdcOps {
implicit class ExecutionContextExt(value: ExecutionContext) {
def withMdc: ExecutionContext = new MdcExecutionContext(value)
}
def withMdc[A](mdc: Map[String, Any], replace: Boolean)(doIt: => A): A = {
val currentMdcContext = getMdc
val newMdc = if(replace) mdc else mdc ++ currentMdcContext
try { setMdc(newMdc); doIt }
finally { setMdc(currentMdcContext) }
}
def setMdc(mdc: Map[String, Any]): Unit = {
if(mdc.isEmpty) {
MDC.clear()
} else
MDC.setContextMap(mdc.view.mapValues(_.toString).toMap.asJava)
}
def getMdc: Map[String, String] = Option(MDC.getCopyOfContextMap).map(_.asScala.toMap).getOrElse(Map.empty)
}
class MdcExecutionContext(underlying: ExecutionContext, context: Map[String, String] = Map.empty) extends ExecutionContext {
override def prepare(): ExecutionContext = new MdcExecutionContext(underlying, MdcOps.getMdc)
override def execute(runnable: Runnable): Unit = underlying.execute { () =>
MdcOps.withMdc(context, replace = true)(runnable.run())
}
override def reportFailure(t: Throwable): Unit = underlying.reportFailure(t)
}
【问题讨论】: