【发布时间】:2017-10-02 11:46:04
【问题描述】:
Akka 中的 ActorLogging 和 DiagnosticActorLogging 特征之间有什么区别,您什么时候应该偏爱其中一个?快速查看docs 并不能提供太多指导。
【问题讨论】:
Akka 中的 ActorLogging 和 DiagnosticActorLogging 特征之间有什么区别,您什么时候应该偏爱其中一个?快速查看docs 并不能提供太多指导。
【问题讨论】:
MDC 允许您为记录的消息添加额外的上下文。例如,使用日志记录模式%5p %X{user-id} %m%n,在 mdc 映射中插入 user-id 将替换模板字段中的值 %X{user-id}
DiagnosticActorLogging 让您可以轻松访问mdc,并负责为参与者处理的每条消息设置和清除 mdc。查看DiagnosticActorLogging trait 中的aroundReceive 方法以更好地理解它
override protected[akka] def aroundReceive(receive: Actor.Receive, msg: Any): Unit = try {
log.mdc(mdc(msg))
super.aroundReceive(receive, msg)
} finally {
log.clearMDC()
}
【讨论】:
最简单的解决方法是检查 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()
}
}
基本上,它允许将一些共享的日志数据片段隐式关联到参与者中的每个日志调用,而无需显式添加它们的所有混乱。根据您的应用程序,它可能对主机名、请求 ID、客户端 ID、jar 版本、构建日期、端点等有用。
【讨论】: