如何在akka的发送和接收动作中添加日志功能 [英] how to add logging function in sending and receiving action in akka

查看:22
本文介绍了如何在akka的发送和接收动作中添加日志功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我被要求在 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 中的 receivesend 函数.假设我创建了一个扩展 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 ...
  }
} 

在此演示文稿中可以看到可堆叠特征方法的一个很好的例子:http://www.slideshare.net/EvanChan2/akka-inproductionpnw-scala2013

A good example of the stackable traits approach can be seen in this presentation: http://www.slideshare.net/EvanChan2/akka-inproductionpnw-scala2013

这篇关于如何在akka的发送和接收动作中添加日志功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆