Scala 使用MDC登录流

Scala 使用MDC登录流,scala,log4j,akka-stream,Scala,Log4j,Akka Stream,我正在基于Akka Streams构建一个系统,我希望记录流中的每个步骤/流,并添加一个标识符,以便能够在日志中跟踪通过流的元素 我可以看到流中的log方法采用隐式LoggingAdapter,我发现DiagnosticLoggingAdapter可以采用MDC参数的映射 我的挑战是找出如何获得诊断日志适配器 我尝试了各种方法来获得一个可以获取MDC参数的记录器,但我缺少了一些东西 首先,我刚刚使用了ScalaLogg中的记录器: class testClass()(implicit syste

我正在基于Akka Streams构建一个系统,我希望记录流中的每个步骤/流,并添加一个标识符,以便能够在日志中跟踪通过流的元素

我可以看到流中的log方法采用隐式LoggingAdapter,我发现DiagnosticLoggingAdapter可以采用MDC参数的映射

我的挑战是找出如何获得诊断日志适配器

我尝试了各种方法来获得一个可以获取MDC参数的记录器,但我缺少了一些东西

首先,我刚刚使用了ScalaLogg中的记录器:

class testClass()(implicit system: ActorSystem, mat: ActorMaterializer, ext: ExecutionContext){

  val log = Logger(getClass)

  def doThisFlow: Flow[ElementIn, ElementOut, NotUsed] = Flow[ElementIn].mapAsync(1)(ei => {

        Source.single(ei)
          .log("Starting of the stream")
          .via(someFlow)
          .log("Handling some flow")
          .runWith(Sink.head)
  })
}
这在没有MDC参数的情况下工作

然后,我尝试通过scala日志添加MDC参数,如下所述

但这只是将MDC参数添加到显式编写的日志语句中,而不是流方法log()编写的日志语句中。这是有意义的,因为这种方法使用LoggerTakingImplicit对象而不是LoggingAdapter

然后,我试图通过akka.event.Logging库获得一个LoggingAdapter,其灵感来源于以下描述:

然后,在log()方法中写入日志消息之后,突然打印了通过流的对象

我想弄清楚如何使用getMDC og clearMDC方法获得一个。 谁能解释一下如何获得诊断日志适配器,或者为什么我不能让它工作

class testClass()(implicit system: ActorSystem, mat: ActorMaterializer, ext: ExecutionContext){

  val logger = Logger.takingImplicit[MDCLoggerObject](this.getClass.getName)

  def doThisFlow: Flow[ElementIn, ElementOut, NotUsed] = Flow[ElementIn].mapAsync(1)(ei => {

    implicit val mDCLoggerObject: MDCLoggerObject = MDCLoggerObject("some value", ei.id, ei.name)

        logger.debug("Starting the stream")

        Source.single(ei)
          .log("Starting of the stream")
          .via(someFlow)
          .log("Handling some flow")
          .runWith(Sink.head)
  })
}
class testClass()(implicit system: ActorSystem, mat: ActorMaterializer, ext: ExecutionContext){

  val logging = Logging.getLogger(system.eventStream, "whatever")

    def doThisFlow: Flow[ElementIn, ElementOut, NotUsed] = Flow[ElementIn].mapAsync(1)(ei => {

    Source.single(ei)
      .log("Starting of the stream")
      .via(someFlow)
      .log("Handling some flow")
      .runWith(Sink.head)
  })
}