1+ // Copyright (c) Microsoft Corporation.
2+ // Licensed under the MIT license.
3+ //
4+ using Microsoft . ApplicationInsights ;
5+
6+ namespace Microsoft . FeatureManagement . Telemetry . ApplicationInsights
7+ {
8+ /// <summary>
9+ /// Used to publish data from evaluation events to Application Insights
10+ /// </summary>
11+ public class ApplicationInsightsTelemetryPublisher : ITelemetryPublisher
12+ {
13+ private const string _eventName = "FeatureEvaluation" ;
14+ private readonly TelemetryClient _telemetryClient ;
15+
16+ public ApplicationInsightsTelemetryPublisher ( TelemetryClient telemetryClient )
17+ {
18+ _telemetryClient = telemetryClient ?? throw new ArgumentNullException ( nameof ( telemetryClient ) ) ;
19+ }
20+
21+ /// <summary>
22+ /// Publishes a custom event to Application Insights using data from the given evaluation event.
23+ /// </summary>
24+ /// <param name="evaluationEvent"> The event to publish.</param>
25+ /// <param name="cancellationToken"> A cancellation token.</param>
26+ /// <returns>Returns a ValueTask that represents the asynchronous operation</returns>
27+ public ValueTask PublishEvent ( EvaluationEvent evaluationEvent , CancellationToken cancellationToken )
28+ {
29+ ValidateEvent ( evaluationEvent ) ;
30+
31+ FeatureDefinition featureDefinition = evaluationEvent . FeatureDefinition ;
32+
33+ Dictionary < string , string > properties = new Dictionary < string , string > ( )
34+ {
35+ { "FeatureName" , featureDefinition . Name } ,
36+ { "IsEnabled" , evaluationEvent . IsEnabled . ToString ( ) }
37+ } ;
38+
39+ if ( evaluationEvent . Variant != null )
40+ {
41+ properties [ "Variant" ] = evaluationEvent . Variant . Name ;
42+ }
43+
44+ if ( featureDefinition . TelemetryMetadata != null )
45+ {
46+ foreach ( KeyValuePair < string , string > kvp in featureDefinition . TelemetryMetadata )
47+ {
48+ properties [ kvp . Key ] = kvp . Value ;
49+ }
50+ }
51+
52+ _telemetryClient . TrackEvent ( _eventName , properties ) ;
53+
54+ return new ValueTask ( ) ;
55+ }
56+
57+ private void ValidateEvent ( EvaluationEvent evaluationEvent )
58+ {
59+ if ( evaluationEvent == null )
60+ {
61+ throw new ArgumentNullException ( nameof ( evaluationEvent ) ) ;
62+ }
63+
64+ if ( evaluationEvent . FeatureDefinition == null )
65+ {
66+ throw new ArgumentNullException ( nameof ( evaluationEvent . FeatureDefinition ) ) ;
67+ }
68+ }
69+ }
70+ }
0 commit comments