Skip to content

Commit 7e9e2e9

Browse files
Merge pull request #3068 from microsoft/rajrang/reqdepenableprop
Integrate Application Insights Service Options / Cleanup
2 parents b9776ed + 8945fe6 commit 7e9e2e9

File tree

12 files changed

+435
-30
lines changed

12 files changed

+435
-30
lines changed

.publicApi/Microsoft.ApplicationInsights.AspNetCore.dll/Stable/PublicAPI.Unshipped.txt

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@ Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOp
99
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.Credential.get -> Azure.Core.TokenCredential
1010
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.Credential.set -> void
1111
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.DependencyCollectionOptions.get -> Microsoft.ApplicationInsights.AspNetCore.Extensions.DependencyCollectionOptions
12-
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.EnableActiveTelemetryConfigurationSetup.get -> bool
13-
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.EnableActiveTelemetryConfigurationSetup.set -> void
1412
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.EnableAdaptiveSampling.get -> bool
1513
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.EnableAdaptiveSampling.set -> void
1614
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.EnableAuthenticationTrackingJavaScript.get -> bool
@@ -25,8 +23,6 @@ Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOp
2523
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.EnableQuickPulseMetricStream.set -> void
2624
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.EnableRequestTrackingTelemetryModule.get -> bool
2725
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.EnableRequestTrackingTelemetryModule.set -> void
28-
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.EndpointAddress.get -> string
29-
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.EndpointAddress.set -> void
3026
Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions.RequestCollectionOptions.get -> Microsoft.ApplicationInsights.AspNetCore.Extensions.RequestCollectionOptions
3127
Microsoft.ApplicationInsights.AspNetCore.Extensions.DependencyCollectionOptions
3228
Microsoft.ApplicationInsights.AspNetCore.Extensions.DependencyCollectionOptions.DependencyCollectionOptions() -> void

.publicApi/Microsoft.ApplicationInsights.WorkerService.dll/Stable/PublicAPI.Unshipped.txt

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@ Microsoft.ApplicationInsights.WorkerService.ApplicationInsightsServiceOptions.En
1919
Microsoft.ApplicationInsights.WorkerService.ApplicationInsightsServiceOptions.EnablePerformanceCounterCollectionModule.set -> void
2020
Microsoft.ApplicationInsights.WorkerService.ApplicationInsightsServiceOptions.EnableQuickPulseMetricStream.get -> bool
2121
Microsoft.ApplicationInsights.WorkerService.ApplicationInsightsServiceOptions.EnableQuickPulseMetricStream.set -> void
22-
Microsoft.ApplicationInsights.WorkerService.ApplicationInsightsServiceOptions.EndpointAddress.get -> string
23-
Microsoft.ApplicationInsights.WorkerService.ApplicationInsightsServiceOptions.EndpointAddress.set -> void
2422
Microsoft.ApplicationInsights.WorkerService.DependencyCollectionOptions
2523
Microsoft.ApplicationInsights.WorkerService.DependencyCollectionOptions.DependencyCollectionOptions() -> void
2624
Microsoft.ApplicationInsights.WorkerService.DependencyCollectionOptions.EnableLegacyCorrelationHeadersInjection.get -> bool

NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Extensions/ApplicationInsightsExtensions.cs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System;
44
using System.Collections.Generic;
55
using System.Diagnostics;
6+
using System.Reflection;
67
using Azure.Monitor.OpenTelemetry.Exporter;
78
using Microsoft.ApplicationInsights;
89
using Microsoft.ApplicationInsights.AspNetCore;
@@ -147,7 +148,11 @@ internal static IOpenTelemetryBuilder UseApplicationInsightsTelemetry(this IOpen
147148
}
148149

149150
return true;
150-
}));
151+
})
152+
.AddProcessor<ActivityFilterProcessor>());
153+
154+
// Register ActivityFilterProcessor in DI
155+
builder.Services.AddSingleton<ActivityFilterProcessor>();
151156

152157
builder.WithMetrics(b => b.AddHttpClientAndServerMetrics());
153158

@@ -207,6 +212,18 @@ internal static IOpenTelemetryBuilder UseApplicationInsightsTelemetry(this IOpen
207212
{
208213
exporterOptions.EnableLiveMetrics = false;
209214
}
215+
216+
// Configure standard metrics and performance counter collection using reflection
217+
// Only set when false since the default is true
218+
if (!serviceOptions.AddAutoCollectedMetricExtractor)
219+
{
220+
TrySetInternalProperty(exporterOptions, "EnableStandardMetrics", false);
221+
}
222+
223+
if (!serviceOptions.EnablePerformanceCounterCollectionModule)
224+
{
225+
TrySetInternalProperty(exporterOptions, "EnablePerfCounters", false);
226+
}
210227
});
211228

212229
builder.UseAzureMonitorExporter();
@@ -220,5 +237,22 @@ private static MeterProviderBuilder AddHttpClientAndServerMetrics(this MeterProv
220237
meterProviderBuilder.AddMeter("Microsoft.AspNetCore.Hosting").AddMeter("System.Net.Http")
221238
: meterProviderBuilder.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation();
222239
}
240+
241+
private static void TrySetInternalProperty(object target, string propertyName, bool value)
242+
{
243+
try
244+
{
245+
var property = target.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
246+
if (property != null && property.CanWrite && property.PropertyType == typeof(bool))
247+
{
248+
property.SetValue(target, value);
249+
}
250+
}
251+
catch
252+
{
253+
// Silently ignore if property doesn't exist or can't be set
254+
// This allows forward/backward compatibility across versions
255+
}
256+
}
223257
}
224258
}

NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Properties/AssemblyInfo.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using System.Runtime.InteropServices;
33

44
[assembly: InternalsVisibleTo("Microsoft.ApplicationInsights.AspNetCore.Tests, PublicKey=" + AssemblyInfo.PublicKey)]
5+
[assembly: InternalsVisibleTo("IntegrationTests.Tests, PublicKey=" + AssemblyInfo.PublicKey)]
56
[assembly: ComVisible(false)]
67
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "SDK intentionally catch ALL exceptions and never re-throws.")]
78
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1633:File must have header", Justification = "Unnecessary.")]

NETCORE/src/Microsoft.ApplicationInsights.WorkerService/ApplicationInsightsExtensions.cs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System;
44
using System.Collections.Generic;
55
using System.Diagnostics;
6+
using System.Reflection;
67
using Azure.Monitor.OpenTelemetry.Exporter;
78
using Microsoft.ApplicationInsights;
89
using Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing;
@@ -142,7 +143,11 @@ internal static IOpenTelemetryBuilder UseApplicationInsightsTelemetry(this IOpen
142143
}
143144

144145
return true;
145-
}));
146+
})
147+
.AddProcessor<ActivityFilterProcessor>());
148+
149+
// Register ActivityFilterProcessor in DI
150+
builder.Services.AddSingleton<ActivityFilterProcessor>();
146151

147152
builder.WithMetrics(b => b.AddHttpClientMetrics());
148153

@@ -195,6 +200,18 @@ internal static IOpenTelemetryBuilder UseApplicationInsightsTelemetry(this IOpen
195200
}
196201

197202
exporterOptions.EnableLiveMetrics = serviceOptions.EnableQuickPulseMetricStream;
203+
204+
// Configure standard metrics and performance counter collection using reflection
205+
// Only set when false since the default is true
206+
if (!serviceOptions.AddAutoCollectedMetricExtractor)
207+
{
208+
TrySetInternalProperty(exporterOptions, "EnableStandardMetrics", false);
209+
}
210+
211+
if (!serviceOptions.EnablePerformanceCounterCollectionModule)
212+
{
213+
TrySetInternalProperty(exporterOptions, "EnablePerfCounters", false);
214+
}
198215
});
199216

200217
builder.UseAzureMonitorExporter();
@@ -208,5 +225,22 @@ private static MeterProviderBuilder AddHttpClientMetrics(this MeterProviderBuild
208225
meterProviderBuilder.AddMeter("System.Net.Http")
209226
: meterProviderBuilder.AddHttpClientInstrumentation();
210227
}
228+
229+
private static void TrySetInternalProperty(object target, string propertyName, bool value)
230+
{
231+
try
232+
{
233+
var property = target.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
234+
if (property != null && property.CanWrite && property.PropertyType == typeof(bool))
235+
{
236+
property.SetValue(target, value);
237+
}
238+
}
239+
catch
240+
{
241+
// Silently ignore if property doesn't exist or can't be set
242+
// This allows forward/backward compatibility across versions
243+
}
244+
}
211245
}
212246
}

NETCORE/src/Microsoft.ApplicationInsights.WorkerService/Properties/AssemblyInfo.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,7 @@
22
using System.Runtime.CompilerServices;
33
using System.Runtime.InteropServices;
44

5+
[assembly: InternalsVisibleTo("Microsoft.ApplicationInsights.WorkerService.Tests, PublicKey=" + AssemblyInfo.PublicKey)]
6+
[assembly: InternalsVisibleTo("WorkerIntegrationTests.Tests, PublicKey=" + AssemblyInfo.PublicKey)]
7+
[assembly: ComVisible(false)]
58
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1633:File must have header", Justification = "Unnecessary.")]
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#if AI_ASPNETCORE_WEB
2+
namespace Microsoft.ApplicationInsights.AspNetCore.Extensions
3+
#else
4+
namespace Microsoft.ApplicationInsights.WorkerService
5+
#endif
6+
{
7+
using System.Diagnostics;
8+
using Microsoft.Extensions.Options;
9+
using OpenTelemetry;
10+
11+
/// <summary>
12+
/// An OpenTelemetry processor that filters activities based on ApplicationInsightsServiceOptions settings.
13+
/// When EnableDependencyTrackingTelemetryModule is false, filters out Client, Internal, and Producer activities.
14+
/// When EnableRequestTrackingTelemetryModule is false, filters out Server and Consumer activities.
15+
/// Filtering is done by setting Activity.IsAllDataRequested to false, which prevents export while maintaining context propagation.
16+
/// </summary>
17+
internal sealed class ActivityFilterProcessor : BaseProcessor<Activity>
18+
{
19+
private readonly bool enableDependencyTracking;
20+
#if AI_ASPNETCORE_WEB
21+
private readonly bool enableRequestTracking;
22+
#endif
23+
24+
/// <summary>
25+
/// Initializes a new instance of the <see cref="ActivityFilterProcessor"/> class.
26+
/// </summary>
27+
/// <param name="options">The Application Insights service options containing filter settings.</param>
28+
public ActivityFilterProcessor(IOptions<ApplicationInsightsServiceOptions> options)
29+
{
30+
var serviceOptions = options.Value;
31+
this.enableDependencyTracking = serviceOptions.EnableDependencyTrackingTelemetryModule;
32+
#if AI_ASPNETCORE_WEB
33+
this.enableRequestTracking = serviceOptions.EnableRequestTrackingTelemetryModule;
34+
#endif
35+
}
36+
37+
/// <summary>
38+
/// Called when an activity is started. Applies filtering logic based on activity kind and service options.
39+
/// </summary>
40+
/// <param name="activity">The activity being started.</param>
41+
public override void OnStart(Activity activity)
42+
{
43+
if (activity == null)
44+
{
45+
return;
46+
}
47+
48+
// Filter dependency activities (outbound calls) when EnableDependencyTrackingTelemetryModule is false
49+
if (!this.enableDependencyTracking)
50+
{
51+
if (activity.Kind == ActivityKind.Client ||
52+
activity.Kind == ActivityKind.Internal ||
53+
activity.Kind == ActivityKind.Producer)
54+
{
55+
// Suppress export while maintaining context propagation
56+
activity.IsAllDataRequested = false;
57+
return;
58+
}
59+
}
60+
61+
#if AI_ASPNETCORE_WEB
62+
// Filter request activities (inbound calls) when EnableRequestTrackingTelemetryModule is false
63+
// Only available in AspNetCore, not WorkerService
64+
if (!this.enableRequestTracking)
65+
{
66+
if (activity.Kind == ActivityKind.Server ||
67+
activity.Kind == ActivityKind.Consumer)
68+
{
69+
// Suppress export while maintaining context propagation
70+
activity.IsAllDataRequested = false;
71+
return;
72+
}
73+
}
74+
#endif
75+
}
76+
}
77+
}

NETCORE/src/Shared/Extensions/ApplicationInsightsServiceOptions.cs

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,6 @@ public class ApplicationInsightsServiceOptions
5555
/// </summary>
5656
public string ApplicationVersion { get; set; } = Assembly.GetEntryAssembly()?.GetName().Version.ToString();
5757

58-
/// <summary>
59-
/// Gets or sets the endpoint address of the channel.
60-
/// </summary>
61-
public string EndpointAddress { get; set; }
62-
6358
/// <summary>
6459
/// Gets or sets a value indicating whether a logger would be registered automatically in debug mode.
6560
/// </summary>
@@ -95,28 +90,12 @@ public class ApplicationInsightsServiceOptions
9590
/// </summary>
9691
public DependencyCollectionOptions DependencyCollectionOptions { get; } = new DependencyCollectionOptions();
9792

98-
#if AI_ASPNETCORE_WEB
99-
/// <summary>
100-
/// Gets or sets a value indicating whether TelemetryConfiguration.Active should be initialized.
101-
/// Former versions of this library had a dependency on this static instance.
102-
/// This dependency has been removed and we no longer initialize this by default.
103-
/// If users depended on this behavior you should enable this.
104-
/// However, we recommend migrating away from using TelemetryConfiguration.Active in your projects.
105-
/// </summary>
106-
public bool EnableActiveTelemetryConfigurationSetup { get; set; } = false;
107-
#endif
108-
10993
/// <summary>
11094
/// Copy the properties from this <see cref="ApplicationInsightsServiceOptions"/> to a target instance.
11195
/// </summary>
11296
/// <param name="target">Target instance to copy properties to.</param>
11397
internal void CopyPropertiesTo(ApplicationInsightsServiceOptions target)
11498
{
115-
if (!string.IsNullOrEmpty(this.EndpointAddress))
116-
{
117-
target.EndpointAddress = this.EndpointAddress;
118-
}
119-
12099
if (!string.IsNullOrEmpty(this.ConnectionString))
121100
{
122101
target.ConnectionString = this.ConnectionString;
@@ -138,7 +117,6 @@ internal void CopyPropertiesTo(ApplicationInsightsServiceOptions target)
138117
#if AI_ASPNETCORE_WEB
139118
target.EnableAuthenticationTrackingJavaScript = this.EnableAuthenticationTrackingJavaScript;
140119
target.EnableRequestTrackingTelemetryModule = this.EnableRequestTrackingTelemetryModule;
141-
target.EnableActiveTelemetryConfigurationSetup = this.EnableActiveTelemetryConfigurationSetup;
142120
#endif
143121
}
144122
}

NETCORE/src/Shared/Shared.projitems

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
<Import_RootNamespace>Microsoft.ApplicationInsights.Shared</Import_RootNamespace>
1010
</PropertyGroup>
1111
<ItemGroup>
12+
<Compile Include="$(MSBuildThisFileDirectory)ActivityFilterProcessor.cs" />
1213
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ApplicationInsightsExtensions.cs" />
1314
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ApplicationInsightsServiceOptions.cs" />
1415
<Compile Include="$(MSBuildThisFileDirectory)Extensions\DependencyCollectionOptions.cs" />

NETCORE/test/IntegrationTests.Tests/IntegrationTests.Tests.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
2323
</PackageReference>
2424
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
25+
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.0" />
2526
</ItemGroup>
2627

2728
<ItemGroup>
@@ -31,6 +32,7 @@
3132

3233
<ItemGroup>
3334
<Compile Include="..\Shared\ConfigurationTests.cs" Link="ConfigurationTests.cs" />
35+
<Compile Include="..\Shared\ActivityFilterProcessorTests.cs" Link="ActivityFilterProcessorTests.cs" />
3436
</ItemGroup>
3537

3638
<ItemGroup>

0 commit comments

Comments
 (0)