Created
July 18, 2019 13:22
-
-
Save ramonsmits/6fca2172074b4cd66dd511bfcc562981 to your computer and use it in GitHub Desktop.
NServiceBus Machine Latency Windows Performance Counter Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Concurrent; | |
using System.Diagnostics; | |
using System.Threading.Tasks; | |
using NServiceBus; | |
using NServiceBus.Pipeline; | |
class OriginatingMachineLatencyBehavior : Behavior<IIncomingPhysicalMessageContext> | |
{ | |
ConcurrentDictionary<string, (PerformanceCounter Counter, PerformanceCounter Base)> machineCounters = new ConcurrentDictionary<string, (PerformanceCounter,PerformanceCounter)>(); | |
const string Category = "NServiceBus Machine Latency Sample"; | |
const string LatencyDurationKey = "Latency Duration"; | |
const string LatencyDurationBaseKey = LatencyDurationKey + "Base"; | |
public OriginatingMachineLatencyBehavior() | |
{ | |
if (PerformanceCounterCategory.Exists(Category)) | |
{ | |
return; | |
} | |
var counterCreationDataCollection = new CounterCreationDataCollection | |
{ | |
new CounterCreationData(LatencyDurationKey, "Time between sending and fetching the message. Requires all system clocks to be synchronized!", PerformanceCounterType.AverageTimer32), | |
new CounterCreationData(LatencyDurationBaseKey, string.Empty, PerformanceCounterType.AverageBase) | |
}; | |
PerformanceCounterCategory.Create(Category, "Sample showing how to monitor the time between sending and fetching a message just before invoking the handlers (excluding processing time).", PerformanceCounterCategoryType.MultiInstance, counterCreationDataCollection); | |
} | |
public override Task Invoke(IIncomingPhysicalMessageContext context, Func<Task> next) | |
{ | |
var headers = context.MessageHeaders; | |
var originatingMachine = headers[Headers.OriginatingMachine]; | |
var timeSent = DateTimeExtensions.ToUtcDateTime(headers[Headers.TimeSent]); | |
var counter = machineCounters.GetOrAdd(originatingMachine, k => (new PerformanceCounter(Category, LatencyDurationKey, originatingMachine, false),new PerformanceCounter(Category, LatencyDurationBaseKey, originatingMachine, false))); | |
var duration = DateTime.UtcNow - timeSent; | |
var performanceCounterTicks = duration.Ticks * Stopwatch.Frequency / TimeSpan.TicksPerSecond; | |
counter.Counter.IncrementBy(duration.Ticks); | |
counter.Base.Increment(); | |
return next(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment