何时在 Akka 中使用 DiagnosticActorLogging 而不是 ActorLogging 特征?

When to use DiagnosticActorLogging instead of ActorLogging traits in Akka?

Akka 中的 ActorLoggingDiagnosticActorLogging 特征有什么区别,什么时候应该偏爱其中一个?快速浏览 docs 并没有提供太多指导。

找出它的最简单方法是检查 DiagnosticActorLogging 来源:

/**
 * Scala API: Mix in DiagnosticActorLogging into your Actor to easily obtain a reference to a logger with MDC support,
 * which is available under the name "log".
 * In the example bellow "the one who knocks" will be available under the key "iam" for using it in the logback pattern.
 *
 * {{{
 * class MyActor extends Actor with DiagnosticActorLogging {
 *
 *   override def mdc(currentMessage: Any): MDC = {
 *     Map("iam", "the one who knocks")
 *   }
 *
 *   def receive = {
 *     case "pigdog" => log.info("We've got yet another pigdog on our hands")
 *   }
 * }
 * }}}
 */
trait DiagnosticActorLogging extends Actor {
  import akka.event.Logging._
  val log = akka.event.Logging(this)
  def mdc(currentMessage: Any): MDC = emptyMDC

  override protected[akka] def aroundReceive(receive: Actor.Receive, msg: Any): Unit = try {
    log.mdc(mdc(msg))
    super.aroundReceive(receive, msg)
  } finally {
    log.clearMDC()
  }
}

基本上,它允许将一些共享的日志记录数据片段隐式关联到 actor 中的每个日志记录调用,而无需显式添加它们的所有混乱。根据您的应用程序,它可能对主机名、请求 ID、客户端 ID、jar 版本、构建日期、端点等有用。

MDC 允许您向记录的消息添加额外的上下文。例如,使用日志模式 %5p %X{user-id} %m%n,在 mdc 映射中插入 user-id 将替换模板字段中的值 %X{user-id}

DiagnosticActorLogging 使您可以轻松访问 mdc 并负责为 actor 处理的每条消息设置和清除 mdc。查看 DiagnosticActorLogging 特征中的 aroundReceive 方法以更好地理解它

override protected[akka] def aroundReceive(receive: Actor.Receive, msg: Any): Unit = try {
    log.mdc(mdc(msg))
    super.aroundReceive(receive, msg)
  } finally {
    log.clearMDC()
  }