Created
May 6, 2024 01:57
-
-
Save distantcam/7b97082a5a4fc536146fadfa34b83102 to your computer and use it in GitHub Desktop.
MediatR pipeline for OpenTelemetry Logging
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
public class OpenTelemetryMediatrBehaviour<TRequest, TResponse>(ActivitySource activitySource) : | |
IPipelineBehavior<TRequest, TResponse> | |
where TRequest : notnull | |
{ | |
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken) | |
{ | |
using var activity = activitySource.StartActivity(typeof(TRequest).FullName); | |
activity.SetTag("mediatr.requesttype", typeof(TRequest)); | |
activity.SetTag("mediatr.request", JsonConvert.SerializeObject(request)); | |
activity.SetStartTime(DateTime.UtcNow); | |
try | |
{ | |
var response = await next(); | |
activity.SetEndTime(DateTime.UtcNow); | |
activity.SetTag("mediatr.responsetype", typeof(TResponse)); | |
activity.SetTag("mediatr.response", JsonConvert.SerializeObject(response)); | |
return response; | |
} | |
catch (Exception ex) | |
{ | |
activity.SetStatus(ActivityStatusCode.Error, ex.ToString()); | |
throw; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment