现在,我被要求在 akka 的 actor 中添加日志记录功能.
Now, I am asked to add logging function in akka's actor.
收到消息后,在处理之前,应将此消息写入日志.并且在发送一条消息之前,应该先记录这条消息.
When a message is received, before it is handled, this message should be written into log. And before a message is sent out, this message should be logged first.
我认为我应该覆盖 Actor 中的 receive 和 send 函数.假设我创建了一个扩展 Actor 的特征 actorlog.而 myActor 类扩展了 actorlog.但是在 myActor 中,我需要覆盖 receive 函数(这似乎会导致问题).所以我很困惑我应该做什么.
I think I should override the receive and send functions in Actor. Suppose I create a trait actorlog which extends Actor. And class myActor extends actorlog. But in myActor, I need to override receive function (it seems it causes problems here). So I am confused what I should do.
附注.我知道 akka 提供日志记录.但是现在我需要自己实现这个功能.
PS. I know akka provides logging. But now I need implement this function by myself.
推荐答案除了这里的其他答案,另一种方法是使用 orElse 将部分函数添加到您的 receive.在该部分函数中,将日志记录放在 isDefinedAt 中,以便在每条消息上调用它.
Besides the other answers here, another approach is to use orElse to prepend a partial function to your receive. In that partial function, put the logging in isDefinedAt so it gets called on every message.
例如:
trait ReceiveLogger { this: Actor with ActorLogging => def logMessage: Receive = new Receive { def isDefinedAt(x: Any) = { log.debug(s"Got a $x") false } def apply(x: Any) = throw new UnsupportedOperationException } } class MyActor extends Actor with ActorLogging with ReceiveLogger { def receive: Receive = logMessage orElse { case ... } }使用orElse 是组成receive 行为的通用方法.在大多数情况下,我正在编写这样的东西:
Using orElse is a general approach for composing receive behavior. In most cases I am composing things like this:
def otherBehavior: Receive = { case OtherMessage => ... } class MyActor extends Actor { def receive = otherBehavior orElse { case ... } }在此演示文稿中可以看到可堆叠特征方法的一个很好的例子:www.slideshare/EvanChan2/akka-inproductionpnw-scala2013
A good example of the stackable traits approach can be seen in this presentation: www.slideshare/EvanChan2/akka-inproductionpnw-scala2013
更多推荐
如何在akka的发送和接收动作中添加日志功能
发布评论