|
| 1 | +using Microsoft.ApplicationInsights; |
| 2 | +using System.Diagnostics; |
| 3 | + |
| 4 | +namespace Microsoft.FeatureManagement.Telemetry.ApplicationInsights |
| 5 | +{ |
| 6 | + /// <summary> |
| 7 | + /// Listens to <see cref="Activity"/> events from feature management and sends them to Application Insights. |
| 8 | + /// </summary> |
| 9 | + internal sealed class ApplicationInsightsEventPublisher : IDisposable |
| 10 | + { |
| 11 | + private readonly TelemetryClient _telemetryClient; |
| 12 | + private readonly ActivityListener _activityListener; |
| 13 | + |
| 14 | + /// <summary> |
| 15 | + /// Initializes a new instance of the <see cref="ApplicationInsightsEventPublisher"/> class. |
| 16 | + /// </summary> |
| 17 | + /// <param name="telemetryClient">The Application Insights telemetry client.</param> |
| 18 | + public ApplicationInsightsEventPublisher(TelemetryClient telemetryClient) |
| 19 | + { |
| 20 | + _telemetryClient = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient)); |
| 21 | + |
| 22 | + _activityListener = new ActivityListener |
| 23 | + { |
| 24 | + ShouldListenTo = (activitySource) => activitySource.Name == "Microsoft.FeatureManagement", |
| 25 | + Sample = (ref ActivityCreationOptions<ActivityContext> options) => ActivitySamplingResult.AllData, |
| 26 | + ActivityStopped = (activity) => |
| 27 | + { |
| 28 | + ActivityEvent? evaluationEvent = activity.Events.FirstOrDefault((activityEvent) => activityEvent.Name == "feature_flag"); |
| 29 | + |
| 30 | + if (evaluationEvent.HasValue && evaluationEvent.Value.Tags.Any()) |
| 31 | + { |
| 32 | + HandleFeatureFlagEvent(evaluationEvent.Value); |
| 33 | + } |
| 34 | + } |
| 35 | + }; |
| 36 | + |
| 37 | + ActivitySource.AddActivityListener(_activityListener); |
| 38 | + } |
| 39 | + |
| 40 | + /// <summary> |
| 41 | + /// Disposes the resources used by the <see cref="ApplicationInsightsEventPublisher"/>. |
| 42 | + /// </summary> |
| 43 | + public void Dispose() |
| 44 | + { |
| 45 | + _activityListener.Dispose(); |
| 46 | + } |
| 47 | + |
| 48 | + private void HandleFeatureFlagEvent(ActivityEvent activityEvent) |
| 49 | + { |
| 50 | + var properties = new Dictionary<string, string>(); |
| 51 | + |
| 52 | + foreach (var tag in activityEvent.Tags) |
| 53 | + { |
| 54 | + properties[tag.Key] = tag.Value?.ToString(); |
| 55 | + } |
| 56 | + |
| 57 | + _telemetryClient.TrackEvent("FeatureEvaluation", properties); |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments