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

编程入门 行业动态 更新时间:2024-10-27 12:30:44
本文介绍了如何在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 中的 receive 和 send 函数.假设我创建了一个扩展 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 ... } }

在此演示文稿中可以看到可堆叠特征方法的一个很好的例子: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 03:15:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628096.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动作   功能   如何在   日志   akka

发布评论

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

>www.elefans.com

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