|
| 1 | +# Workflow Core 3.4.0 |
| 2 | + |
| 3 | +## Execute Workflow Middleware |
| 4 | + |
| 5 | +These middleware get run after each workflow execution and can be used to perform additional actions or build metrics/statistics for all workflows in your app. |
| 6 | + |
| 7 | +The following example illustrates how you can use a execute workflow middleware to build [prometheus](https://prometheus.io/) metrics. |
| 8 | + |
| 9 | +Note that you use `WorkflowMiddlewarePhase.ExecuteWorkflow` to specify that it runs after each workflow execution. |
| 10 | + |
| 11 | +**Important:** You should call `next` as part of the workflow middleware to ensure that the next workflow in the chain runs. |
| 12 | + |
| 13 | +```cs |
| 14 | +public class MetricsMiddleware : IWorkflowMiddleware |
| 15 | +{ |
| 16 | + private readonly ConcurrentHashSet<string>() _suspendedWorkflows = |
| 17 | + new ConcurrentHashSet<string>(); |
| 18 | + |
| 19 | + private readonly Counter _completed; |
| 20 | + private readonly Counter _suspended; |
| 21 | + |
| 22 | + public MetricsMiddleware() |
| 23 | + { |
| 24 | + _completed = Prometheus.Metrics.CreateCounter( |
| 25 | + "workflow_completed", "Workflow completed"); |
| 26 | + |
| 27 | + _suspended = Prometheus.Metrics.CreateCounter( |
| 28 | + "workflow_suspended", "Workflow suspended"); |
| 29 | + } |
| 30 | + |
| 31 | + public WorkflowMiddlewarePhase Phase => |
| 32 | + WorkflowMiddlewarePhase.ExecuteWorkflow; |
| 33 | + |
| 34 | + public Task HandleAsync( |
| 35 | + WorkflowInstance workflow, |
| 36 | + WorkflowDelegate next) |
| 37 | + { |
| 38 | + switch (workflow.Status) |
| 39 | + { |
| 40 | + case WorkflowStatus.Complete: |
| 41 | + if (_suspendedWorkflows.TryRemove(workflow.Id)) |
| 42 | + { |
| 43 | + _suspended.Dec(); |
| 44 | + } |
| 45 | + _completed.Inc(); |
| 46 | + break; |
| 47 | + case WorkflowStatus.Suspended: |
| 48 | + _suspended.Inc(); |
| 49 | + break; |
| 50 | + } |
| 51 | + |
| 52 | + return next(); |
| 53 | + } |
| 54 | +} |
| 55 | +``` |
0 commit comments