问题描述
现在,我被要求在akka的演员中添加日志记录功能。
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.
我想我应该覆盖接收
和 send
函数。假设我创建了一个特征 actorlog
,它扩展了 Actor
。类 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.
PS。我知道akka提供日志记录。但是,现在我需要自己实现此功能。
PS. I know akka provides logging. But now I need implement this function by myself.
推荐答案
除了这里的其他答案,另一种方法是使用 orElse
为您的接收
附加部分函数。在该部分函数中,将日志记录放入 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
是构成接收
行为的通用方法。在大多数情况下,我会编写如下内容:
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 ...
}
}
在本演示中可以看到可堆叠特征方法的一个很好的例子:
A good example of the stackable traits approach can be seen in this presentation: http://www.slideshare.net/EvanChan2/akka-inproductionpnw-scala2013
这篇关于如何在akka中发送和接收动作中添加日志记录功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!