-
Notifications
You must be signed in to change notification settings - Fork 287
/
TelemetryClient.cs
1302 lines (1195 loc) · 74.8 KB
/
TelemetryClient.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
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace Microsoft.ApplicationInsights
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using Microsoft.ApplicationInsights.Extensibility.Implementation.Platform;
using Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing;
using Microsoft.ApplicationInsights.Metrics;
using Microsoft.ApplicationInsights.Metrics.Extensibility;
/// <summary>
/// Send events, metrics and other telemetry to the Application Insights service.
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722">Learn more</a>
/// </summary>
public sealed class TelemetryClient
{
#if NETSTANDARD // This constant is defined for all versions of NetStandard https://docs.microsoft.com/en-us/dotnet/core/tutorials/libraries#how-to-multitarget
private const string VersionPrefix = "dotnetc:";
#else
private const string VersionPrefix = "dotnet:";
#endif
private readonly TelemetryConfiguration configuration;
private string sdkVersion;
#pragma warning disable 612, 618 // TelemetryConfiguration.Active
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryClient" /> class. Send telemetry with the active configuration, usually loaded from ApplicationInsights.config.
/// </summary>
#if NETSTANDARD // This constant is defined for all versions of NetStandard https://docs.microsoft.com/en-us/dotnet/core/tutorials/libraries#how-to-multitarget
[Obsolete("We do not recommend using TelemetryConfiguration.Active on .NET Core. See https://github.com/microsoft/ApplicationInsights-dotnet/issues/1152 for more details")]
#endif
public TelemetryClient() : this(TelemetryConfiguration.Active)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryClient" /> class. Send telemetry with the specified <paramref name="configuration"/>.
/// </summary>
/// <exception cref="ArgumentNullException">The <paramref name="configuration"/> is null.</exception>
/// <exception cref="ArgumentException">The <paramref name="configuration"/> does not contain a telemetry channel.</exception>
public TelemetryClient(TelemetryConfiguration configuration)
{
if (configuration == null)
{
CoreEventSource.Log.TelemetryClientConstructorWithNoTelemetryConfiguration();
configuration = TelemetryConfiguration.Active;
}
this.configuration = configuration;
if (this.configuration.TelemetryChannel == null)
{
throw new ArgumentException("The specified configuration does not have a telemetry channel.", nameof(configuration));
}
}
#pragma warning restore 612, 618 // TelemetryConfiguration.Active
/// <summary>
/// Gets the current context that will be used to augment telemetry you send.
/// </summary>
public TelemetryContext Context
{
get;
internal set;
}
= new TelemetryContext();
/// <summary>
/// Gets or sets the default instrumentation key for all <see cref="ITelemetry"/> objects logged in this <see cref="TelemetryClient"/>.
/// </summary>
public string InstrumentationKey
{
get => this.Context.InstrumentationKey;
[Obsolete("InstrumentationKey based global ingestion is being deprecated. Recommended to set TelemetryConfiguration.ConnectionString. See https://github.com/microsoft/ApplicationInsights-dotnet/issues/2560 for more details.")]
set { this.Context.InstrumentationKey = value; }
}
/// <summary>
/// Gets the <see cref="TelemetryConfiguration"/> object associated with this telemetry client instance.
/// Changes made to the configuration can affect other clients.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public TelemetryConfiguration TelemetryConfiguration
{
get { return this.configuration; }
}
/// <summary>
/// Check to determine if the tracking is enabled.
/// </summary>
public bool IsEnabled()
{
return !this.configuration.DisableTelemetry;
}
/// <summary>
/// Send an <see cref="EventTelemetry"/> for display in Diagnostic Search and in the Analytics Portal.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#trackevent">Learn more</a>
/// </remarks>
/// <param name="eventName">A name for the event.</param>
/// <param name="properties">Named string values you can use to search and classify events.</param>
/// <param name="metrics">Measurements associated with this event.</param>
public void TrackEvent(string eventName, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null)
{
var telemetry = new EventTelemetry(eventName);
if (properties != null && properties.Count > 0)
{
Utils.CopyDictionary(properties, telemetry.Properties);
}
if (metrics != null && metrics.Count > 0)
{
Utils.CopyDictionary(metrics, telemetry.Metrics);
}
this.TrackEvent(telemetry);
}
/// <summary>
/// Send an <see cref="EventTelemetry"/> for display in Diagnostic Search and in the Analytics Portal.
/// Create a separate <see cref="EventTelemetry"/> instance for each call to <see cref="TrackEvent(EventTelemetry)"/>.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#trackevent">Learn more</a>
/// </remarks>
/// <param name="telemetry">An event log item.</param>
public void TrackEvent(EventTelemetry telemetry)
{
if (telemetry == null)
{
telemetry = new EventTelemetry();
}
this.Track(telemetry);
}
/// <summary>
/// Send a trace message for display in Diagnostic Search.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#tracktrace">Learn more</a>
/// </remarks>
/// <param name="message">Message to display.</param>
public void TrackTrace(string message)
{
this.TrackTrace(new TraceTelemetry(message));
}
/// <summary>
/// Send a trace message for display in Diagnostic Search.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#tracktrace">Learn more</a>
/// </remarks>
/// <param name="message">Message to display.</param>
/// <param name="severityLevel">Trace severity level.</param>
public void TrackTrace(string message, SeverityLevel severityLevel)
{
this.TrackTrace(new TraceTelemetry(message, severityLevel));
}
/// <summary>
/// Send a trace message for display in Diagnostic Search.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#tracktrace">Learn more</a>
/// </remarks>
/// <param name="message">Message to display.</param>
/// <param name="properties">Named string values you can use to search and classify events.</param>
public void TrackTrace(string message, IDictionary<string, string> properties)
{
TraceTelemetry telemetry = new TraceTelemetry(message);
if (properties != null && properties.Count > 0)
{
Utils.CopyDictionary(properties, telemetry.Properties);
}
this.TrackTrace(telemetry);
}
/// <summary>
/// Send a trace message for display in Diagnostic Search.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#tracktrace">Learn more</a>
/// </remarks>
/// <param name="message">Message to display.</param>
/// <param name="severityLevel">Trace severity level.</param>
/// <param name="properties">Named string values you can use to search and classify events.</param>
public void TrackTrace(string message, SeverityLevel severityLevel, IDictionary<string, string> properties)
{
TraceTelemetry telemetry = new TraceTelemetry(message, severityLevel);
if (properties != null && properties.Count > 0)
{
Utils.CopyDictionary(properties, telemetry.Properties);
}
this.TrackTrace(telemetry);
}
/// <summary>
/// Send a trace message for display in Diagnostic Search.
/// Create a separate <see cref="TraceTelemetry"/> instance for each call to <see cref="TrackTrace(TraceTelemetry)"/>.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#tracktrace">Learn more</a>
/// </remarks>
/// <param name="telemetry">Message with optional properties.</param>
public void TrackTrace(TraceTelemetry telemetry)
{
telemetry = telemetry ?? new TraceTelemetry();
this.Track(telemetry);
}
/// <summary>
/// This method is not the preferred method for sending metrics.
/// Metrics should always be pre-aggregated across a time period before being sent.<br />
/// Use one of the <c>GetMetric(..)</c> overloads to get a metric object for accessing SDK pre-aggregation capabilities.<br />
/// If you are implementing your own pre-aggregation logic, then you can use this method.
/// If your application requires sending a separate telemetry item at every occasion without aggregation across time,
/// you likely have a use case for event telemetry; see <see cref="TrackEvent(EventTelemetry)"/>.
/// </summary>
/// <param name="name">Metric name.</param>
/// <param name="value">Metric value.</param>
/// <param name="properties">Named string values you can use to classify and filter metrics.</param>
public void TrackMetric(string name, double value, IDictionary<string, string> properties = null)
{
var telemetry = new MetricTelemetry(name, value);
if (properties != null && properties.Count > 0)
{
Utils.CopyDictionary(properties, telemetry.Properties);
}
this.TrackMetric(telemetry);
}
/// <summary>
/// This method is not the preferred method for sending metrics.
/// Metrics should always be pre-aggregated across a time period before being sent.<br />
/// Use one of the <c>GetMetric(..)</c> overloads to get a metric object for accessing SDK pre-aggregation capabilities.<br />
/// If you are implementing your own pre-aggregation logic, then you can use this method.
/// If your application requires sending a separate telemetry item at every occasion without aggregation across time,
/// you likely have a use case for event telemetry; see <see cref="TrackEvent(EventTelemetry)"/>.
/// </summary>
/// <param name="telemetry">The metric telemetry item.</param>
public void TrackMetric(MetricTelemetry telemetry)
{
if (telemetry == null)
{
telemetry = new MetricTelemetry();
}
this.Track(telemetry);
}
/// <summary>
/// Send an <see cref="ExceptionTelemetry"/> for display in Diagnostic Search.
/// </summary>
/// <param name="exception">The exception to log.</param>
/// <param name="properties">Named string values you can use to classify and search for this exception.</param>
/// <param name="metrics">Additional values associated with this exception.</param>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#trackexception">Learn more</a>
/// </remarks>
public void TrackException(Exception exception, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null)
{
if (exception == null)
{
exception = new Exception(Utils.PopulateRequiredStringValue(null, "message", typeof(ExceptionTelemetry).FullName));
}
var telemetry = new ExceptionTelemetry(exception);
if (properties != null && properties.Count > 0)
{
Utils.CopyDictionary(properties, telemetry.Properties);
}
if (metrics != null && metrics.Count > 0)
{
Utils.CopyDictionary(metrics, telemetry.Metrics);
}
this.TrackException(telemetry);
}
/// <summary>
/// Send an <see cref="ExceptionTelemetry"/> for display in Diagnostic Search.
/// Create a separate <see cref="ExceptionTelemetry"/> instance for each call to <see cref="TrackException(ExceptionTelemetry)"/>.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#trackexception">Learn more</a>
/// </remarks>
public void TrackException(ExceptionTelemetry telemetry)
{
if (telemetry == null)
{
var exception = new Exception(Utils.PopulateRequiredStringValue(null, "message", typeof(ExceptionTelemetry).FullName));
telemetry = new ExceptionTelemetry(exception);
}
this.Track(telemetry);
}
/// <summary>
/// Send information about an external dependency (outgoing call) in the application.
/// </summary>
/// <param name="dependencyName">Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.</param>
/// <param name="data">Command initiated by this dependency call. Examples are SQL statement and HTTP URL's with all query parameters.</param>
/// <param name="startTime">The time when the dependency was called.</param>
/// <param name="duration">The time taken by the external dependency to handle the call.</param>
/// <param name="success">True if the dependency call was handled successfully.</param>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#trackdependency">Learn more</a>
/// </remarks>
[Obsolete("Please use a different overload of TrackDependency")]
public void TrackDependency(string dependencyName, string data, DateTimeOffset startTime, TimeSpan duration, bool success)
{
#pragma warning disable 618
this.TrackDependency(new DependencyTelemetry(dependencyName, data, startTime, duration, success));
#pragma warning restore 618
}
/// <summary>
/// Send information about an external dependency (outgoing call) in the application.
/// </summary>
/// <param name="dependencyTypeName">External dependency type. Very low cardinality value for logical grouping and interpretation of fields. Examples are SQL, Azure table, and HTTP.</param>
/// <param name="dependencyName">Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.</param>
/// <param name="data">Command initiated by this dependency call. Examples are SQL statement and HTTP URL's with all query parameters.</param>
/// <param name="startTime">The time when the dependency was called.</param>
/// <param name="duration">The time taken by the external dependency to handle the call.</param>
/// <param name="success">True if the dependency call was handled successfully.</param>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#trackdependency">Learn more</a>
/// </remarks>
public void TrackDependency(string dependencyTypeName, string dependencyName, string data, DateTimeOffset startTime, TimeSpan duration, bool success)
{
this.TrackDependency(new DependencyTelemetry(dependencyTypeName, null, dependencyName, data, startTime, duration, null, success));
}
/// <summary>
/// Send information about an external dependency (outgoing call) in the application.
/// </summary>
/// <param name="dependencyTypeName">External dependency type. Very low cardinality value for logical grouping and interpretation of fields. Examples are SQL, Azure table, and HTTP.</param>
/// <param name="target">External dependency target.</param>
/// <param name="dependencyName">Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.</param>
/// <param name="data">Command initiated by this dependency call. Examples are SQL statement and HTTP URL's with all query parameters.</param>
/// <param name="startTime">The time when the dependency was called.</param>
/// <param name="duration">The time taken by the external dependency to handle the call.</param>
/// <param name="resultCode">Result code of dependency call execution.</param>
/// <param name="success">True if the dependency call was handled successfully.</param>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#trackdependency">Learn more</a>
/// </remarks>
public void TrackDependency(string dependencyTypeName, string target, string dependencyName, string data, DateTimeOffset startTime, TimeSpan duration, string resultCode, bool success)
{
this.TrackDependency(new DependencyTelemetry(dependencyTypeName, target, dependencyName, data, startTime, duration, resultCode, success));
}
/// <summary>
/// Send information about external dependency call in the application.
/// Create a separate <see cref="DependencyTelemetry"/> instance for each call to <see cref="TrackDependency(DependencyTelemetry)"/>.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#trackdependency">Learn more</a>
/// </remarks>
public void TrackDependency(DependencyTelemetry telemetry)
{
if (telemetry == null)
{
telemetry = new DependencyTelemetry();
}
this.Track(telemetry);
}
/// <summary>
/// Send information about availability of an application.
/// </summary>
/// <param name="name">Availability test name.</param>
/// <param name="timeStamp">The time when the availability was captured.</param>
/// <param name="duration">The time taken for the availability test to run.</param>
/// <param name="runLocation">Name of the location the availability test was run from.</param>
/// <param name="success">True if the availability test ran successfully.</param>
/// <param name="message">Error message on availability test run failure.</param>
/// <param name="properties">Named string values you can use to classify and search for this availability telemetry.</param>
/// <param name="metrics">Additional values associated with this availability telemetry.</param>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=517889">Learn more</a>
/// </remarks>
public void TrackAvailability(string name, DateTimeOffset timeStamp, TimeSpan duration, string runLocation, bool success, string message = null, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null)
{
var availabilityTelemetry = new AvailabilityTelemetry(name, timeStamp, duration, runLocation, success, message);
if (properties != null && properties.Count > 0)
{
Utils.CopyDictionary(properties, availabilityTelemetry.Properties);
}
if (metrics != null && metrics.Count > 0)
{
Utils.CopyDictionary(metrics, availabilityTelemetry.Metrics);
}
this.TrackAvailability(availabilityTelemetry);
}
/// <summary>
/// Send information about availability of an application.
/// Create a separate <see cref="AvailabilityTelemetry"/> instance for each call to <see cref="TrackAvailability(AvailabilityTelemetry)"/>.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=517889">Learn more</a>
/// </remarks>
public void TrackAvailability(AvailabilityTelemetry telemetry)
{
if (telemetry == null)
{
telemetry = new AvailabilityTelemetry();
}
this.Track(telemetry);
}
/// <summary>
/// This method is an internal part of Application Insights infrastructure. Do not call.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public void Track(ITelemetry telemetry)
{
if (telemetry == null)
{
throw new ArgumentNullException(nameof(telemetry));
}
// TALK TO YOUR TEAM MATES BEFORE CHANGING THIS.
// This method needs to be public so that we can build and ship new telemetry types without having to ship core.
// It is hidden from intellisense to prevent customer confusion.
if (this.IsEnabled())
{
this.Initialize(telemetry);
telemetry.Context.ClearTempRawObjects();
// invokes the Process in the first processor in the chain
this.configuration.TelemetryProcessorChain.Process(telemetry);
// logs rich payload ETW event for any partners to process it
RichPayloadEventSource.Log.Process(telemetry);
}
}
/// <summary>
/// This method is an internal part of Application Insights infrastructure. Do not call.
/// </summary>
/// <param name="telemetry">Telemetry item to initialize instrumentation key.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
public void InitializeInstrumentationKey(ITelemetry telemetry)
{
if (telemetry == null)
{
throw new ArgumentNullException(nameof(telemetry));
}
string instrumentationKey = this.Context.InstrumentationKey;
if (string.IsNullOrEmpty(instrumentationKey))
{
instrumentationKey = this.configuration.InstrumentationKey;
}
telemetry.Context.InitializeInstrumentationkey(instrumentationKey);
}
/// <summary>
/// This method is an internal part of Application Insights infrastructure. Do not call.
/// </summary>
/// <param name="telemetry">Telemetry item to initialize.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
public void Initialize(ITelemetry telemetry)
{
if (telemetry == null)
{
throw new ArgumentNullException(nameof(telemetry));
}
ISupportAdvancedSampling telemetryWithSampling = telemetry as ISupportAdvancedSampling;
// Telemetry can be already sampled out if that decision was made before calling Track()
bool sampledOut = false;
if (telemetryWithSampling != null)
{
sampledOut = telemetryWithSampling.ProactiveSamplingDecision == SamplingDecision.SampledOut;
}
if (!sampledOut)
{
if (telemetry is ISupportProperties telemetryWithProperties)
{
if (this.configuration.TelemetryChannel?.DeveloperMode != null && this.configuration.TelemetryChannel.DeveloperMode.Value)
{
if (!telemetryWithProperties.Properties.ContainsKey("DeveloperMode"))
{
telemetryWithProperties.Properties.Add("DeveloperMode", "true");
}
}
}
// Properties set of TelemetryClient's Context are copied over to that of ITelemetry's Context
#pragma warning disable CS0618 // Type or member is obsolete
if (this.Context.PropertiesValue != null)
{
Utils.CopyDictionary(this.Context.Properties, telemetry.Context.Properties);
}
#pragma warning restore CS0618 // Type or member is obsolete
// This check avoids accessing the public accessor GlobalProperties
// unless needed, to avoid the penalty of ConcurrentDictionary instantiation.
if (this.Context.GlobalPropertiesValue != null)
{
Utils.CopyDictionary(this.Context.GlobalProperties, telemetry.Context.GlobalProperties);
}
string instrumentationKey = this.Context.InstrumentationKey;
if (string.IsNullOrEmpty(instrumentationKey))
{
instrumentationKey = this.configuration.InstrumentationKey;
}
telemetry.Context.Initialize(this.Context, instrumentationKey);
for (int index = 0; index < this.configuration.TelemetryInitializers.Count; index++)
{
try
{
this.configuration.TelemetryInitializers[index].Initialize(telemetry);
}
catch (Exception exception)
{
CoreEventSource.Log.LogError(string.Format(
CultureInfo.InvariantCulture,
"Exception while initializing {0}, exception message - {1}",
this.configuration.TelemetryInitializers[index].GetType().FullName,
exception));
}
}
if (telemetry.Timestamp == default(DateTimeOffset))
{
telemetry.Timestamp = PreciseTimestamp.GetUtcNow();
}
// Currently backend requires SDK version to comply "name: version"
if (string.IsNullOrEmpty(telemetry.Context.Internal.SdkVersion))
{
var version = this.sdkVersion ?? (this.sdkVersion = SdkVersionUtils.GetSdkVersion(VersionPrefix));
telemetry.Context.Internal.SdkVersion = version;
}
// set NodeName to the machine name if it's not initialized yet, if RoleInstance is also not set then we send only RoleInstance
if (string.IsNullOrEmpty(telemetry.Context.Internal.NodeName) && !string.IsNullOrEmpty(telemetry.Context.Cloud.RoleInstance))
{
telemetry.Context.Internal.NodeName = PlatformSingleton.Current.GetMachineName();
}
// set RoleInstance to the machine name if it's not initialized yet
if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleInstance))
{
telemetry.Context.Cloud.RoleInstance = PlatformSingleton.Current.GetMachineName();
}
}
else
{
CoreEventSource.Log.InitializationIsSkippedForSampledItem();
}
}
/// <summary>
/// Send information about the page viewed in the application.
/// </summary>
/// <param name="name">Name of the page.</param>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#page-views">Learn more</a>
/// </remarks>
public void TrackPageView(string name)
{
this.Track(new PageViewTelemetry(name));
}
/// <summary>
/// Send information about the page viewed in the application.
/// Create a separate <see cref="PageViewTelemetry"/> instance for each call to <see cref="TrackPageView(PageViewTelemetry)"/>.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#page-views">Learn more</a>
/// </remarks>
public void TrackPageView(PageViewTelemetry telemetry)
{
if (telemetry == null)
{
telemetry = new PageViewTelemetry();
}
this.Track(telemetry);
}
/// <summary>
/// Send information about a request handled by the application.
/// </summary>
/// <param name="name">The request name.</param>
/// <param name="startTime">The time when the page was requested.</param>
/// <param name="duration">The time taken by the application to handle the request.</param>
/// <param name="responseCode">The response status code.</param>
/// <param name="success">True if the request was handled successfully by the application.</param>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#trackrequest">Learn more</a>
/// </remarks>
public void TrackRequest(string name, DateTimeOffset startTime, TimeSpan duration, string responseCode, bool success)
{
this.Track(new RequestTelemetry(name, startTime, duration, responseCode, success));
}
/// <summary>
/// Send information about a request handled by the application.
/// Create a separate <see cref="RequestTelemetry"/> instance for each call to <see cref="TrackRequest(RequestTelemetry)"/>.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#trackrequest">Learn more</a>
/// </remarks>
public void TrackRequest(RequestTelemetry request)
{
if (request == null)
{
request = new RequestTelemetry();
}
this.Track(request);
}
/// <summary>
/// Flushes the in-memory buffer and any metrics being pre-aggregated.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#flushing-data">Learn more</a>
/// </remarks>
public void Flush()
{
CoreEventSource.Log.TelemetlyClientFlush();
if (this.TryGetMetricManager(out MetricManager privateMetricManager))
{
privateMetricManager.Flush(flushDownstreamPipeline: false);
}
TelemetryConfiguration pipeline = this.configuration;
if (pipeline != null)
{
MetricManager sharedMetricManager = pipeline.GetMetricManager(createIfNotExists: false);
sharedMetricManager?.Flush(flushDownstreamPipeline: false);
ITelemetryChannel channel = pipeline.TelemetryChannel;
channel?.Flush();
}
}
/// <summary>
/// Asynchronously Flushes the in-memory buffer and any metrics being pre-aggregated.
/// </summary>
/// <remarks>
/// <a href="https://go.microsoft.com/fwlink/?linkid=525722#flushing-data">Learn more</a>
/// </remarks>
/// <returns>
/// Returns true when telemetry data is transferred out of process (application insights server or local storage) and are emitted before the flush invocation.
/// Returns false when transfer of telemetry data to server has failed with non-retriable http status.
/// FlushAsync on InMemoryChannel always returns true, as the channel offers minimal reliability guarantees and doesn't retry sending telemetry after a failure.
/// </returns>
/// TODO: Metrics flush to respect CancellationToken.
public Task<bool> FlushAsync(CancellationToken cancellationToken)
{
if (this.TryGetMetricManager(out MetricManager privateMetricManager))
{
privateMetricManager.Flush(flushDownstreamPipeline: false);
}
TelemetryConfiguration pipeline = this.configuration;
if (pipeline != null)
{
MetricManager sharedMetricManager = pipeline.GetMetricManager(createIfNotExists: false);
sharedMetricManager?.Flush(flushDownstreamPipeline: false);
ITelemetryChannel channel = pipeline.TelemetryChannel;
if (channel is IAsyncFlushable asyncFlushableChannel && !cancellationToken.IsCancellationRequested)
{
return asyncFlushableChannel.FlushAsync(cancellationToken);
}
}
return cancellationToken.IsCancellationRequested ? TaskEx.FromCanceled<bool>(cancellationToken) : Task.FromResult(false);
}
/// <summary>
/// Gets or creates a metric container that you can use to track, aggregate and send metric values.<br />
/// Optionally specify a metric configuration to control how the tracked values are aggregated.
/// </summary>
/// <remarks>The aggregated values will be sent to the <c>TelemetryConfiguration</c>
/// associated with this client.<br />
/// The aggregation scope of the fetched<c>Metric</c> is <c>TelemetryConfiguration</c>; this
/// means that all values tracked for a given metric ID and dimensions will be aggregated together
/// across all clients that share the same <c>TelemetryConfiguration</c>.</remarks>
/// <param name="metricId">The ID (name) of the metric.
/// (The namespace specified in <see cref="MetricIdentifier.DefaultMetricNamespace"/> will be used.
/// To specify another namespace, use an overload that takes a <c>MetricIdentifier</c> parameter instead.)</param>
/// <returns>A <c>Metric</c> with the specified ID and dimensions. If you call this method several times
/// with the same metric ID and dimensions for a given aggregation scope, you will receive the same
/// instance of <c>Metric</c>.</returns>
/// <exception cref="ArgumentException">If you previously created a metric with the same namespace, ID, dimensions
/// and aggregation scope, but with a different configuration. When calling this method to get a previously
/// created metric, you can simply avoid specifying any configuration (or specify null) to imply the
/// configuration used earlier.</exception>
public Metric GetMetric(
string metricId)
{
return this.GetOrCreateMetric(
MetricAggregationScope.TelemetryConfiguration,
new MetricIdentifier(metricId),
metricConfiguration: null);
}
/// <summary>
/// Gets or creates a metric container that you can use to track, aggregate and send metric values.<br />
/// Optionally specify a metric configuration to control how the tracked values are aggregated.
/// </summary>
/// <remarks>The aggregated values will be sent to the <c>TelemetryConfiguration</c>
/// associated with this client.<br />
/// The aggregation scope of the fetched<c>Metric</c> is <c>TelemetryConfiguration</c>; this
/// means that all values tracked for a given metric ID and dimensions will be aggregated together
/// across all clients that share the same <c>TelemetryConfiguration</c>.</remarks>
/// <param name="metricId">The ID (name) of the metric.
/// (The namespace specified in <see cref="MetricIdentifier.DefaultMetricNamespace"/> will be used.
/// To specify another namespace, use an overload that takes a <c>MetricIdentifier</c> parameter instead.)</param>
/// <param name="metricConfiguration">Determines how tracked values will be aggregated. <br />
/// Use presets in <see cref="MetricConfigurations.Common"/> or specify your own settings. </param>
/// <returns>A <c>Metric</c> with the specified ID and dimensions. If you call this method several times
/// with the same metric ID and dimensions for a given aggregation scope, you will receive the same
/// instance of <c>Metric</c>.</returns>
/// <exception cref="ArgumentException">If you previously created a metric with the same namespace, ID, dimensions
/// and aggregation scope, but with a different configuration. When calling this method to get a previously
/// created metric, you can simply avoid specifying any configuration (or specify null) to imply the
/// configuration used earlier.</exception>
public Metric GetMetric(
string metricId,
MetricConfiguration metricConfiguration)
{
return this.GetOrCreateMetric(
MetricAggregationScope.TelemetryConfiguration,
new MetricIdentifier(metricId),
metricConfiguration: metricConfiguration);
}
/// <summary>
/// Gets or creates a metric container that you can use to track, aggregate and send metric values.<br />
/// Optionally specify a metric configuration to control how the tracked values are aggregated.
/// </summary>
/// <param name="metricId">The ID (name) of the metric.
/// (The namespace specified in <see cref="MetricIdentifier.DefaultMetricNamespace"/> will be used.
/// To specify another namespace, use an overload that takes a <c>MetricIdentifier</c> parameter instead.)</param>
/// <param name="metricConfiguration">Determines how tracked values will be aggregated. <br />
/// Use presets in <see cref="MetricConfigurations.Common"/> or specify your own settings. </param>
/// <returns>A <c>Metric</c> with the specified ID and dimensions. If you call this method several times
/// with the same metric ID and dimensions for a given aggregation scope, you will receive the same
/// instance of <c>Metric</c>.</returns>
/// <exception cref="ArgumentException">If you previously created a metric with the same namespace, ID, dimensions
/// and aggregation scope, but with a different configuration. When calling this method to get a previously
/// created metric, you can simply avoid specifying any configuration (or specify null) to imply the
/// configuration used earlier.</exception>
/// <param name="aggregationScope">The scope across which the values for the metric are to be aggregated in memory.
/// See <see cref="MetricAggregationScope" /> for more info.</param>
/// <returns>A <see cref="Metric"/> instance that you can use to automatically aggregate and then sent metric data value.</returns>
public Metric GetMetric(
string metricId,
MetricConfiguration metricConfiguration,
MetricAggregationScope aggregationScope)
{
return this.GetOrCreateMetric(
aggregationScope,
new MetricIdentifier(metricId),
metricConfiguration: metricConfiguration);
}
/// <summary>
/// Gets or creates a metric container that you can use to track, aggregate and send metric values.<br />
/// Optionally specify a metric configuration to control how the tracked values are aggregated.
/// </summary>
/// <remarks>The aggregated values will be sent to the <c>TelemetryConfiguration</c>
/// associated with this client.<br />
/// The aggregation scope of the fetched<c>Metric</c> is <c>TelemetryConfiguration</c>; this
/// means that all values tracked for a given metric ID and dimensions will be aggregated together
/// across all clients that share the same <c>TelemetryConfiguration</c>.</remarks>
/// <param name="metricId">The ID (name) of the metric.
/// (The namespace specified in <see cref="MetricIdentifier.DefaultMetricNamespace"/> will be used.
/// To specify another namespace, use an overload that takes a <c>MetricIdentifier</c> parameter instead.)</param>
/// <param name="dimension1Name">The name of the first dimension.</param>
/// <exception cref="ArgumentException">If you previously created a metric with the same namespace, ID, dimensions
/// and aggregation scope, but with a different configuration. When calling this method to get a previously
/// created metric, you can simply avoid specifying any configuration (or specify null) to imply the
/// configuration used earlier.</exception>
/// <returns>A <see cref="Metric"/> instance that you can use to automatically aggregate and then sent metric data value.</returns>
public Metric GetMetric(
string metricId,
string dimension1Name)
{
return this.GetOrCreateMetric(
MetricAggregationScope.TelemetryConfiguration,
new MetricIdentifier(MetricIdentifier.DefaultMetricNamespace, metricId, dimension1Name),
metricConfiguration: null);
}
/// <summary>
/// Gets or creates a metric container that you can use to track, aggregate and send metric values.<br />
/// Optionally specify a metric configuration to control how the tracked values are aggregated.
/// </summary>
/// <remarks>The aggregated values will be sent to the <c>TelemetryConfiguration</c>
/// associated with this client.<br />
/// The aggregation scope of the fetched<c>Metric</c> is <c>TelemetryConfiguration</c>; this
/// means that all values tracked for a given metric ID and dimensions will be aggregated together
/// across all clients that share the same <c>TelemetryConfiguration</c>.</remarks>
/// <param name="metricId">The ID (name) of the metric.
/// (The namespace specified in <see cref="MetricIdentifier.DefaultMetricNamespace"/> will be used.
/// To specify another namespace, use an overload that takes a <c>MetricIdentifier</c> parameter instead.)</param>
/// <param name="dimension1Name">The name of the first dimension.</param>
/// <param name="metricConfiguration">Determines how tracked values will be aggregated. <br />
/// Use presets in <see cref="MetricConfigurations.Common"/> or specify your own settings. </param>
/// <returns>A <c>Metric</c> with the specified ID and dimensions. If you call this method several times
/// with the same metric ID and dimensions for a given aggregation scope, you will receive the same
/// instance of <c>Metric</c>.</returns>
/// <exception cref="ArgumentException">If you previously created a metric with the same namespace, ID, dimensions
/// and aggregation scope, but with a different configuration. When calling this method to get a previously
/// created metric, you can simply avoid specifying any configuration (or specify null) to imply the
/// configuration used earlier.</exception>
public Metric GetMetric(
string metricId,
string dimension1Name,
MetricConfiguration metricConfiguration)
{
return this.GetOrCreateMetric(
MetricAggregationScope.TelemetryConfiguration,
new MetricIdentifier(MetricIdentifier.DefaultMetricNamespace, metricId, dimension1Name),
metricConfiguration: metricConfiguration);
}
/// <summary>
/// Gets or creates a metric container that you can use to track, aggregate and send metric values.<br />
/// Optionally specify a metric configuration to control how the tracked values are aggregated.
/// </summary>
/// <param name="metricId">The ID (name) of the metric.
/// (The namespace specified in <see cref="MetricIdentifier.DefaultMetricNamespace"/> will be used.
/// To specify another namespace, use an overload that takes a <c>MetricIdentifier</c> parameter instead.)</param>
/// <param name="dimension1Name">The name of the first dimension.</param>
/// <param name="metricConfiguration">Determines how tracked values will be aggregated. <br />
/// Use presets in <see cref="MetricConfigurations.Common"/> or specify your own settings. </param>
/// <returns>A <c>Metric</c> with the specified ID and dimensions. If you call this method several times
/// with the same metric ID and dimensions for a given aggregation scope, you will receive the same
/// instance of <c>Metric</c>.</returns>
/// <exception cref="ArgumentException">If you previously created a metric with the same namespace, ID, dimensions
/// and aggregation scope, but with a different configuration. When calling this method to get a previously
/// created metric, you can simply avoid specifying any configuration (or specify null) to imply the
/// configuration used earlier.</exception>
/// <param name="aggregationScope">The scope across which the values for the metric are to be aggregated in memory.
/// See <see cref="MetricAggregationScope" /> for more info.</param>
public Metric GetMetric(
string metricId,
string dimension1Name,
MetricConfiguration metricConfiguration,
MetricAggregationScope aggregationScope)
{
return this.GetOrCreateMetric(
aggregationScope,
new MetricIdentifier(MetricIdentifier.DefaultMetricNamespace, metricId, dimension1Name),
metricConfiguration: metricConfiguration);
}
/// <summary>
/// Gets or creates a metric container that you can use to track, aggregate and send metric values.<br />
/// Optionally specify a metric configuration to control how the tracked values are aggregated.
/// </summary>
/// <remarks>The aggregated values will be sent to the <c>TelemetryConfiguration</c>
/// associated with this client.<br />
/// The aggregation scope of the fetched<c>Metric</c> is <c>TelemetryConfiguration</c>; this
/// means that all values tracked for a given metric ID and dimensions will be aggregated together
/// across all clients that share the same <c>TelemetryConfiguration</c>.</remarks>
/// <param name="metricId">The ID (name) of the metric.
/// (The namespace specified in <see cref="MetricIdentifier.DefaultMetricNamespace"/> will be used.
/// To specify another namespace, use an overload that takes a <c>MetricIdentifier</c> parameter instead.)</param>
/// <param name="dimension1Name">The name of the first dimension.</param>
/// <param name="dimension2Name">The name of the second dimension.</param>
/// <exception cref="ArgumentException">If you previously created a metric with the same namespace, ID, dimensions
/// and aggregation scope, but with a different configuration. When calling this method to get a previously
/// created metric, you can simply avoid specifying any configuration (or specify null) to imply the
/// configuration used earlier.</exception>
/// <returns>A <see cref="Metric"/> instance that you can use to automatically aggregate and then sent metric data value.</returns>
public Metric GetMetric(
string metricId,
string dimension1Name,
string dimension2Name)
{
return this.GetOrCreateMetric(
MetricAggregationScope.TelemetryConfiguration,
new MetricIdentifier(MetricIdentifier.DefaultMetricNamespace, metricId, dimension1Name, dimension2Name),
metricConfiguration: null);
}
/// <summary>
/// Gets or creates a metric container that you can use to track, aggregate and send metric values.<br />
/// Optionally specify a metric configuration to control how the tracked values are aggregated.
/// </summary>
/// <remarks>The aggregated values will be sent to the <c>TelemetryConfiguration</c>
/// associated with this client.<br />
/// The aggregation scope of the fetched<c>Metric</c> is <c>TelemetryConfiguration</c>; this
/// means that all values tracked for a given metric ID and dimensions will be aggregated together
/// across all clients that share the same <c>TelemetryConfiguration</c>.</remarks>
/// <param name="metricId">The ID (name) of the metric.
/// (The namespace specified in <see cref="MetricIdentifier.DefaultMetricNamespace"/> will be used.
/// To specify another namespace, use an overload that takes a <c>MetricIdentifier</c> parameter instead.)</param>
/// <param name="dimension1Name">The name of the first dimension.</param>
/// <param name="dimension2Name">The name of the second dimension.</param>
/// <param name="metricConfiguration">Determines how tracked values will be aggregated. <br />
/// Use presets in <see cref="MetricConfigurations.Common"/> or specify your own settings. </param>
/// <returns>A <c>Metric</c> with the specified ID and dimensions. If you call this method several times
/// with the same metric ID and dimensions for a given aggregation scope, you will receive the same
/// instance of <c>Metric</c>.</returns>
/// <exception cref="ArgumentException">If you previously created a metric with the same namespace, ID, dimensions
/// and aggregation scope, but with a different configuration. When calling this method to get a previously
/// created metric, you can simply avoid specifying any configuration (or specify null) to imply the
/// configuration used earlier.</exception>
public Metric GetMetric(
string metricId,
string dimension1Name,
string dimension2Name,
MetricConfiguration metricConfiguration)
{
return this.GetOrCreateMetric(
MetricAggregationScope.TelemetryConfiguration,
new MetricIdentifier(MetricIdentifier.DefaultMetricNamespace, metricId, dimension1Name, dimension2Name),
metricConfiguration);
}
/// <summary>
/// Gets or creates a metric container that you can use to track, aggregate and send metric values.<br />
/// Optionally specify a metric configuration to control how the tracked values are aggregated.
/// </summary>
/// <param name="metricId">The ID (name) of the metric.
/// (The namespace specified in <see cref="MetricIdentifier.DefaultMetricNamespace"/> will be used.
/// To specify another namespace, use an overload that takes a <c>MetricIdentifier</c> parameter instead.)</param>
/// <param name="dimension1Name">The name of the first dimension.</param>
/// <param name="dimension2Name">The name of the second dimension.</param>
/// <param name="metricConfiguration">Determines how tracked values will be aggregated. <br />
/// Use presets in <see cref="MetricConfigurations.Common"/> or specify your own settings. </param>
/// <returns>A <c>Metric</c> with the specified ID and dimensions. If you call this method several times
/// with the same metric ID and dimensions for a given aggregation scope, you will receive the same
/// instance of <c>Metric</c>.</returns>
/// <exception cref="ArgumentException">If you previously created a metric with the same namespace, ID, dimensions
/// and aggregation scope, but with a different configuration. When calling this method to get a previously
/// created metric, you can simply avoid specifying any configuration (or specify null) to imply the
/// configuration used earlier.</exception>
/// <param name="aggregationScope">The scope across which the values for the metric are to be aggregated in memory.
/// See <see cref="MetricAggregationScope" /> for more info.</param>
public Metric GetMetric(
string metricId,
string dimension1Name,
string dimension2Name,
MetricConfiguration metricConfiguration,
MetricAggregationScope aggregationScope)
{
return this.GetOrCreateMetric(
aggregationScope,
new MetricIdentifier(MetricIdentifier.DefaultMetricNamespace, metricId, dimension1Name, dimension2Name),
metricConfiguration);
}
/// <summary>
/// Gets or creates a metric container that you can use to track, aggregate and send metric values.<br />
/// Optionally specify a metric configuration to control how the tracked values are aggregated.