Log how long it took for Sagas with multiple handlers to be completed

I have the following scenario: there are 20 sagas, and each saga has 3 or more handlers. The goal is to log the start time when a saga begins and record the end time when the saga is completed or timed out.

The question is whether there’s a way to accomplish this without modifying the code within the sagas. For instance, can a decorator be used to accomplish this? I can imagine that the saga data classes should be extended with Start and End DateTime properties, but that should be the only change.

Thanks in advance.

Welcome to the Particular discussion group, @sidiki30.

I’m thinking out loud, and I haven’t tested my idea. In theory, you could be adding a pipeline behavior (IInvokeHandlerContext) that intercepts saga handling without changing anything in the sagas. Your code inside the behavior will look like the following snippet:

class CaptureSagaStats : Behavior<IInvokeHandlerContext>
{
   public override async Task Invoke(IInvokeHandlerContext context, Func<Task> next)
   {
      await next();
      
      // After the next, if the message is for a saga,
      // the saga has been invoked and is available in the context
      if (context.Extensions.TryGet(out ActiveSagaInstance saga))
      {
         //Use the saga information
      };
   }
}

The saga instance lets you know if it’s a new saga if it’s completed, its type, and other information.

Let me know if this helps,
.m

Thanks @mauroservienti, for the reply. I also considered using the Behaviour but was unsure how to check when the Saga started and ended. I will do some experiments to understand this better.

the ActiveSagaInstance type has two properties you can use for that: IsNew and IsCompleted. When IsNew is true, it’ll be your start time. When IsCompleted is true, it’ll be the end time.

@sidiki30, one additional option to consider, if you don’t need those numbers programmatically, is to use the Platform capabilities through the sagas audit plugin.

The plugin will transparently monitor endpoints and report back saga changes to ServiceControl. In ServiceInsight, you can see the start and end times of the sagas you’re monitoring/interested in.

Thanks @mauroservienti; we are using Application Insights and Ligz.io to collect and visualize the logs. Hence, the preference is to use behavior to achieve this.