Adds support for basic instrumentation of MediatR queries and commands.
What does this do?
This library exposes a new Subscriber for ElasticApm to extend its instrumentation capabilities. Internally, the subscriber is responsible for setting up and configuring a listener for events generated by MediatR.Pipeline.Diagnostics. The method of operation is very close to reference source from the ElasticApm code. Some classes needed to be re-implemented because protection levels, at the time of writing, prevent a cleaner re-use of code and logic.
Why would I use this?
If you rely on Elastic APM and utilize MediatR for queries and commands, this library will help you gain visibility to when your handlers are running, and for how long.
How to use Registration is a simple two step process:
- First, add the
DiagnosticPipeline
behavior.services.AddScoped(typeof(IPipelineBehavior<,>), typeof(DiagnosticPipeline<,>));
- It is best to register the pipeline behavior first, before any other behaviors that you may already have. This will allow you to record execution time for not only the handler, but any behaviors that wrap it.
- Next, add the
MediatrDiagnosticsSubscriber
when registering ElasticApm.app.UseElasticApm(Configuration, new HttpDiagnosticsSubscriber(), new MediatrDiagnosticsSubscriber(), new AspNetCoreDiagnosticsSubscriber());
Example In this screenshot, we are calling a sample endpoint within a WeatherForecast controller.
- Code called by controller uses MediatR to send SampleQuery
- SampleQueryHandler is called, pauses for 5 seconds, and sends (and waits for) a SampleCommand
- SampleCommandHandler pauses for 2 seconds and exits
- SampleQueryHandler continues and sends a Sample2Query
- Sample2QueryHandler pauses for 1 second and returns a value
Note that the controller method took a little over 8 seconds, and the flow of execution within MediatR is captured accurately.
Contributions
I welcome any and all suggestions or improvements to the codebase. Thanks for dropping by and hope you find a good use for this library!