如何在akka中发送和接收动作中添加日志记录功能

编程入门 行业动态 更新时间:2024-10-09 18:17:08
本文介绍了如何在akka中发送和接收动作中添加日志记录功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

现在,我被要求在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 ... } }

在本演示中可以看到可堆叠特征方法的一个很好的例子: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中发送和接收动作中添加日志记录功能

本文发布于:2023-11-25 10:13:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629347.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动作   功能   如何在   日志   akka

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!