Akka Logging within a TypedActor


The basic example for an Actor (not TypedActor) that uses logging from the Akka documentation is the following:

class MyActor extends Actor {
  val log = Logging(context.system, this)
  def receive = {
    case "test" => log.info("received test")
    case _      => log.info("received unknown message")
  }
}

So one might think that it is possible to do the same within a TypedActor:

class TypedActorImpl extends TypedActorTrait {
    val log = Logging(TypedActor.context.system, this)

    def squareDontCare(i:Int, i:Int):Unit {
        log.info("Weeeee!")
        i * i // Nobody cares :(
    }
} 

This breaks because “you need to provide an implicit akka.event.LogSource for the type of “this” when you call Logging” (Viktor Klang), and understandably there is no implicit defined for our TypedActorImpl. But don’t despair! There is an implicit that converts an ActorRef to a LogSource, and we can access a TypedActor’s ActorRef by using TypedActor.context.self.

So here’s the complete example:

class TypedActorImpl extends TypedActorTrait {
    val log = Logging(TypedActor.context.system, TypedActor.context.self)

    def squareDontCare(i:Int, i:Int):Unit {
        log.info("Weeeee!")
        i * i // Nobody cares :(
    }
}

Troubleshooting

You probably used something else than TypedActor.context.self for the second parameter of Logging():

error: could not find implicit value for evidence parameter of type akka.event.LogSource[...]

You probably used TypedActor.self instead of TypedActor.context.self for the second parameter of Logging():

error: ambiguous implicit values:
both value fromString in object LogSource of type => akka.event.LogSource[String]
and value fromActor in object LogSource of type => akka.event.LogSource[akka.actor.Actor]
match expected type akka.event.LogSource[Nothing]