diff --git a/src/Microsoft.FeatureManagement.Telemetry.ApplicationInsights/ApplicationInsightsTelemetryPublisher.cs b/src/Microsoft.FeatureManagement.Telemetry.ApplicationInsights/ApplicationInsightsTelemetryPublisher.cs new file mode 100644 index 00000000..02aed91a --- /dev/null +++ b/src/Microsoft.FeatureManagement.Telemetry.ApplicationInsights/ApplicationInsightsTelemetryPublisher.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// +using Microsoft.ApplicationInsights; + +namespace Microsoft.FeatureManagement.Telemetry.ApplicationInsights +{ + /// + /// Used to publish data from evaluation events to Application Insights + /// + public class ApplicationInsightsTelemetryPublisher : ITelemetryPublisher + { + private const string _eventName = "FeatureEvaluation"; + private readonly TelemetryClient _telemetryClient; + + public ApplicationInsightsTelemetryPublisher(TelemetryClient telemetryClient) + { + _telemetryClient = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient)); + } + + /// + /// Publishes a custom event to Application Insights using data from the given evaluation event. + /// + /// The event to publish. + /// A cancellation token. + /// Returns a ValueTask that represents the asynchronous operation + public ValueTask PublishEvent(EvaluationEvent evaluationEvent, CancellationToken cancellationToken) + { + ValidateEvent(evaluationEvent); + + FeatureDefinition featureDefinition = evaluationEvent.FeatureDefinition; + + Dictionary properties = new Dictionary() + { + { "FeatureName", featureDefinition.Name }, + { "IsEnabled", evaluationEvent.IsEnabled.ToString() } + }; + + if (evaluationEvent.Variant != null) + { + properties["Variant"] = evaluationEvent.Variant.Name; + } + + if (featureDefinition.TelemetryMetadata != null) + { + foreach (KeyValuePair kvp in featureDefinition.TelemetryMetadata) + { + properties[kvp.Key] = kvp.Value; + } + } + + _telemetryClient.TrackEvent(_eventName, properties); + + return new ValueTask(); + } + + private void ValidateEvent(EvaluationEvent evaluationEvent) + { + if (evaluationEvent == null) + { + throw new ArgumentNullException(nameof(evaluationEvent)); + } + + if (evaluationEvent.FeatureDefinition == null) + { + throw new ArgumentNullException(nameof(evaluationEvent.FeatureDefinition)); + } + } + } +} \ No newline at end of file diff --git a/src/Microsoft.FeatureManagement.Telemetry.ApplicationInsights/Microsoft.FeatureManagement.Telemetry.ApplicationInsights.csproj b/src/Microsoft.FeatureManagement.Telemetry.ApplicationInsights/Microsoft.FeatureManagement.Telemetry.ApplicationInsights.csproj new file mode 100644 index 00000000..ea1077cb --- /dev/null +++ b/src/Microsoft.FeatureManagement.Telemetry.ApplicationInsights/Microsoft.FeatureManagement.Telemetry.ApplicationInsights.csproj @@ -0,0 +1,17 @@ + + + + net6.0 + enable + enable + + + + + + + + + + +