-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVsixTelemetry.cs
More file actions
462 lines (408 loc) · 17 KB
/
Copy pathVsixTelemetry.cs
File metadata and controls
462 lines (408 loc) · 17 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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Threading;
using Microsoft.Extensions.Logging;
using OpenTelemetry;
using OpenTelemetry.Exporter;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using Otel4Vsix.Exceptions;
using Otel4Vsix.Logging;
using Otel4Vsix.Metrics;
using Otel4Vsix.Tracing;
namespace Otel4Vsix
{
/// <summary>
/// Main entry point for OpenTelemetry in Visual Studio extensions.
/// Provides static access to tracing, metrics, logging, and exception tracking.
/// </summary>
/// <remarks>
/// This class is thread-safe. Call <see cref="Initialize"/> once during extension initialization,
/// then access telemetry through the static properties. Call <see cref="Shutdown"/> during disposal.
/// </remarks>
public static class VsixTelemetry
{
private static readonly object _lock = new object();
private static volatile bool _isInitialized;
private static TelemetryConfiguration _configuration;
private static ActivitySourceProvider _activitySourceProvider;
private static Metrics.MetricsProvider _metricsProvider;
private static LoggerProvider _loggerProvider;
private static ExceptionTracker _exceptionTracker;
private static TracerProvider _tracerProvider;
private static OpenTelemetry.Metrics.MeterProvider _otelMeterProvider;
private static ILoggerFactory _loggerFactory;
/// <summary>
/// Gets a value indicating whether telemetry has been initialized.
/// </summary>
public static bool IsInitialized => _isInitialized;
/// <summary>
/// Gets the <see cref="ActivitySource"/> for creating traces.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when telemetry is not initialized.</exception>
public static ActivitySource Tracer
{
get
{
ThrowIfNotInitialized();
return _activitySourceProvider.ActivitySource;
}
}
/// <summary>
/// Gets the <see cref="System.Diagnostics.Metrics.Meter"/> for creating metrics.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when telemetry is not initialized.</exception>
public static Meter Meter
{
get
{
ThrowIfNotInitialized();
return _metricsProvider.Meter;
}
}
/// <summary>
/// Gets the default <see cref="ILogger"/> for logging.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when telemetry is not initialized.</exception>
public static ILogger Logger
{
get
{
ThrowIfNotInitialized();
return _loggerProvider.Logger;
}
}
/// <summary>
/// Gets the <see cref="ILoggerFactory"/> for creating additional loggers.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when telemetry is not initialized.</exception>
public static ILoggerFactory LoggerFactory
{
get
{
ThrowIfNotInitialized();
return _loggerProvider.LoggerFactory;
}
}
/// <summary>
/// Initializes telemetry with the specified configuration.
/// </summary>
/// <param name="configuration">The configuration options for telemetry.</param>
/// <exception cref="ArgumentNullException">Thrown when configuration is null.</exception>
/// <exception cref="InvalidOperationException">Thrown when telemetry is already initialized.</exception>
public static void Initialize(TelemetryConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
configuration.Validate();
lock (_lock)
{
if (_isInitialized)
{
throw new InvalidOperationException(
"VsixTelemetry is already initialized. Call Shutdown() before reinitializing.");
}
_configuration = configuration;
InitializeProviders();
_isInitialized = true;
}
}
/// <summary>
/// Shuts down telemetry and releases all resources.
/// </summary>
/// <param name="timeoutMilliseconds">Optional timeout for flushing pending telemetry.</param>
public static void Shutdown(int timeoutMilliseconds = 5000)
{
lock (_lock)
{
if (!_isInitialized)
{
return;
}
try
{
// Dispose in reverse order of initialization
_exceptionTracker?.Dispose();
_loggerProvider?.Dispose();
_metricsProvider?.Dispose();
_activitySourceProvider?.Dispose();
// Shutdown OpenTelemetry providers
_otelMeterProvider?.Shutdown(timeoutMilliseconds);
_tracerProvider?.Shutdown(timeoutMilliseconds);
_otelMeterProvider?.Dispose();
_tracerProvider?.Dispose();
_loggerFactory?.Dispose();
}
finally
{
_exceptionTracker = null;
_loggerProvider = null;
_metricsProvider = null;
_activitySourceProvider = null;
_otelMeterProvider = null;
_tracerProvider = null;
_loggerFactory = null;
_configuration = null;
_isInitialized = false;
}
}
}
/// <summary>
/// Tracks an exception and records it to telemetry.
/// </summary>
/// <param name="exception">The exception to track.</param>
/// <param name="additionalAttributes">Optional additional attributes to include.</param>
public static void TrackException(Exception exception, IDictionary<string, object> additionalAttributes = null)
{
if (!_isInitialized || _exceptionTracker == null)
{
return;
}
_exceptionTracker.TrackException(exception, additionalAttributes);
}
/// <summary>
/// Starts a new activity with the specified name.
/// </summary>
/// <param name="name">The name of the activity.</param>
/// <param name="kind">The kind of activity.</param>
/// <returns>The started activity, or null if telemetry is not initialized or no listeners are registered.</returns>
public static Activity StartActivity(string name, ActivityKind kind = ActivityKind.Internal)
{
if (!_isInitialized || _activitySourceProvider == null)
{
return null;
}
return _activitySourceProvider.StartActivity(name, kind);
}
/// <summary>
/// Starts a new activity for a VS command execution.
/// </summary>
/// <param name="commandName">The name of the command being executed.</param>
/// <returns>The started activity, or null if telemetry is not initialized or no listeners are registered.</returns>
public static Activity StartCommandActivity(string commandName)
{
if (!_isInitialized || _activitySourceProvider == null)
{
return null;
}
return _activitySourceProvider.StartCommandActivity(commandName);
}
/// <summary>
/// Creates a logger for the specified type.
/// </summary>
/// <typeparam name="T">The type to use as the category name.</typeparam>
/// <returns>A new logger instance, or null if telemetry is not initialized.</returns>
public static ILogger<T> CreateLogger<T>()
{
if (!_isInitialized || _loggerProvider == null)
{
return null;
}
return _loggerProvider.CreateLogger<T>();
}
/// <summary>
/// Creates a logger with the specified category name.
/// </summary>
/// <param name="categoryName">The category name for the logger.</param>
/// <returns>A new logger instance, or null if telemetry is not initialized.</returns>
public static ILogger CreateLogger(string categoryName)
{
if (!_isInitialized || _loggerProvider == null)
{
return null;
}
return _loggerProvider.CreateLogger(categoryName);
}
/// <summary>
/// Gets or creates a counter with the specified name.
/// </summary>
/// <typeparam name="T">The type of the counter value.</typeparam>
/// <param name="name">The name of the counter.</param>
/// <param name="unit">Optional unit of measurement.</param>
/// <param name="description">Optional description.</param>
/// <returns>The counter, or null if telemetry is not initialized.</returns>
public static Counter<T> GetOrCreateCounter<T>(string name, string unit = null, string description = null)
where T : struct
{
if (!_isInitialized || _metricsProvider == null)
{
return null;
}
return _metricsProvider.GetOrCreateCounter<T>(name, unit, description);
}
/// <summary>
/// Gets or creates a histogram with the specified name.
/// </summary>
/// <typeparam name="T">The type of the histogram value.</typeparam>
/// <param name="name">The name of the histogram.</param>
/// <param name="unit">Optional unit of measurement.</param>
/// <param name="description">Optional description.</param>
/// <returns>The histogram, or null if telemetry is not initialized.</returns>
public static Histogram<T> GetOrCreateHistogram<T>(string name, string unit = null, string description = null)
where T : struct
{
if (!_isInitialized || _metricsProvider == null)
{
return null;
}
return _metricsProvider.GetOrCreateHistogram<T>(name, unit, description);
}
private static void InitializeProviders()
{
var resourceBuilder = CreateResourceBuilder();
// Initialize tracing
if (_configuration.EnableTracing)
{
_activitySourceProvider = new ActivitySourceProvider(
_configuration.ServiceName,
_configuration.ServiceVersion);
_tracerProvider = BuildTracerProvider(resourceBuilder);
}
// Initialize metrics
if (_configuration.EnableMetrics)
{
_metricsProvider = new Metrics.MetricsProvider(
_configuration.ServiceName,
_configuration.ServiceVersion);
_otelMeterProvider = BuildMeterProvider(resourceBuilder);
}
// Initialize logging
if (_configuration.EnableLogging)
{
_loggerFactory = BuildLoggerFactory(resourceBuilder);
_loggerProvider = new LoggerProvider(_loggerFactory, _configuration.ServiceName);
}
// Initialize exception tracking
var logger = _loggerProvider?.Logger ??
Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
_exceptionTracker = new ExceptionTracker(
logger,
_configuration.ExceptionFilter,
_configuration.IncludeVisualStudioContext);
if (_configuration.EnableGlobalExceptionHandler)
{
_exceptionTracker.RegisterGlobalExceptionHandler();
}
}
private static ResourceBuilder CreateResourceBuilder()
{
var resourceBuilder = ResourceBuilder.CreateDefault()
.AddService(
serviceName: _configuration.ServiceName,
serviceVersion: _configuration.ServiceVersion)
.AddAttributes(new[]
{
new KeyValuePair<string, object>("deployment.environment", "visualstudio"),
new KeyValuePair<string, object>("telemetry.sdk.name", "Otel4Vsix"),
new KeyValuePair<string, object>("telemetry.sdk.version", "1.0.0")
});
// Add custom resource attributes
if (_configuration.ResourceAttributes.Count > 0)
{
var customAttributes = new List<KeyValuePair<string, object>>();
foreach (var kvp in _configuration.ResourceAttributes)
{
customAttributes.Add(new KeyValuePair<string, object>(kvp.Key, kvp.Value));
}
resourceBuilder.AddAttributes(customAttributes);
}
return resourceBuilder;
}
private static TracerProvider BuildTracerProvider(ResourceBuilder resourceBuilder)
{
var builder = Sdk.CreateTracerProviderBuilder()
.SetResourceBuilder(resourceBuilder)
.AddSource(_configuration.ServiceName)
.SetSampler(new TraceIdRatioBasedSampler(_configuration.TraceSamplingRatio));
// Add OTLP exporter if endpoint is configured
if (!string.IsNullOrWhiteSpace(_configuration.OtlpEndpoint))
{
builder.AddOtlpExporter(options =>
{
ConfigureOtlpExporter(options);
});
}
// Add console exporter if enabled
if (_configuration.EnableConsoleExporter)
{
builder.AddConsoleExporter();
}
return builder.Build();
}
private static OpenTelemetry.Metrics.MeterProvider BuildMeterProvider(ResourceBuilder resourceBuilder)
{
var builder = Sdk.CreateMeterProviderBuilder()
.SetResourceBuilder(resourceBuilder)
.AddMeter(_configuration.ServiceName);
// Add OTLP exporter if endpoint is configured
if (!string.IsNullOrWhiteSpace(_configuration.OtlpEndpoint))
{
builder.AddOtlpExporter(options =>
{
ConfigureOtlpExporter(options);
});
}
// Add console exporter if enabled
if (_configuration.EnableConsoleExporter)
{
builder.AddConsoleExporter();
}
return builder.Build();
}
private static ILoggerFactory BuildLoggerFactory(ResourceBuilder resourceBuilder)
{
return Microsoft.Extensions.Logging.LoggerFactory.Create(builder =>
{
builder.AddOpenTelemetry(options =>
{
options.SetResourceBuilder(resourceBuilder);
options.IncludeFormattedMessage = true;
options.IncludeScopes = true;
// Add OTLP exporter if endpoint is configured
if (!string.IsNullOrWhiteSpace(_configuration.OtlpEndpoint))
{
options.AddOtlpExporter(exporterOptions =>
{
ConfigureOtlpExporter(exporterOptions);
});
}
// Add console exporter if enabled
if (_configuration.EnableConsoleExporter)
{
options.AddConsoleExporter();
}
});
});
}
private static void ConfigureOtlpExporter(OtlpExporterOptions options)
{
options.Endpoint = new Uri(_configuration.OtlpEndpoint);
options.Protocol = _configuration.UseOtlpHttp
? OtlpExportProtocol.HttpProtobuf
: OtlpExportProtocol.Grpc;
options.TimeoutMilliseconds = _configuration.ExportTimeoutMilliseconds;
// Add custom headers if configured
if (_configuration.OtlpHeaders.Count > 0)
{
var headerString = string.Join(",",
_configuration.OtlpHeaders.Select(kvp => $"{kvp.Key}={kvp.Value}"));
options.Headers = headerString;
}
}
private static void ThrowIfNotInitialized()
{
if (!_isInitialized)
{
throw new InvalidOperationException(
"VsixTelemetry is not initialized. Call Initialize() first.");
}
}
}
}