forked from microsoft/ApplicationInsights-aspnetcore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApplicationInsightsExtensions.cs
More file actions
293 lines (258 loc) · 14.1 KB
/
Copy pathApplicationInsightsExtensions.cs
File metadata and controls
293 lines (258 loc) · 14.1 KB
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
using System.Linq;
namespace Microsoft.Extensions.DependencyInjection
{
using System;
using System.Collections.Generic;
using AspNetCore.Builder;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.AspNetCore;
using Microsoft.ApplicationInsights.AspNetCore.DiagnosticListeners;
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.ApplicationInsights.AspNetCore.Logging;
using Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers;
using Microsoft.ApplicationInsights.DependencyCollector;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
#if NET451
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector;
#endif
/// <summary>
/// Extension methods for <see cref="IServiceCollection"/> that allow adding Application Insights services to application.
/// </summary>
public static class ApplicationInsightsExtensions
{
private const string VersionKeyFromConfig = "version";
private const string InstrumentationKeyFromConfig = "ApplicationInsights:InstrumentationKey";
private const string DeveloperModeFromConfig = "ApplicationInsights:TelemetryChannel:DeveloperMode";
private const string EndpointAddressFromConfig = "ApplicationInsights:TelemetryChannel:EndpointAddress";
private const string InstrumentationKeyForWebSites = "APPINSIGHTS_INSTRUMENTATIONKEY";
private const string DeveloperModeForWebSites = "APPINSIGHTS_DEVELOPER_MODE";
private const string EndpointAddressForWebSites = "APPINSIGHTS_ENDPOINTADDRESS";
[Obsolete]
public static IApplicationBuilder UseApplicationInsightsRequestTelemetry(this IApplicationBuilder app)
{
return app;
}
[Obsolete]
public static IApplicationBuilder UseApplicationInsightsExceptionTelemetry(this IApplicationBuilder app)
{
return app.UseMiddleware<ExceptionTrackingMiddleware>();
}
/// <summary>
/// Adds Application Insights services into service collection.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> instance.</param>
/// <param name="instrumentationKey">Instrumentation key to use for telemetry.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddApplicationInsightsTelemetry(this IServiceCollection services, string instrumentationKey)
{
services.AddApplicationInsightsTelemetry(options => options.InstrumentationKey = instrumentationKey);
return services;
}
/// <summary>
/// Adds Application Insights services into service collection.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> instance.</param>
/// <param name="configuration">Configuration to use for sending telemetry.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddApplicationInsightsTelemetry(this IServiceCollection services, IConfiguration configuration)
{
services.AddApplicationInsightsTelemetry(options => AddTelemetryConfiguration(configuration, options));
return services;
}
/// <summary>
/// Adds Application Insights services into service collection.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> instance.</param>
/// <param name="options">The action used to configure the options.</param>
/// <returns>
/// The <see cref="IServiceCollection"/>.
/// </returns>
public static IServiceCollection AddApplicationInsightsTelemetry(this IServiceCollection services, Action<ApplicationInsightsServiceOptions> options)
{
services.AddApplicationInsightsTelemetry();
services.Configure(options);
return services;
}
/// <summary>
/// Adds Application Insights services into service collection.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> instance.</param>
/// <param name="options">The options instance used to configure with.</param>
/// <returns>
/// The <see cref="IServiceCollection"/>.
/// </returns>
public static IServiceCollection AddApplicationInsightsTelemetry(this IServiceCollection services, ApplicationInsightsServiceOptions options)
{
services.AddApplicationInsightsTelemetry();
services.Configure((ApplicationInsightsServiceOptions o) =>
{
o.ApplicationVersion = options.ApplicationVersion;
o.DeveloperMode = options.DeveloperMode;
o.EnableAdaptiveSampling = options.EnableAdaptiveSampling;
o.EnableAuthenticationTrackingJavaScript = options.EnableAuthenticationTrackingJavaScript;
o.EnableDebugLogger = options.EnableDebugLogger;
o.EnableQuickPulseMetricStream = options.EnableQuickPulseMetricStream;
o.EndpointAddress = options.EndpointAddress;
o.InstrumentationKey = options.InstrumentationKey;
});
return services;
}
/// <summary>
/// Adds Application Insights services into service collection.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> instance.</param>
/// <param name="options">The action used to configure the options.</param>
/// <returns>
/// The <see cref="IServiceCollection"/>.
/// </returns>
public static IServiceCollection AddApplicationInsightsTelemetry(this IServiceCollection services)
{
if (!IsApplicationInsightsAdded(services))
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<ITelemetryInitializer, AzureWebAppRoleEnvironmentTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, DomainNameRoleInstanceTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, ComponentVersionTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, ClientIpHeaderTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, OperationNameTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, ApplicationInsights.AspNetCore.TelemetryInitializers.OperationCorrelationTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, SyntheticTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, WebSessionTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, WebUserTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, AspNetCoreEnvironmentTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, HttpDependenciesParsingTelemetryInitializer>();
services.AddSingleton<ITelemetryModule, DependencyTrackingTelemetryModule>(provider => {
var module = new DependencyTrackingTelemetryModule();
var excludedDomains = module.ExcludeComponentCorrelationHttpHeadersOnDomains;
excludedDomains.Add("core.windows.net");
excludedDomains.Add("core.chinacloudapi.cn");
excludedDomains.Add("core.cloudapi.de");
excludedDomains.Add("core.usgovcloudapi.net");
return module;
});
#if NET451
services.AddSingleton<ITelemetryModule, PerformanceCollectorModule>();
#endif
services.AddSingleton<TelemetryConfiguration>(provider => provider.GetService<IOptions<TelemetryConfiguration>>().Value);
services.AddSingleton<ICorrelationIdLookupHelper>(provider => new CorrelationIdLookupHelper(() => provider.GetService<IOptions<TelemetryConfiguration>>().Value));
services.AddSingleton<TelemetryClient>();
services.AddSingleton<ApplicationInsightsInitializer, ApplicationInsightsInitializer>();
services.AddSingleton<IApplicationInsightDiagnosticListener, HostingDiagnosticListener>();
services.AddSingleton<IApplicationInsightDiagnosticListener, MvcDiagnosticsListener>();
// Using startup filter instead of starting DiagnosticListeners directly because
// AspNetCoreHostingDiagnosticListener injects TelemetryClient that injects TelemetryConfiguration
// that requires IOptions infrastructure to run and initialize
services.AddSingleton<IStartupFilter, ApplicationInsightsStartupFilter>();
services.AddSingleton<JavaScriptSnippet>();
services.AddSingleton<ApplicationInsightsLoggerEvents>();
services.AddOptions();
services.AddSingleton<IOptions<TelemetryConfiguration>, TelemetryConfigurationOptions>();
services.AddSingleton<IConfigureOptions<TelemetryConfiguration>, TelemetryConfigurationOptionsSetup>();
}
return services;
}
/// <summary>
/// Adds Application Insight specific configuration properties to <see cref="IConfigurationBuilder"/>.
/// </summary>
/// <param name="configurationSourceRoot">The <see cref="IConfigurationBuilder"/> instance.</param>
/// <param name="developerMode">Enables or disables developer mode.</param>
/// <param name="endpointAddress">Sets telemetry endpoint address.</param>
/// <param name="instrumentationKey">Sets instrumentation key.</param>
/// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
public static IConfigurationBuilder AddApplicationInsightsSettings(
this IConfigurationBuilder configurationSourceRoot,
bool? developerMode = null,
string endpointAddress = null,
string instrumentationKey = null)
{
var telemetryConfigValues = new List<KeyValuePair<string, string>>();
bool wasAnythingSet = false;
if (developerMode != null)
{
telemetryConfigValues.Add(new KeyValuePair<string, string>(DeveloperModeForWebSites, developerMode.Value.ToString()));
wasAnythingSet = true;
}
if (instrumentationKey != null)
{
telemetryConfigValues.Add(new KeyValuePair<string, string>(InstrumentationKeyForWebSites, instrumentationKey));
wasAnythingSet = true;
}
if (endpointAddress != null)
{
telemetryConfigValues.Add(new KeyValuePair<string, string>(EndpointAddressForWebSites, endpointAddress));
wasAnythingSet = true;
}
if (wasAnythingSet)
{
configurationSourceRoot.Add(new MemoryConfigurationSource() { InitialData = telemetryConfigValues });
}
return configurationSourceRoot;
}
/// <summary>
/// Read from configuration
/// Config.json will look like this:
/// <para>
/// "ApplicationInsights": {
/// "InstrumentationKey": "11111111-2222-3333-4444-555555555555"
/// "TelemetryChannel": {
/// EndpointAddress: "http://dc.services.visualstudio.com/v2/track",
/// DeveloperMode: true
/// }
/// }
/// </para>
/// Values can also be read from environment variables to support azure web sites configuration:
/// </summary>
/// <param name="config">Configuration to read variables from.</param>
/// <param name="serviceOptions">Telemetry configuration to populate.</param>
internal static void AddTelemetryConfiguration(IConfiguration config, ApplicationInsightsServiceOptions serviceOptions)
{
string instrumentationKey = config[InstrumentationKeyForWebSites];
if (string.IsNullOrWhiteSpace(instrumentationKey))
{
instrumentationKey = config[InstrumentationKeyFromConfig];
}
if (!string.IsNullOrWhiteSpace(instrumentationKey))
{
serviceOptions.InstrumentationKey = instrumentationKey;
}
string developerModeValue = config[DeveloperModeForWebSites];
if (string.IsNullOrWhiteSpace(developerModeValue))
{
developerModeValue = config[DeveloperModeFromConfig];
}
if (!string.IsNullOrWhiteSpace(developerModeValue))
{
bool developerMode = false;
if (bool.TryParse(developerModeValue, out developerMode))
{
serviceOptions.DeveloperMode = developerMode;
}
}
string endpointAddress = config[EndpointAddressForWebSites];
if (string.IsNullOrWhiteSpace(endpointAddress))
{
endpointAddress = config[EndpointAddressFromConfig];
}
if (!string.IsNullOrWhiteSpace(endpointAddress))
{
serviceOptions.EndpointAddress = endpointAddress;
}
var version = config[VersionKeyFromConfig];
if (!string.IsNullOrWhiteSpace(version))
{
serviceOptions.ApplicationVersion = version;
}
}
private static bool IsApplicationInsightsAdded(IServiceCollection services)
{
// We treat ApplicationInsightsInitializer as a marker that AI services were added to service collection
return services.Any(service => service.ServiceType == typeof(ApplicationInsightsInitializer));
}
}
}