-
Notifications
You must be signed in to change notification settings - Fork 358
/
ApplicationInsightsServiceCollectionExtensions.cs
369 lines (313 loc) · 17.2 KB
/
ApplicationInsightsServiceCollectionExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.AspNetCore;
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DependencyCollector;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
using Microsoft.ApplicationInsights.SnapshotCollector;
using Microsoft.ApplicationInsights.WindowsServer;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Logging.ApplicationInsights;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Options;
namespace Microsoft.Extensions.DependencyInjection
{
internal static class ApplicationInsightsServiceCollectionExtensions
{
public static IServiceCollection AddApplicationInsights(this IServiceCollection services, Action<ApplicationInsightsLoggerOptions> configure)
{
services.AddApplicationInsights();
if (configure != null)
{
services.Configure<ApplicationInsightsLoggerOptions>(configure);
}
return services;
}
public static IServiceCollection AddApplicationInsights(this IServiceCollection services)
{
services.TryAddSingleton<ISdkVersionProvider, WebJobsSdkVersionProvider>();
services.TryAddSingleton<IRoleInstanceProvider, WebJobsRoleInstanceProvider>();
// Bind to the configuration section registered with
services.AddOptions<ApplicationInsightsLoggerOptions>()
.Configure<ILoggerProviderConfiguration<ApplicationInsightsLoggerProvider>>((options, config) =>
{
config.Configuration?.Bind(options);
});
services.AddSingleton<ITelemetryInitializer, HttpDependenciesParsingTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer>(provider =>
{
ApplicationInsightsLoggerOptions options = provider.GetService<IOptions<ApplicationInsightsLoggerOptions>>().Value;
if (options.HttpAutoCollectionOptions.EnableHttpTriggerExtendedInfoCollection)
{
var httpContextAccessor = provider.GetService<IHttpContextAccessor>();
if (httpContextAccessor != null)
{
return new ClientIpHeaderTelemetryInitializer(httpContextAccessor);
}
}
return NullTelemetryInitializer.Instance;
});
services.AddSingleton<ITelemetryInitializer, WebJobsRoleEnvironmentTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, WebJobsTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, MetricSdkVersionTelemetryInitializer>();
services.AddSingleton<QuickPulseInitializationScheduler>();
services.AddSingleton<QuickPulseTelemetryModule>();
services.AddSingleton<ITelemetryModule>(provider =>
{
ApplicationInsightsLoggerOptions options = provider.GetService<IOptions<ApplicationInsightsLoggerOptions>>().Value;
if (options.EnableLiveMetrics)
{
return provider.GetService<QuickPulseTelemetryModule>();
}
return NullTelemetryModule.Instance;
});
services.AddSingleton<ITelemetryModule>(provider =>
{
ApplicationInsightsLoggerOptions options = provider.GetService<IOptions<ApplicationInsightsLoggerOptions>>().Value;
if (options.EnablePerformanceCountersCollection)
{
return new PerformanceCollectorModule
{
// Disabling this can improve cold start times
EnableIISExpressPerformanceCounters = false
};
}
return NullTelemetryModule.Instance;
});
services.AddSingleton<IApplicationIdProvider, ApplicationInsightsApplicationIdProvider>();
services.AddSingleton<ITelemetryModule>(provider =>
{
var options = provider.GetService<IOptions<ApplicationInsightsLoggerOptions>>().Value;
DependencyTrackingTelemetryModule dependencyCollector = null;
if (options.EnableDependencyTracking)
{
dependencyCollector = new DependencyTrackingTelemetryModule();
var excludedDomains = dependencyCollector.ExcludeComponentCorrelationHttpHeadersOnDomains;
excludedDomains.Add("core.windows.net");
excludedDomains.Add("core.chinacloudapi.cn");
excludedDomains.Add("core.cloudapi.de");
excludedDomains.Add("core.usgovcloudapi.net");
excludedDomains.Add("localhost");
excludedDomains.Add("127.0.0.1");
var includedActivities = dependencyCollector.IncludeDiagnosticSourceActivities;
includedActivities.Add("Microsoft.Azure.ServiceBus");
includedActivities.Add("Microsoft.Azure.EventHubs");
if (options.DependencyTrackingOptions != null)
{
dependencyCollector.DisableRuntimeInstrumentation = options.DependencyTrackingOptions.DisableRuntimeInstrumentation;
dependencyCollector.DisableDiagnosticSourceInstrumentation = options.DependencyTrackingOptions.DisableDiagnosticSourceInstrumentation;
dependencyCollector.EnableLegacyCorrelationHeadersInjection = options.DependencyTrackingOptions.EnableLegacyCorrelationHeadersInjection;
dependencyCollector.EnableRequestIdHeaderInjectionInW3CMode = options.DependencyTrackingOptions.EnableRequestIdHeaderInjectionInW3CMode;
dependencyCollector.EnableSqlCommandTextInstrumentation = options.DependencyTrackingOptions.EnableSqlCommandTextInstrumentation;
dependencyCollector.SetComponentCorrelationHttpHeaders = options.DependencyTrackingOptions.SetComponentCorrelationHttpHeaders;
dependencyCollector.EnableAzureSdkTelemetryListener = options.DependencyTrackingOptions.EnableAzureSdkTelemetryListener;
}
return dependencyCollector;
}
return NullTelemetryModule.Instance;
});
services.AddSingleton<ITelemetryModule>(provider =>
{
var options = provider.GetService<IOptions<ApplicationInsightsLoggerOptions>>().Value;
if (options.HttpAutoCollectionOptions.EnableHttpTriggerExtendedInfoCollection)
{
var appIdProvider = provider.GetService<IApplicationIdProvider>();
return new RequestTrackingTelemetryModule(appIdProvider)
{
CollectionOptions = new RequestCollectionOptions
{
TrackExceptions = false, // webjobs/functions track exceptions themselves
InjectResponseHeaders = options.HttpAutoCollectionOptions.EnableResponseHeaderInjection
}
};
}
return NullTelemetryModule.Instance;
});
services.AddSingleton<ITelemetryModule, AppServicesHeartbeatTelemetryModule>();
services.AddSingleton<ITelemetryChannel, ServerTelemetryChannel>();
services.AddSingleton<TelemetryConfiguration>(provider =>
{
ApplicationInsightsLoggerOptions options = provider.GetService<IOptions<ApplicationInsightsLoggerOptions>>().Value;
Activity.DefaultIdFormat = options.HttpAutoCollectionOptions.EnableW3CDistributedTracing
? ActivityIdFormat.W3C
: ActivityIdFormat.Hierarchical;
Activity.ForceDefaultIdFormat = true;
LoggerFilterOptions filterOptions = CreateFilterOptions(provider.GetService<IOptions<LoggerFilterOptions>>().Value);
ITelemetryChannel channel = provider.GetService<ITelemetryChannel>();
TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
IApplicationIdProvider appIdProvider = provider.GetService<IApplicationIdProvider>();
ISdkVersionProvider sdkVersionProvider = provider.GetService<ISdkVersionProvider>();
IRoleInstanceProvider roleInstanceProvider = provider.GetService<IRoleInstanceProvider>();
// Because of https://github.com/Microsoft/ApplicationInsights-dotnet-server/issues/943
// we have to touch (and create) Active configuration before initializing telemetry modules
// Active configuration is used to report AppInsights heartbeats
// role environment telemetry initializer is needed to correlate heartbeats to particular host
var activeConfig = TelemetryConfiguration.Active;
if (!string.IsNullOrEmpty(options.InstrumentationKey) &&
string.IsNullOrEmpty(activeConfig.InstrumentationKey))
{
activeConfig.InstrumentationKey = options.InstrumentationKey;
}
// Set ConnectionString second because it takes precedence and
// we don't want InstrumentationKey to overwrite the value
// ConnectionString sets
if (!string.IsNullOrEmpty(options.ConnectionString) &&
string.IsNullOrEmpty(activeConfig.ConnectionString))
{
activeConfig.ConnectionString = options.ConnectionString;
}
if (!activeConfig.TelemetryInitializers.OfType<WebJobsRoleEnvironmentTelemetryInitializer>().Any())
{
activeConfig.TelemetryInitializers.Add(new WebJobsRoleEnvironmentTelemetryInitializer());
activeConfig.TelemetryInitializers.Add(new WebJobsTelemetryInitializer(sdkVersionProvider, roleInstanceProvider));
}
SetupTelemetryConfiguration(
config,
options,
channel,
provider.GetServices<ITelemetryInitializer>(),
provider.GetServices<ITelemetryModule>(),
appIdProvider,
filterOptions,
roleInstanceProvider,
provider.GetService<QuickPulseInitializationScheduler>());
return config;
});
services.AddSingleton<TelemetryClient>(provider =>
{
TelemetryConfiguration configuration = provider.GetService<TelemetryConfiguration>();
TelemetryClient client = new TelemetryClient(configuration);
ISdkVersionProvider versionProvider = provider.GetService<ISdkVersionProvider>();
client.Context.GetInternalContext().SdkVersion = versionProvider?.GetSdkVersion();
return client;
});
services.AddSingleton<ILoggerProvider, ApplicationInsightsLoggerProvider>();
return services;
}
internal static LoggerFilterOptions CreateFilterOptions(LoggerFilterOptions registeredOptions)
{
// We want our own copy of the rules, excluding the 'allow-all' rule that we added for this provider.
LoggerFilterOptions customFilterOptions = new LoggerFilterOptions
{
MinLevel = registeredOptions.MinLevel
};
ApplicationInsightsLoggerFilterRule allowAllRule = registeredOptions.Rules.OfType<ApplicationInsightsLoggerFilterRule>().Single();
// Copy all existing rules
foreach (LoggerFilterRule rule in registeredOptions.Rules)
{
if (rule != allowAllRule)
{
customFilterOptions.Rules.Add(rule);
}
}
// Copy 'hidden' rules
foreach (LoggerFilterRule rule in allowAllRule.ChildRules)
{
customFilterOptions.Rules.Add(rule);
}
return customFilterOptions;
}
private static void SetupTelemetryConfiguration(
TelemetryConfiguration configuration,
ApplicationInsightsLoggerOptions options,
ITelemetryChannel channel,
IEnumerable<ITelemetryInitializer> telemetryInitializers,
IEnumerable<ITelemetryModule> telemetryModules,
IApplicationIdProvider applicationIdProvider,
LoggerFilterOptions filterOptions,
IRoleInstanceProvider roleInstanceProvider,
QuickPulseInitializationScheduler delayer)
{
if (options.ConnectionString != null)
{
configuration.ConnectionString = options.ConnectionString;
}
else if (options.InstrumentationKey != null)
{
configuration.InstrumentationKey = options.InstrumentationKey;
}
configuration.TelemetryChannel = channel;
foreach (ITelemetryInitializer initializer in telemetryInitializers)
{
if (!(initializer is NullTelemetryInitializer))
{
configuration.TelemetryInitializers.Add(initializer);
}
}
(channel as ServerTelemetryChannel)?.Initialize(configuration);
QuickPulseTelemetryModule quickPulseModule = null;
foreach (ITelemetryModule module in telemetryModules)
{
if (module is QuickPulseTelemetryModule telemetryModule)
{
quickPulseModule = telemetryModule;
if (options.LiveMetricsAuthenticationApiKey != null)
{
quickPulseModule.AuthenticationApiKey = options.LiveMetricsAuthenticationApiKey;
}
quickPulseModule.ServerId = roleInstanceProvider?.GetRoleInstanceName();
// QuickPulse can have a startup performance hit, so delay its initialization.
delayer.ScheduleInitialization(() => module.Initialize(configuration), options.LiveMetricsInitializationDelay);
}
else if (module != null)
{
module.Initialize(configuration);
}
}
QuickPulseTelemetryProcessor quickPulseProcessor = null;
configuration.TelemetryProcessorChainBuilder
.Use((next) => new OperationFilteringTelemetryProcessor(next))
.Use((next) =>
{
quickPulseProcessor = new QuickPulseTelemetryProcessor(next);
return quickPulseProcessor;
})
.Use((next) => new FilteringTelemetryProcessor(filterOptions, next));
if (options.SamplingSettings != null)
{
configuration.TelemetryProcessorChainBuilder.Use((next) =>
{
var processor = new AdaptiveSamplingTelemetryProcessor(options.SamplingSettings, null, next);
if (options.SamplingExcludedTypes != null)
{
processor.ExcludedTypes = options.SamplingExcludedTypes;
}
if (options.SamplingIncludedTypes != null)
{
processor.IncludedTypes = options.SamplingIncludedTypes;
}
return processor;
});
}
if (options.SnapshotConfiguration != null)
{
configuration.TelemetryProcessorChainBuilder.UseSnapshotCollector(options.SnapshotConfiguration);
}
configuration.TelemetryProcessorChainBuilder.Build();
quickPulseModule?.RegisterTelemetryProcessor(quickPulseProcessor);
foreach (ITelemetryProcessor processor in configuration.TelemetryProcessors)
{
if (processor is ITelemetryModule module)
{
module.Initialize(configuration);
}
}
configuration.ApplicationIdProvider = applicationIdProvider;
}
}
}