| | | 1 | | using System.Diagnostics; |
| | | 2 | | using Elsa.Workflows.Pipelines.ActivityExecution; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | |
| | | 5 | | namespace Elsa.Workflows.Middleware.Activities; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// An activity execution middleware component that logs information about the activity being executed. |
| | | 9 | | /// </summary> |
| | | 10 | | public class LoggingMiddleware : IActivityExecutionMiddleware |
| | | 11 | | { |
| | | 12 | | private readonly ActivityMiddlewareDelegate _next; |
| | | 13 | | private readonly ILogger _logger; |
| | | 14 | | private readonly Stopwatch _stopwatch; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Constructor. |
| | | 18 | | /// </summary> |
| | | 19 | | public LoggingMiddleware(ActivityMiddlewareDelegate next, ILogger<LoggingMiddleware> logger) |
| | | 20 | | { |
| | | 21 | | _next = next; |
| | | 22 | | _logger = logger; |
| | | 23 | | _stopwatch = new(); |
| | | 24 | | } |
| | | 25 | | |
| | | 26 | | /// <inheritdoc /> |
| | | 27 | | public async ValueTask InvokeAsync(ActivityExecutionContext context) |
| | | 28 | | { |
| | | 29 | | if (!_logger.IsEnabled(LogLevel.Information)) |
| | | 30 | | { |
| | | 31 | | await _next(context); |
| | | 32 | | return; |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | var activity = context.Activity; |
| | | 36 | | _logger.LogInformation("Executing activity {ActivityId}", activity.Id); |
| | | 37 | | _stopwatch.Restart(); |
| | | 38 | | await _next(context); |
| | | 39 | | _stopwatch.Stop(); |
| | | 40 | | _logger.LogInformation("Executed activity {ActivityId} in {Elapsed}", activity.Id, _stopwatch.Elapsed); |
| | | 41 | | } |
| | | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// Extends <see cref="IActivityExecutionPipelineBuilder"/> to install the <see cref="LoggingMiddleware"/> component. |
| | | 46 | | /// </summary> |
| | | 47 | | public static class LoggingMiddlewareExtensions |
| | | 48 | | { |
| | | 49 | | /// <summary> |
| | | 50 | | /// Installs the <see cref="LoggingMiddleware"/> component. |
| | | 51 | | /// </summary> |
| | 0 | 52 | | public static IActivityExecutionPipelineBuilder UseLogging(this IActivityExecutionPipelineBuilder pipelineBuilder) = |
| | | 53 | | } |