scala - 如何在接收中记录内部参与者状态?

标签 scala logging akka

对于可以相当简洁地表达的Actor,不得不添加 block ({...})只是为了添加一个日志命令,这令人沮丧。我想在处理消息之前记录我的内部状态,然后在处理消息之后记录 - 这可能吗?

def receive = {
    // I want to log here instead and remove the non-critical logs from below
    //  e.g. log.debug(s"Received $message")
    //       log.debug(s"Internal state is $subscriptions")
    case RegisterChannel(name, owner) => {
      getChannel(name) match {
        case Some(deadChannel: DeadChannel) => {
          subscriptions += (RealChannel(name, Server(owner)) -> subscriptions(deadChannel))
          subscriptions -= deadChannel
          context.watch(owner)
          log.debug(s"Replaced $deadChannel with a real channel $channels")
        }
        case Some(realChannel: RealChannel) =>
          log.error(s"Refusing to use RegisterChannel($name, $owner) due to $realChannel")
        case None => {
          subscriptions += (RealChannel(name, Server(owner)) -> Vector())
          context.watch(owner)
          log.debug(s"Registered a new channel $channels")
        }
      }
    }

    case Terminated(dead) => {
      getRole(dead) match {
        case Some(client: Client) => // Remove subscriptions
          log.debug(s"Received Client Terminated($dead) $client")
          subscriptionsFor(client).foreach { subscription =>
            subscriptions += (subscription._1 -> subscription._2.filterNot(c => c == client))
          }
        case Some(server: Server) => { // Remove any channels
          log.debug(s"Received Server Terminated($dead) $server")
          channelsBy(server).foreach { realChannel =>
            subscriptions += (DeadChannel(realChannel.name) -> subscriptions(realChannel))
            subscriptions -= realChannel
          }
        }
        case None =>
          log.debug(s"Received Terminated($dead) but no channel is registered")
      }
    }
    // I want to log here as well, to see what effect the message had
    //  e.g. log.debug(s"Finished $message")
    //       log.debug(s"Internal state is now $subscriptions")
}

我不确定这是 Akka 特定问题还是 Scala 模式匹配特定问题,所以我标记了两者

编辑:尝试@aepurniet 的答案后,我不知道如何解决编译器错误。接收需要返回 PartialFunction[Any,Unit],但是当 match 不是 => {...} 中的唯一项目时,它似乎正在返回 Any=>AnyRef

// Compiler error because msg=>{...} is not proper type
def receive = msg => { 
    log.info(s"some log")

    msg match {
      case RegisterChannel(name, owner) => {
        getChannel(name) match {
    <snip>

最佳答案

received = { case ... } 实际上是 received = msg => msg match { case ... } 的简写。你可以重写 receive = msg => { log.info(..); msg match { case ... } } 你可能需要额外指定类型。

关于scala - 如何在接收中记录内部参与者状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26063377/

相关文章:

python - 在 Python 中以编程方式启动 HiveThriftServer

logging - 如何获取vlc日志?

java - 抛出异常的记录方法

scala - 在scala中实现生产者消费者的正确方法是什么

akka - 微服务风格和权衡 - Akka 集群 vs Kubernetes vs

scala - 使用 Scala 的 Java 泛型方法

scala - 通过HDFS返回的文件路径获取带有扩展名的文件名

scala - 如何在case语句中引用val?

Python 记录器不遵守设置的级别

akka - 优雅地重启整个 Akka Actor 系统