-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimingBehavior.cs
More file actions
60 lines (52 loc) · 1.97 KB
/
Copy pathTimingBehavior.cs
File metadata and controls
60 lines (52 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System.Diagnostics;
using NServiceBus.Pipeline;
using Serilog;
namespace ClearMeasure.HostedEndpoint.Infrastructure.Behaviors;
/// <summary>
/// NServiceBus pipeline behavior that logs handler execution time with Application Insights metrics.
/// </summary>
public class TimingBehavior : Behavior<IInvokeHandlerContext>
{
private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TimingBehavior"/> class.
/// </summary>
/// <param name="logger">The Serilog logger instance.</param>
public TimingBehavior(ILogger logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// <summary>
/// Invokes the behavior and logs the handler execution time.
/// </summary>
/// <param name="context">The handler context.</param>
/// <param name="next">The next step in the pipeline.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public override async Task Invoke(IInvokeHandlerContext context, Func<Task> next)
{
var stopwatch = Stopwatch.StartNew();
var messageType = context.MessageBeingHandled.GetType().Name;
var handlerType = context.MessageHandler.HandlerType.Name;
try
{
await next();
stopwatch.Stop();
_logger.Information(
"Handler {HandlerType} processed message {MessageType} in {ElapsedMilliseconds}ms",
handlerType,
messageType,
stopwatch.ElapsedMilliseconds);
}
catch (Exception ex)
{
stopwatch.Stop();
_logger.Error(
ex,
"Handler {HandlerType} failed to process message {MessageType} after {ElapsedMilliseconds}ms",
handlerType,
messageType,
stopwatch.ElapsedMilliseconds);
throw;
}
}
}