Last active
April 8, 2020 17:22
-
-
Save mknet3/c9d94c47373e9b96bb4de21a7a8368d5 to your computer and use it in GitHub Desktop.
Rebus.TraceContext.W3C.Incoming
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
namespace RebusTraceContext | |
{ | |
using System.Diagnostics; | |
using System.Threading.Tasks; | |
using Microsoft.ApplicationInsights; | |
using Microsoft.ApplicationInsights.DataContracts; | |
using Microsoft.Extensions.DependencyInjection; | |
using Rebus.Handlers; | |
using Rebus.Pipeline; | |
public static class ServiceCollectionExtensions | |
{ | |
public static IServiceCollection AddRebusTraceContextDecorator(IServiceCollection services) | |
{ | |
services.Decorate(typeof(IHandleMessages<>), typeof(AddTraceContextDecorator<>)); | |
return services; | |
} | |
} | |
public class AddTraceContextDecorator<TStep> : IHandleMessages<TStep> | |
{ | |
private readonly IHandleMessages<TStep> _handleMessages; | |
private readonly TelemetryClient _telemetryClient; | |
public AddTraceContextDecorator(IHandleMessages<TStep> handleMessages, TelemetryClient telemetryClient) | |
{ | |
_handleMessages = handleMessages; | |
_telemetryClient = telemetryClient; | |
} | |
public async Task Handle(TStep message) | |
{ | |
var context = MessageContext.Current; | |
var activity = new Activity(typeof(TStep).Name); | |
if (context.Message.Headers.TryGetValue("traceparent", out var requestId) | |
|| context.Message.Headers.TryGetValue("Request-Id", out requestId)) | |
{ | |
activity.SetParentId(requestId); | |
if (context.Message.Headers.TryGetValue("tracestate", out var traceState)) | |
{ | |
activity.TraceStateString = traceState; | |
} | |
} | |
using (var operation = _telemetryClient.StartOperation<RequestTelemetry>(activity)) | |
{ | |
await _handleMessages.Handle(message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment