Search code examples
loggingakkamdc

When to use DiagnosticActorLogging instead of ActorLogging traits in Akka?


What is the difference between ActorLogging and DiagnosticActorLogging traits in Akka and when should you favor one over the other? A quick look at the docs doesn't provide much guidance.


Solution

  • MDC allows you to add additional context to messages you log. For example, with logging pattern %5p %X{user-id} %m%n, inserting user-id in mdc map will substitute the value in the template field %X{user-id}

    DiagnosticActorLogging provides you an easy access to mdc and takes care of setting and clearing mdc for each message processed by the actor. Take a look at aroundReceive method in DiagnosticActorLogging trait to understand it better

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