-
-
Notifications
You must be signed in to change notification settings - Fork 220
/
Copy pathSentryOptions.cs
1831 lines (1626 loc) · 70.6 KB
/
SentryOptions.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
using Sentry.Extensibility;
using Sentry.Http;
using Sentry.Infrastructure;
using Sentry.Integrations;
using Sentry.Internal;
using Sentry.Internal.Extensions;
using Sentry.Internal.Http;
using Sentry.Internal.ScopeStack;
using Sentry.PlatformAbstractions;
using static Sentry.SentryConstants;
#if HAS_DIAGNOSTIC_INTEGRATION
using Sentry.Internal.DiagnosticSource;
#endif
#if ANDROID
using Sentry.Android;
using Sentry.Android.AssemblyReader;
#endif
#if IOS || MACCATALYST
using ObjCRuntime;
using Sentry.Cocoa;
#endif
namespace Sentry;
/// <summary>
/// Sentry SDK options
/// </summary>
#if __MOBILE__
public partial class SentryOptions
#else
public class SentryOptions
#endif
{
private Dictionary<string, string>? _defaultTags;
private const RegexOptions DefaultRegexOptions = RegexOptions.Compiled | RegexOptions.CultureInvariant;
/// <summary>
/// If set, the <see cref="SentryScopeManager"/> will ignore <see cref="IsGlobalModeEnabled"/>
/// and use the provided container instead.
/// </summary>
/// <remarks>
/// Used by the ASP.NET (classic) integration.
/// </remarks>
internal IScopeStackContainer? ScopeStackContainer { get; set; }
private readonly Lazy<string?> _lazyInstallationId;
internal string? InstallationId => _lazyInstallationId.Value;
#if __MOBILE__
private bool _isGlobalModeEnabled = true;
/// <summary>
/// Specifies whether to use global scope management mode.
/// Should be <c>true</c> for client applications and <c>false</c> for server applications.
/// The default is <c>true</c> for mobile targets.
/// </summary>
public bool IsGlobalModeEnabled
{
get => _isGlobalModeEnabled;
set
{
_isGlobalModeEnabled = value;
if (!value)
{
_diagnosticLogger?.LogWarning("Global Mode should usually be enabled on {0}", DeviceInfo.PlatformName);
}
}
}
#else
private bool? _isGlobalModeEnabled;
/// <summary>
/// Specifies whether to use global scope management mode.
/// Should be <c>true</c> for client applications and <c>false</c> for server applications.
/// The default is <c>false</c>. The default for Blazor WASM, MAUI, and Mobile apps is <c>true</c>.
/// </summary>
public bool IsGlobalModeEnabled
{
get => _isGlobalModeEnabled ??= SentryRuntime.Current.IsBrowserWasm();
set => _isGlobalModeEnabled = value;
}
#endif
/// <summary>
/// A scope set outside of Sentry SDK. If set, the global parameters from the SDK's scope will be sent to the observed scope.<br/>
/// NOTE: EnableScopeSync must be set true for the scope to be synced.
/// </summary>
public IScopeObserver? ScopeObserver { get; set; }
/// <summary>
/// If true, the SDK's scope will be synced with the observed scope.
/// </summary>
public bool EnableScopeSync { get; set; }
/// <summary>
/// This holds a reference to the current transport, when one is active.
/// If set manually before initialization, the provided transport will be used instead of the default transport.
/// </summary>
/// <remarks>
/// If <seealso cref="CacheDirectoryPath"/> is set, any transport set here will be wrapped in a
/// <seealso cref="CachingTransport"/> and used as its inner transport.
/// </remarks>
public ITransport? Transport { get; set; }
private Lazy<IClientReportRecorder> _clientReportRecorder;
internal IClientReportRecorder ClientReportRecorder
{
get => _clientReportRecorder.Value;
set => _clientReportRecorder = new Lazy<IClientReportRecorder>(() => value);
}
private Lazy<ISentryStackTraceFactory> _sentryStackTraceFactory;
internal ISentryStackTraceFactory SentryStackTraceFactory
{
get => _sentryStackTraceFactory.Value;
set => _sentryStackTraceFactory = new Lazy<ISentryStackTraceFactory>(() => value);
}
internal int SentryVersion { get; } = ProtocolVersion;
/// <summary>
/// A list of exception processors
/// </summary>
internal List<(Type Type, Lazy<ISentryEventExceptionProcessor> Lazy)> ExceptionProcessors { get; set; }
/// <summary>
/// A list of transaction processors
/// </summary>
internal List<ISentryTransactionProcessor>? TransactionProcessors { get; set; }
/// <summary>
/// A list of event processors
/// </summary>
internal List<(Type Type, Lazy<ISentryEventProcessor> Lazy)> EventProcessors { get; set; }
/// <summary>
/// A list of providers of <see cref="ISentryEventProcessor"/>
/// </summary>
internal List<Func<IEnumerable<ISentryEventProcessor>>> EventProcessorsProviders { get; set; }
/// <summary>
/// A list of providers of <see cref="ISentryTransactionProcessor"/>
/// </summary>
internal List<Func<IEnumerable<ISentryTransactionProcessor>>> TransactionProcessorsProviders { get; set; }
/// <summary>
/// A list of providers of <see cref="ISentryEventExceptionProcessor"/>
/// </summary>
internal List<Func<IEnumerable<ISentryEventExceptionProcessor>>> ExceptionProcessorsProviders { get; set; }
private DefaultIntegrations _defaultIntegrations;
/// <summary>
/// A list of integrations to be added when the SDK is initialized.
/// </summary>
internal IEnumerable<ISdkIntegration> Integrations
{
get
{
// Auto-session tracking to be the first to run
if ((_defaultIntegrations & DefaultIntegrations.AutoSessionTrackingIntegration) != 0)
{
yield return new AutoSessionTrackingIntegration();
}
#if IOS || MACCATALYST
if ((_defaultIntegrations & DefaultIntegrations.RuntimeMarshalManagedExceptionIntegration) != 0)
{
yield return new RuntimeMarshalManagedExceptionIntegration();
}
#else
if ((_defaultIntegrations & DefaultIntegrations.AppDomainUnhandledExceptionIntegration) != 0)
{
yield return new AppDomainUnhandledExceptionIntegration();
}
#endif
if ((_defaultIntegrations & DefaultIntegrations.AppDomainProcessExitIntegration) != 0)
{
yield return new AppDomainProcessExitIntegration();
}
if ((_defaultIntegrations & DefaultIntegrations.UnobservedTaskExceptionIntegration) != 0)
{
yield return new UnobservedTaskExceptionIntegration();
}
#if NETFRAMEWORK
if ((_defaultIntegrations & DefaultIntegrations.NetFxInstallationsIntegration) != 0)
{
yield return new NetFxInstallationsIntegration();
}
#endif
#if HAS_DIAGNOSTIC_INTEGRATION
if ((_defaultIntegrations & DefaultIntegrations.SentryDiagnosticListenerIntegration) != 0)
{
yield return new SentryDiagnosticListenerIntegration();
}
#endif
#if NET5_0_OR_GREATER && !__MOBILE__
if ((_defaultIntegrations & DefaultIntegrations.WinUiUnhandledExceptionIntegration) != 0
&& RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
yield return new WinUIUnhandledExceptionIntegration();
}
#endif
foreach (var integration in _integrations)
{
yield return integration;
}
}
}
internal List<IExceptionFilter>? ExceptionFilters { get; set; } = new();
/// <summary>
/// List of substrings or regular expression patterns to filter out tags
/// </summary>
public IList<StringOrRegex> TagFilters { get; set; } = new List<StringOrRegex>();
/// <summary>
/// The worker used by the client to pass envelopes.
/// </summary>
public IBackgroundWorker? BackgroundWorker { get; set; }
internal ISentryHttpClientFactory? SentryHttpClientFactory { get; set; }
internal HttpClient GetHttpClient()
{
if (SentryHttpClientFactory is not null)
{
DiagnosticLogger?.LogDebug(
"Using ISentryHttpClientFactory set through options: {0}.",
SentryHttpClientFactory.GetType().Name);
}
var factory = SentryHttpClientFactory ?? new DefaultSentryHttpClientFactory();
return factory.Create(this);
}
/// <summary>
/// Scope state processor.
/// </summary>
public ISentryScopeStateProcessor SentryScopeStateProcessor { get; set; } = new DefaultSentryScopeStateProcessor();
/// <summary>
/// A list of prefixes or patterns used to filter namespaces that are not considered part of application code
/// </summary>
/// <remarks>
/// Sentry by default filters the stacktrace to display only application code.
/// A user can optionally click to see all which will include framework and libraries.
/// </remarks>
/// <example>
/// 'System.', 'Microsoft.'
/// </example>
internal List<StringOrRegex>? InAppExclude { get; set; }
/// <summary>
/// A list of prefixes or patterns used to filter namespaces that are considered part of application code
/// </summary>
/// <remarks>
/// Sentry by default filters the stacktrace to display only application code.
/// A user can optionally click to see all which will include framework and libraries.
/// </remarks>
/// <example>
/// 'System.CustomNamespace', 'Microsoft.Azure.App'
/// </example>
/// <seealso href="https://docs.sentry.io/platforms/dotnet/guides/aspnet/configuration/options/#in-app-include"/>
internal List<StringOrRegex>? InAppInclude { get; set; }
/// <summary>
/// Whether to include default Personal Identifiable information
/// </summary>
/// <remarks>
/// By default PII data like Username and Client IP address are not sent to Sentry.
/// When this flag is turned on, default PII data like Cookies, Claims in Web applications
/// and user data read from the request are sent.
/// </remarks>
public bool SendDefaultPii { get; set; }
/// <summary>
/// Whether to report the <see cref="System.Environment.UserName"/> as the User affected in the event.
/// </summary>
/// <remarks>
/// This configuration is only relevant if <see cref="SendDefaultPii"/> is set to true.
/// In environments like server applications this is set to false in order to not report server account names as user names.
/// </remarks>
public bool IsEnvironmentUser { get; set; } = true;
/// <summary>
/// Gets or sets the name of the server running the application.
/// </summary>
/// <remarks>
/// When <see cref="SendDefaultPii"/> is set to <c>true</c>, <see cref="System.Environment.MachineName"/> is
/// automatically set as ServerName. This property can serve as an override.
/// This is relevant only to server applications.
/// </remarks>
public string? ServerName { get; set; }
/// <summary>
/// Whether to send the stack trace of a event captured without an exception.
/// As of version 3.22.0, the default is <c>true</c>.
/// </summary>
/// <remarks>
/// Append stack trace of the call to the SDK to capture a message or event without Exception
/// </remarks>
public bool AttachStacktrace { get; set; } = true;
/// <summary>
/// Gets or sets the maximum breadcrumbs.
/// </summary>
/// <remarks>
/// When the number of events reach this configuration value,
/// older breadcrumbs start dropping to make room for new ones.
/// </remarks>
/// <value>
/// The maximum breadcrumbs per scope.
/// </value>
public int MaxBreadcrumbs { get; set; } = DefaultMaxBreadcrumbs;
private float? _sampleRate;
/// <summary>
/// The rate to sample error and crash events.
/// </summary>
/// <remarks>
/// Can be anything between 0.01 (1%) and 1.0 (99.9%) or null (default), to disable it.
/// </remarks>
/// <example>
/// 0.1 = 10% of events are sent
/// </example>
/// <see href="https://develop.sentry.dev/sdk/features/#event-sampling"/>
/// <exception cref="InvalidOperationException"></exception>
public float? SampleRate
{
get => _sampleRate;
set
{
if (value is > 1 or <= 0)
{
throw new InvalidOperationException(
$"The value {value} is not valid. Use null to disable or values between 0.01 (inclusive) and 1.0 (exclusive) ");
}
_sampleRate = value;
}
}
/// <summary>
/// The release information for the application.
/// Can be anything, but generally should be either a semantic version string in the format
/// <c>package@version</c> or <c>package@version+build</c>, or a commit SHA from a version control system.
/// </summary>
/// <example>
/// [email protected]+foo
/// 721e41770371db95eee98ca2707686226b993eda
/// 14.1.16.32451
/// </example>
/// <remarks>
/// This value will generally be something along the lines of the git SHA for the given project.
/// If not explicitly defined via configuration or environment variable (SENTRY_RELEASE).
/// It will attempt to read it from:
/// <see cref="System.Reflection.AssemblyInformationalVersionAttribute"/>
/// </remarks>
/// <seealso href="https://docs.sentry.io/platforms/dotnet/configuration/releases/"/>
public string? Release { get; set; }
/// <summary>
/// The distribution of the application, associated with the release set in <see cref="Release"/>.
/// </summary>
/// <example>
/// 22
/// 14G60
/// </example>
/// <remarks>
/// Distributions are used to disambiguate build or deployment variants of the same release of
/// an application. For example, it can be the build number of an XCode (iOS) build, or the version
/// code of an Android build.
/// A distribution can be set under any circumstances, and is passed along to Sentry if provided.
/// However, they are generally relevant only for mobile application scenarios.
/// </remarks>
/// <seealso href="https://develop.sentry.dev/sdk/event-payloads/#optional-attributes"/>
public string? Distribution { get; set; }
/// <summary>
/// The environment the application is running
/// </summary>
/// <remarks>
/// This value can also be set via environment variable: SENTRY_ENVIRONMENT
/// In some cases you don't need to set this manually since integrations, when possible, automatically fill this value.
/// For ASP.NET Core which can read from IHostingEnvironment
/// </remarks>
/// <example>
/// Production, Staging
/// </example>
/// <seealso href="https://docs.sentry.io/platforms/dotnet/configuration/environments/"/>
public string? Environment { get; set; }
private string? _dsn;
/// <summary>
/// The Data Source Name of a given project in Sentry.
/// </summary>
public string? Dsn
{
get => _dsn;
set
{
_dsn = value;
_parsedDsn = null;
}
}
internal Dsn? _parsedDsn;
internal Dsn ParsedDsn => _parsedDsn ??= Sentry.Dsn.Parse(Dsn!);
private readonly Lazy<string> _sentryBaseUrl;
internal bool IsSentryRequest(string? requestUri) =>
!string.IsNullOrEmpty(requestUri) && IsSentryRequest(new Uri(requestUri));
internal bool IsSentryRequest(Uri? requestUri)
{
if (string.IsNullOrEmpty(Dsn) || requestUri is null)
{
return false;
}
var requestBaseUrl = requestUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
return string.Equals(requestBaseUrl, _sentryBaseUrl.Value, StringComparison.OrdinalIgnoreCase);
}
private Func<SentryEvent, SentryHint, SentryEvent?>? _beforeSend;
internal Func<SentryEvent, SentryHint, SentryEvent?>? BeforeSendInternal => _beforeSend;
/// <summary>
/// Configures a callback function to be invoked before sending an event to Sentry
/// </summary>
/// <remarks>
/// The event returned by this callback will be sent to Sentry. This allows the
/// application a chance to inspect and/or modify the event before it's sent. If the
/// event should not be sent at all, return null from the callback.
/// </remarks>
public void SetBeforeSend(Func<SentryEvent, SentryHint, SentryEvent?> beforeSend)
{
_beforeSend = beforeSend;
}
/// <summary>
/// Configures a callback function to be invoked before sending an event to Sentry
/// </summary>
/// <remarks>
/// The event returned by this callback will be sent to Sentry. This allows the
/// application a chance to inspect and/or modify the event before it's sent. If the
/// event should not be sent at all, return null from the callback.
/// </remarks>
public void SetBeforeSend(Func<SentryEvent, SentryEvent?> beforeSend)
{
_beforeSend = (@event, _) => beforeSend(@event);
}
private Func<SentryTransaction, SentryHint, SentryTransaction?>? _beforeSendTransaction;
internal Func<SentryTransaction, SentryHint, SentryTransaction?>? BeforeSendTransactionInternal => _beforeSendTransaction;
/// <summary>
/// Configures a callback to invoke before sending a transaction to Sentry
/// </summary>
/// <param name="beforeSendTransaction">The callback</param>
public void SetBeforeSendTransaction(Func<SentryTransaction, SentryHint, SentryTransaction?> beforeSendTransaction)
{
_beforeSendTransaction = beforeSendTransaction;
}
/// <summary>
/// Configures a callback to invoke before sending a transaction to Sentry
/// </summary>
/// <param name="beforeSendTransaction">The callback</param>
public void SetBeforeSendTransaction(Func<SentryTransaction, SentryTransaction?> beforeSendTransaction)
{
_beforeSendTransaction = (transaction, _) => beforeSendTransaction(transaction);
}
private Func<Breadcrumb, SentryHint, Breadcrumb?>? _beforeBreadcrumb;
internal Func<Breadcrumb, SentryHint, Breadcrumb?>? BeforeBreadcrumbInternal => _beforeBreadcrumb;
/// <summary>
/// Sets a callback function to be invoked when a breadcrumb is about to be stored.
/// </summary>
/// <remarks>
/// Gives a chance to inspect and modify the breadcrumb. If null is returned, the
/// breadcrumb will be discarded. Otherwise the result of the callback will be stored.
/// </remarks>
public void SetBeforeBreadcrumb(Func<Breadcrumb, SentryHint, Breadcrumb?> beforeBreadcrumb)
{
_beforeBreadcrumb = beforeBreadcrumb;
}
/// <summary>
/// Sets a callback function to be invoked when a breadcrumb is about to be stored.
/// </summary>
/// <remarks>
/// Gives a chance to inspect and modify the breadcrumb. If null is returned, the
/// breadcrumb will be discarded. Otherwise the result of the callback will be stored.
/// </remarks>
public void SetBeforeBreadcrumb(Func<Breadcrumb, Breadcrumb?> beforeBreadcrumb)
{
_beforeBreadcrumb = (breadcrumb, _) => beforeBreadcrumb(breadcrumb);
}
private int _maxQueueItems = 30;
/// <summary>
/// The maximum number of events to keep while the worker attempts to send them.
/// </summary>
public int MaxQueueItems
{
get => _maxQueueItems;
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
"At least 1 item must be allowed in the queue.");
}
_maxQueueItems = value;
}
}
/*
* dotnet-gcdump needs .NET 6 or later... also `GC.GetGCMemoryInfo()` is not available in NetFX or NetStandard
*/
#if MEMORY_DUMP_SUPPORTED
/// <summary>
/// <para>
/// Configures a heap dump to be captured if the percentage of memory used exceeds a certain threshold.
/// This can be useful to diagnose memory leaks.
/// </para>
/// <para>
/// Note: This feature requires `dotnet-gcdump` to be installed globally on the machine or container where the heap
/// dumps will be captured. You can install this by running: `dotnet tool install --global dotnet-gcdump`
/// </para>
/// </summary>
/// <remarks>
/// This API is experimental and may change in future versions.
/// </remarks>
/// <param name="memoryPercentageThreshold">
/// The memory threshold at which to trigger a heap dump, as a percentage of total available memory.
/// Must be a number between 1 and 99.
/// </param>
/// <param name="debouncer">
/// Limits the frequency at which heap dumps are captured. If no debouncer is set then this defaults to
/// <code>Debouncer.PerApplicationLifetime()</code>
/// </param>
/// <param name="level">Optional parameter controlling the event level associated with heap dumps.
/// Defaults to <see cref="SentryLevel.Warning"/>.</param>
[Experimental(DiagnosticId.ExperimentalFeature)]
public void EnableHeapDumps(short memoryPercentageThreshold, Debouncer? debouncer = null, SentryLevel level = SentryLevel.Warning)
=> EnableHeapDumps(HeapDumpTriggers.MemoryPercentageThreshold(memoryPercentageThreshold), debouncer, level);
/// <summary>
/// <para>
/// Configures Sentry to capture a heap dump based on a trigger function. This can be useful to diagnose memory leaks.
/// </para>
/// <para>
/// Note: This feature requires `dotnet-gcdump` to be installed globally on the machine or container where the heap
/// dumps will be captured. You can install this by running: `dotnet tool install --global dotnet-gcdump`
/// </para>
/// </summary>
/// <remarks>
/// This API is experimental and may change in future versions.
/// </remarks>
/// <param name="trigger">
/// A custom trigger function that accepts the current memory usage and total available memory as arguments and
/// return true to indicate that a heap dump should be captured or false otherwise.
/// </param>
/// <param name="debouncer">
/// Limits the frequency at which heap dumps are captured. If no debouncer is set then this defaults to
/// <code>Debouncer.PerApplicationLifetime()</code>
/// </param>
/// <param name="level">Optional parameter controlling the event level associated with heap dumps.
/// Defaults to <see cref="SentryLevel.Warning"/>.</param>
[Experimental(DiagnosticId.ExperimentalFeature)]
public void EnableHeapDumps(HeapDumpTrigger trigger, Debouncer? debouncer = null, SentryLevel level = SentryLevel.Warning)
=> HeapDumpOptions = new HeapDumpOptions(trigger, debouncer ?? Debouncer.PerApplicationLifetime(), level);
internal HeapDumpOptions? HeapDumpOptions { get; set; }
#endif
private int _maxCacheItems = 30;
/// <summary>
/// The maximum number of events to keep in cache.
/// This option only works if <see cref="CacheDirectoryPath"/> is configured as well.
/// </summary>
public int MaxCacheItems
{
get => _maxCacheItems;
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
"At least 1 item must be allowed in the cache.");
}
_maxCacheItems = value;
}
}
/// <summary>
/// How long to wait for events to be sent before shutdown
/// </summary>
/// <remarks>
/// In case there are events queued when the SDK is closed, upper bound limit to wait
/// for the worker to send the events to Sentry.
/// </remarks>
/// <example>
/// The SDK is closed while the queue has 1 event queued.
/// The worker takes 50 milliseconds to send an event to Sentry.
/// Even though default settings say 2 seconds, closing the SDK would block for 50ms.
/// </example>
public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(2);
/// <summary>
/// How long to wait for flush operations to finish. Defaults to 2 seconds.
/// </summary>
/// <remarks>
/// When using the <c>Sentry.NLog</c> integration, the default is increased to 15 seconds.
/// </remarks>
public TimeSpan FlushTimeout { get; set; } = TimeSpan.FromSeconds(2);
/// <summary>
/// Decompression methods accepted
/// </summary>
/// <remarks>
/// By default accepts all available compression methods supported by the platform
/// </remarks>
public DecompressionMethods DecompressionMethods { get; set; }
// Note the ~ enabling all bits
= ~DecompressionMethods.None;
/// <summary>
/// The level of which to compress the <see cref="SentryEvent"/> before sending to Sentry
/// </summary>
/// <remarks>
/// To disable request body compression, use <see cref="CompressionLevel.NoCompression"/>
/// </remarks>
public CompressionLevel RequestBodyCompressionLevel { get; set; } = CompressionLevel.Optimal;
/// <summary>
/// Whether the body compression is buffered and the request 'Content-Length' known in advance.
/// </summary>
/// <remarks>
/// Without reading through the Gzip stream to have its final size, it's no possible to use 'Content-Length'
/// header value. That means 'Content-Encoding: chunked' has to be used which is sometimes not supported.
/// Sentry on-premise without a reverse-proxy, for example, does not support 'chunked' requests.
/// </remarks>
/// <see href="https://github.com/getsentry/sentry-dotnet/issues/71"/>
public bool RequestBodyCompressionBuffered { get; set; } = true;
/// <summary>
/// Whether to send client reports, which contain statistics about discarded events.
/// </summary>
/// <see href="https://develop.sentry.dev/sdk/client-reports/"/>
public bool SendClientReports { get; set; } = true;
/// <summary>
/// An optional web proxy
/// </summary>
public IWebProxy? HttpProxy { get; set; }
/// <summary>
/// Creates the inner most <see cref="HttpMessageHandler"/>.
/// </summary>
public Func<HttpMessageHandler>? CreateHttpMessageHandler { get; set; }
/// <summary>
/// A callback invoked when a <see cref="SentryClient"/> is created.
/// </summary>
public Action<HttpClient>? ConfigureClient { get; set; }
private volatile bool _debug;
/// <summary>
/// Whether to log diagnostics messages
/// </summary>
/// <remarks>
/// The verbosity can be controlled through <see cref="DiagnosticLevel"/>
/// and the implementation via <see cref="DiagnosticLogger"/>.
/// </remarks>
public bool Debug
{
get => _debug;
set => _debug = value;
}
/// <summary>
/// The diagnostics level to be used
/// </summary>
/// <remarks>
/// The <see cref="Debug"/> flag has to be switched on for this setting to take effect.
/// </remarks>
public SentryLevel DiagnosticLevel { get; set; } = SentryLevel.Debug;
private volatile IDiagnosticLogger? _diagnosticLogger;
/// <summary>
/// The implementation of the logger.
/// </summary>
/// <remarks>
/// The <see cref="Debug"/> flag has to be switched on for this logger to be used at all.
/// When debugging is turned off, this property is made null and any internal logging results in a no-op.
/// </remarks>
public IDiagnosticLogger? DiagnosticLogger
{
get => Debug ? _diagnosticLogger : null;
set
{
if (value is null)
{
_diagnosticLogger?.LogDebug(
"Sentry will not emit SDK debug messages because debug mode has been turned off.");
}
else
{
_diagnosticLogger?.LogInfo("Replacing current logger with: '{0}'.", value.GetType().Name);
}
_diagnosticLogger = value;
}
}
/// <summary>
/// What mode to use for reporting referenced assemblies in each event sent to sentry. Defaults to <see cref="Sentry.ReportAssembliesMode.Version"/>.
/// </summary>
public ReportAssembliesMode ReportAssembliesMode { get; set; } = ReportAssembliesMode.Version;
/// <summary>
/// What modes to use for event automatic deduplication
/// </summary>
/// <remarks>
/// By default will not drop an event solely for including an inner exception that was already captured.
/// </remarks>
public DeduplicateMode DeduplicateMode { get; set; } = DeduplicateMode.All ^ DeduplicateMode.InnerException;
/// <summary>
/// Path to the root directory used for storing events locally for resilience.
/// If set to <i>null</i>, caching will not be used.
/// </summary>
public string? CacheDirectoryPath { get; set; }
/// <summary>
/// <para>The SDK will only capture HTTP Client errors if it is enabled.</para>
/// <para><see cref="FailedRequestStatusCodes"/> can be used to configure which requests will be treated as failed.</para>
/// <para>Also <see cref="FailedRequestTargets"/> can be used to filter to match only certain request URLs.</para>
/// <para>Defaults to true.</para>
/// </summary>
public bool CaptureFailedRequests { get; set; } = true;
/// <summary>
/// <para>The SDK will only capture HTTP Client errors if the HTTP Response status code is within these defined ranges.</para>
/// <para>Defaults to 500-599 (Server error responses only).</para>
/// </summary>
public IList<HttpStatusCodeRange> FailedRequestStatusCodes { get; set; } = new List<HttpStatusCodeRange>
{
(500, 599)
};
// The default failed request target list will match anything, but adding to the list should clear that.
private Lazy<IList<StringOrRegex>> _failedRequestTargets = new(() =>
new AutoClearingList<StringOrRegex>(
new[] { new StringOrRegex(".*") }, clearOnNextAdd: true));
/// <summary>
/// <para>The SDK will only capture HTTP Client errors if the HTTP Request URL is a match for any of the failedRequestsTargets.</para>
/// <para>Targets may be URLs or Regular expressions.</para>
/// <para>Matches "*." by default.</para>
/// </summary>
public IList<StringOrRegex> FailedRequestTargets
{
get => _failedRequestTargets.Value;
set => _failedRequestTargets = new(value.WithConfigBinding);
}
private IFileSystem? _fileSystem;
/// <summary>
/// Sets the filesystem instance to use. Defaults to the actual <see cref="ReadWriteFileSystem"/>.
/// Used for testing.
/// </summary>
internal IFileSystem FileSystem
{
get => _fileSystem ??= DisableFileWrite ? new ReadOnlyFileSystem() : new ReadWriteFileSystem();
set => _fileSystem = value;
}
/// <summary>
/// Allows to disable the SDKs writing to disk operations
/// </summary>
public bool DisableFileWrite { get; set; }
/// <summary>
/// If set to a positive value, Sentry will attempt to flush existing local event cache when initializing.
/// Set to <see cref="TimeSpan.Zero"/> to disable this feature.
/// This option only works if <see cref="CacheDirectoryPath"/> is configured as well.
/// </summary>
/// <remarks>
/// The trade off here is: Ensure a crash that happens during app start is sent to Sentry
/// even though that might slow down the app start. If set to false, the app might crash
/// too quickly, before Sentry can capture the cached error in the background.
/// </remarks>
public TimeSpan InitCacheFlushTimeout { get; set; } = TimeSpan.FromSeconds(1);
/// <summary>
/// Defaults tags to add to all events. (These are indexed by Sentry).
/// </summary>
/// <remarks>
/// If the key already exists in the event, it will not be overwritten by a default tag.
/// </remarks>
public Dictionary<string, string> DefaultTags
{
get => _defaultTags ??= new Dictionary<string, string>();
internal set => _defaultTags = value;
}
/// <summary>
/// Indicates whether the performance feature is enabled, via either <see cref="TracesSampleRate"/>
/// or <see cref="TracesSampler"/>.
/// </summary>
internal bool IsPerformanceMonitoringEnabled => TracesSampler is not null || TracesSampleRate is > 0.0;
/// <summary>
/// Indicates whether profiling is enabled, via <see cref="TracesSampleRate"/>, or <see cref="TracesSampler"/>
/// </summary>
internal bool IsProfilingEnabled => IsPerformanceMonitoringEnabled && ProfilesSampleRate > 0.0;
private double? _tracesSampleRate;
/// <summary>
/// Indicates the percentage of the tracing data that is collected.
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Effect</description>
/// </listheader>
/// <item>
/// <term><c>>= 0.0 and <=1.0</c></term>
/// <description>
/// A custom sample rate is used unless overriden by a <see cref="TracesSampler"/> function.
/// Values outside of this range are invalid.
/// </description>
/// </item>
/// <item>
/// <term><c>null</c></term>
/// <description>
/// <b>The default setting.</b>
/// The tracing sample rate is determined by the <see cref="TracesSampler"/> function.
/// </description>
/// </item>
/// </list>
/// </summary>
/// <remarks>
/// Random sampling rate is only applied to transactions that don't already
/// have a sampling decision set by other means, such as through <see cref="TracesSampler"/>,
/// by inheriting it from an incoming trace header, or by copying it from <see cref="TransactionContext"/>.
/// </remarks>
public double? TracesSampleRate
{
get => _tracesSampleRate;
set
{
if (value is < 0.0 or > 1.0)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
"The traces sample rate must be between 0.0 and 1.0, inclusive.");
}
_tracesSampleRate = value;
}
}
private double? _profilesSampleRate;
/// <summary>
/// The sampling rate for profiling is relative to <see cref="TracesSampleRate"/>.
/// Setting to 1.0 will profile 100% of sampled transactions.
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Effect</description>
/// </listheader>
/// <item>
/// <term><c>>= 0.0 and <=1.0</c></term>
/// <description>
/// A custom sample rate is. Values outside of this range are invalid.
/// Setting to 0.0 will disable profiling.
/// </description>
/// </item>
/// <item>
/// <term><c>null</c></term>
/// <description>
/// <b>The default setting.</b>
/// At this time, this is equivalent to 0.0, i.e. disabling profiling, but that may change in the future.
/// </description>
/// </item>
/// </list>
/// </summary>
public double? ProfilesSampleRate
{
get => _profilesSampleRate;
set
{
if (value is < 0.0 or > 1.0)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
"The profiles sample rate must be between 0.0 and 1.0, inclusive.");
}
_profilesSampleRate = value;
}
}
/// <summary>
/// Custom delegate that returns sample rate dynamically for a specific transaction context.
/// </summary>
/// <remarks>
/// Returning <c>null</c> signals that the sampler did not reach a sampling decision.
/// In such case, if the transaction already has a sampling decision (for example, if it's
/// started from a trace header) that decision is retained.
/// Otherwise sampling decision is determined by applying the static sampling rate
/// set in <see cref="TracesSampleRate"/>.
/// </remarks>
public Func<TransactionSamplingContext, double?>? TracesSampler { get; set; }
// The default propagation list will match anything, but adding to the list should clear that.
private IList<StringOrRegex> _tracePropagationTargets = new AutoClearingList<StringOrRegex>
(new[] { new StringOrRegex(".*") }, clearOnNextAdd: true);
/// <summary>
/// A customizable list of <see cref="StringOrRegex"/> objects, each containing either a
/// substring or regular expression pattern that can be used to control which outgoing HTTP requests
/// will have the <c>sentry-trace</c>, <c>traceparent</c>, and <c>baggage</c> headers propagated,
/// for purposes of distributed tracing.
/// The default value contains a single value of <c>.*</c>, which matches everything.
/// To disable propagation completely, clear this collection or set it to an empty collection.
/// </summary>
/// <seealso href="https://develop.sentry.dev/sdk/performance/#tracepropagationtargets"/>
/// <remarks>
/// Adding an item to the default list will clear the <c>.*</c> value automatically.
/// </remarks>
public IList<StringOrRegex> TracePropagationTargets
{
// NOTE: During configuration binding, .NET 6 and lower used to just call Add on the existing item.
// .NET 7 changed this to call the setter with an array that already starts with the old value.
// We have to handle both cases.
get => _tracePropagationTargets;
set => _tracePropagationTargets = value.WithConfigBinding();
}
internal ITransactionProfilerFactory? TransactionProfilerFactory { get; set; }
private StackTraceMode? _stackTraceMode;
private readonly List<ISdkIntegration> _integrations;
/// <summary>
/// ATTENTION: This option will change how issues are grouped in Sentry!
/// </summary>
/// <remarks>
/// Sentry groups events by stack traces. If you change this mode and you have thousands of groups,
/// you'll get thousands of new groups. So use this setting with care.
/// </remarks>
public StackTraceMode StackTraceMode
{
get
{
if (_stackTraceMode is not null)
{
return _stackTraceMode.Value;
}
try
{
// from 3.0.0 uses Enhanced (Ben.Demystifier) by default which is a breaking change
// unless you are using .NET Native which isn't compatible with Ben.Demystifier.
_stackTraceMode = SentryRuntime.Current.Name == ".NET Native"
? StackTraceMode.Original
: StackTraceMode.Enhanced;