Search code examples
scalaakkafsm

Instrumenting Akka FSM


I like to take the metrics a FSM needs till it reaches a certain state. Instead of spamming my classes with metrics code I would like to add a trait which overrides certain methods and emits a message when the method is called.

For example:

trait InstrumentedActorFSM[S,D] extends Actor with FSM[S,D] {self: Actor with FSM[S,D] with Logging  =>
  startTimer // start measuring time here with Graphite

  override def stop = {
    stopTimerAndEmitMessage // emit message to graphite
    super.stop
  }
}

Sadly all methods whitin FSM are declared final and can't be overwritten. I could resort to the Cake pattern and embed a FSM an reimplement all calls but that feels quite clumsy. Any good ideas?


Solution

  • You can use onTransition handler like:

    trait InstrumentedActorFSM[S,D] extends Actor with FSM[S,D] { ...
    
      onTransition {
        case _ -> SomeState => stopTimerAndEmitMessage
      }
    
    }