【问题标题】:Logging all messages sent to an Akka TestKit TestProbe记录发送到 Akka TestKit TestProbe 的所有消息
【发布时间】:2012-11-16 16:43:42
【问题描述】:

我正在尝试记录由 TestKit TestProbe 接收到的所有消息,这被证明有些困难。我知道文档中的Actor Logging 部分,它说应该将debug.receive 选项与LogginReceive 块结合使用。但是,当我无法控制演员的实施时,这不起作用。

我唯一的想法是将akka.testkit.TestActor 子类化以使用LoggingReceive,然后将TestKit 子类化以使其创建我的TestActor 子类的实例,但这不起作用,因为大多数功能都是私有的到 akka 命名空间(我想这是有充分理由的)。

【问题讨论】:

    标签: scala akka testkit


    【解决方案1】:

    有一个(可能令人惊讶)简单的答案:

    probe.setAutoPilot(new TestActor.AutoPilot {
      def run(sender: ActorRef, msg: Any) = {
        log.debug("whatever")
        this
      }
    })
    

    【讨论】:

    • 可能更简单,但有点神秘。什么是自动驾驶仪?文档对此保持沉默。
    • AutoPilot 现在在文档中,仅供参考。不是最简单的概念,但上面的代码非常简单并且可以解决问题(显然,我只记录发送者和 msg 值而不是“任何”文字)。
    【解决方案2】:

    使用 Ronald 的回答,我写了这个是为了有一种更简单的方法来定义我的探针:

    object LoggingTestProbe {
      def apply()(implicit system: ActorSystem) : TestProbe = {
        val probe = TestProbe()
        probe.setAutoPilot(new TestActor.AutoPilot {
          def run(sender: ActorRef, msg: Any) = {
            val other = sender.path
            val me = probe.ref.path
            system.log.debug(s"$me received $msg from $other")
            this
          }
        })
        probe
      }
    }
    

    有了这个,我使用LoggingTestProbe()而不是TestProbe()来定义我的探针。

    我是 Scala 的新手,所以这可能不是最佳的,但对我来说效果很好。

    【讨论】:

      【解决方案3】:

      抱歉,一开始你的问题有点不对,所以这是我的方法。

      创建一个包装器actor,记录消息:

      class LoggingActor(fac: => Actor) extends Actor {
      
        val underlying = context.system.actorOf(Props(fac))
      
        def receive = {
          LoggingReceive {
            case x ⇒ underlying.tell(x, sender)
          }
        }
      }
      

      然后只需创建您的TestActorRef,并将您的演员包裹在LoggingActor中:

        val echo = TestActorRef(new LoggingActor(new FooActor))
      
        echo ! "hello world"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-14
        • 1970-01-01
        相关资源
        最近更新 更多