-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimingBehavior.cs
More file actions
63 lines (53 loc) · 1.93 KB
/
Copy pathTimingBehavior.cs
File metadata and controls
63 lines (53 loc) · 1.93 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
61
62
63
using NServiceBus.Pipeline;
using Serilog;
using System.Diagnostics;
namespace ClearMeasure.HostedEndpoint.Behaviors;
/// <summary>
/// NServiceBus pipeline behavior that captures and logs handler execution timing 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>
/// Invoked when a message is being handled.
/// </summary>
public override async Task Invoke(IInvokeHandlerContext context, Func<Task> next)
{
var stopwatch = Stopwatch.StartNew();
var messageType = context.MessageBeingHandled.GetType().Name;
var handlerType = context.MessageHandler.Instance.GetType().Name;
try
{
_logger.Information(
"Handler {HandlerType} starting to process message {MessageType}",
handlerType,
messageType);
await next();
stopwatch.Stop();
_logger.Information(
"Handler {HandlerType} completed processing message {MessageType} in {ElapsedMilliseconds}ms",
handlerType,
messageType,
stopwatch.ElapsedMilliseconds);
}
catch (Exception ex)
{
stopwatch.Stop();
_logger.Error(
ex,
"Handler {HandlerType} failed processing message {MessageType} after {ElapsedMilliseconds}ms",
handlerType,
messageType,
stopwatch.ElapsedMilliseconds);
throw;
}
}
}