-
-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathHub.cs
More file actions
898 lines (780 loc) · 31.2 KB
/
Hub.cs
File metadata and controls
898 lines (780 loc) · 31.2 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
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
using Sentry.Extensibility;
using Sentry.Infrastructure;
using Sentry.Internal.Extensions;
using Sentry.Protocol.Envelopes;
using Sentry.Protocol.Metrics;
namespace Sentry.Internal;
internal class Hub : IHub, IHubInternal, IDisposable
{
private readonly Lock _sessionPauseLock = new();
private readonly ISystemClock _clock;
private readonly ISessionManager _sessionManager;
private readonly SentryOptions _options;
private readonly ISampleRandHelper _sampleRandHelper;
private readonly RandomValuesFactory _randomValuesFactory;
private readonly IReplaySession _replaySession;
private readonly List<IDisposable> _integrationsToCleanup = new();
private readonly BackpressureMonitor? _backpressureMonitor;
#if MEMORY_DUMP_SUPPORTED
private readonly MemoryMonitor? _memoryMonitor;
#endif
private InterlockedBoolean _isPersistedSessionRecovered;
// Internal for testability
internal ConditionalWeakTable<Exception, ISpan> ExceptionToSpanMap { get; } = new();
internal IInternalScopeManager ScopeManager { get; }
private InterlockedBoolean _isEnabled = true;
public bool IsEnabled => _isEnabled;
public bool IsSessionActive => _sessionManager.IsSessionActive;
internal SentryOptions Options => _options;
private Scope CurrentScope => ScopeManager.GetCurrent().Key;
private ISentryClient CurrentClient => ScopeManager.GetCurrent().Value;
internal Hub(
SentryOptions options,
ISentryClient? client = null,
ISessionManager? sessionManager = null,
ISystemClock? clock = null,
IInternalScopeManager? scopeManager = null,
RandomValuesFactory? randomValuesFactory = null,
IReplaySession? replaySession = null,
ISampleRandHelper? sampleRandHelper = null,
BackpressureMonitor? backpressureMonitor = null)
{
if (string.IsNullOrWhiteSpace(options.Dsn))
{
const string msg = "Attempt to instantiate a Hub without a DSN.";
options.LogFatal(msg);
throw new InvalidOperationException(msg);
}
options.LogDebug("Initializing Hub for Dsn: '{0}'.", options.Dsn);
_options = options;
_randomValuesFactory = randomValuesFactory ?? new SynchronizedRandomValuesFactory();
_sessionManager = sessionManager ?? new GlobalSessionManager(options);
_clock = clock ?? SystemClock.Clock;
if (_options.EnableBackpressureHandling)
{
_backpressureMonitor = backpressureMonitor ?? new BackpressureMonitor(_options.DiagnosticLogger, clock);
}
client ??= new SentryClient(options, randomValuesFactory: _randomValuesFactory, sessionManager: _sessionManager, backpressureMonitor: _backpressureMonitor);
_replaySession = replaySession ?? ReplaySession.Instance;
_sampleRandHelper = sampleRandHelper ?? new SampleRandHelperAdapter();
ScopeManager = scopeManager ?? new SentryScopeManager(options, client);
if (!options.IsGlobalModeEnabled)
{
// Push the first scope so the async local starts from here
PushScope();
}
Logger = SentryStructuredLogger.Create(this, options, _clock);
Metrics = SentryMetricEmitter.Create(this, options, _clock);
#if MEMORY_DUMP_SUPPORTED
if (options.HeapDumpOptions is not null)
{
if (_options.DisableFileWrite)
{
_options.LogError("Automatic Heap Dumps cannot be used with file write disabled.");
}
else
{
_memoryMonitor = new MemoryMonitor(options, CaptureHeapDump);
}
}
#endif
foreach (var integration in options.Integrations)
{
options.LogDebug("Registering integration: '{0}'.", integration.GetType().Name);
integration.Register(this, options);
if (integration is IDisposable disposableIntegration)
{
_integrationsToCleanup.Add(disposableIntegration);
}
}
}
public void ConfigureScope(Action<Scope> configureScope)
{
try
{
ScopeManager.ConfigureScope(configureScope);
}
catch (Exception e)
{
_options.LogError(e, "Failure to ConfigureScope");
}
}
public void ConfigureScope<TArg>(Action<Scope, TArg> configureScope, TArg arg)
{
try
{
ScopeManager.ConfigureScope(configureScope, arg);
}
catch (Exception e)
{
_options.LogError(e, "Failure to ConfigureScope<TArg>");
}
}
public async Task ConfigureScopeAsync(Func<Scope, Task> configureScope)
{
try
{
await ScopeManager.ConfigureScopeAsync(configureScope).ConfigureAwait(false);
}
catch (Exception e)
{
_options.LogError(e, "Failure to ConfigureScopeAsync");
}
}
public async Task ConfigureScopeAsync<TArg>(Func<Scope, TArg, Task> configureScope, TArg arg)
{
try
{
await ScopeManager.ConfigureScopeAsync(configureScope, arg).ConfigureAwait(false);
}
catch (Exception e)
{
_options.LogError(e, "Failure to ConfigureScopeAsync<TArg>");
}
}
public void SetTag(string key, string value) => ScopeManager.SetTag(key, value);
public void UnsetTag(string key) => ScopeManager.UnsetTag(key);
public IDisposable PushScope() => ScopeManager.PushScope();
public IDisposable PushScope<TState>(TState state) => ScopeManager.PushScope(state);
public void RestoreScope(Scope savedScope) => ScopeManager.RestoreScope(savedScope);
public void BindClient(ISentryClient client) => ScopeManager.BindClient(client);
public ITransactionTracer StartTransaction(
ITransactionContext context,
IReadOnlyDictionary<string, object?> customSamplingContext)
=> StartTransaction(context, customSamplingContext, null);
public ITransactionTracer StartTransaction(ITransactionContext context, TimeSpan? idleTimeout)
=> StartTransaction(context, new Dictionary<string, object?>(), null, idleTimeout);
internal ITransactionTracer StartTransaction(
ITransactionContext context,
IReadOnlyDictionary<string, object?> customSamplingContext,
DynamicSamplingContext? dynamicSamplingContext,
TimeSpan? idleTimeout = null)
{
// If the hub is disabled, we will always sample out. In other words, starting a transaction
// after disposing the hub will result in that transaction not being sent to Sentry.
if (!IsEnabled)
{
return NoOpTransaction.Instance;
}
bool? isSampled = null;
double? sampleRate = null;
DiscardReason? discardReason = null;
var sampleRand = dynamicSamplingContext?.Items.TryGetValue("sample_rand", out var dscSampleRand) ?? false
? double.Parse(dscSampleRand, NumberStyles.Float, CultureInfo.InvariantCulture)
: _sampleRandHelper.GenerateSampleRand(context.TraceId.ToString());
// TracesSampler runs regardless of whether a decision has already been made, as it can be used to override it.
if (_options.TracesSampler is { } tracesSampler)
{
var samplingContext = new TransactionSamplingContext(
context,
customSamplingContext);
if (tracesSampler(samplingContext) is { } samplerSampleRate)
{
// The TracesSampler trumps all other sampling decisions (even the trace header)
sampleRate = samplerSampleRate * _backpressureMonitor.GetDownsampleFactor();
isSampled = SampleRandHelper.IsSampled(sampleRand, sampleRate.Value);
if (isSampled is false)
{
// If sampling out is only a result of the downsampling then we specify the reason as backpressure
// management... otherwise the event would have been sampled out anyway, so it's just regular sampling.
discardReason = sampleRand < samplerSampleRate ? DiscardReason.Backpressure : DiscardReason.SampleRate;
}
// Ensure the actual sampleRate is set on the provided DSC (if any) when the TracesSampler reached a sampling decision
dynamicSamplingContext?.SetSampleRate(samplerSampleRate);
}
}
// If the sampling decision isn't made by a trace sampler we check the trace header first (from the context) or
// finally fallback to Random sampling if the decision has been made by no other means
if (isSampled == null)
{
var optionsSampleRate = _options.TracesSampleRate ?? 0.0;
sampleRate = optionsSampleRate * _backpressureMonitor.GetDownsampleFactor();
isSampled = context.IsSampled ?? SampleRandHelper.IsSampled(sampleRand, sampleRate.Value);
if (isSampled is false)
{
// If sampling out is only a result of the downsampling then we specify the reason as backpressure
// management... otherwise the event would have been sampled out anyway, so it's just regular sampling.
discardReason = sampleRand < optionsSampleRate ? DiscardReason.Backpressure : DiscardReason.SampleRate;
}
if (context.IsSampled is null && _options.TracesSampleRate is not null)
{
// Ensure the actual sampleRate is set on the provided DSC (if any) when not IsSampled upstream but the TracesSampleRate reached a sampling decision
dynamicSamplingContext?.SetSampleRate(_options.TracesSampleRate.Value);
}
}
// Make sure there is a replayId (if available) on the provided DSC (if any).
dynamicSamplingContext?.SetReplayId(_replaySession);
if (isSampled is false)
{
var unsampledTransaction = new UnsampledTransaction(this, context)
{
SampleRate = sampleRate,
SampleRand = sampleRand,
DiscardReason = discardReason,
DynamicSamplingContext = dynamicSamplingContext // Default to the provided DSC
};
// If no DSC was provided, create one based on this transaction.
// Must be done AFTER the sampling decision has been made (the DSC propagates sampling decisions).
unsampledTransaction.DynamicSamplingContext ??= unsampledTransaction.CreateDynamicSamplingContext(_options, _replaySession);
return unsampledTransaction;
}
var transaction = new TransactionTracer(this, context, idleTimeout)
{
SampleRate = sampleRate,
SampleRand = sampleRand,
DynamicSamplingContext = dynamicSamplingContext // Default to the provided DSC
};
// If no DSC was provided, create one based on this transaction.
// Must be done AFTER the sampling decision has been made (the DSC propagates sampling decisions).
transaction.DynamicSamplingContext ??= transaction.CreateDynamicSamplingContext(_options, _replaySession);
if (_options.TransactionProfilerFactory is { } profilerFactory &&
_randomValuesFactory.NextBool(_options.ProfilesSampleRate ?? 0.0))
{
// TODO cancellation token based on Hub being closed?
transaction.TransactionProfiler = profilerFactory.Start(transaction, CancellationToken.None);
}
// A sampled out transaction still appears fully functional to the user
// but will be dropped by the client and won't reach Sentry's servers.
return transaction;
}
public void BindException(Exception exception, ISpan span)
{
// Don't bind on sampled out spans
if (span.IsSampled == false)
{
return;
}
// Don't overwrite existing pair in the unlikely event that it already exists
_ = ExceptionToSpanMap.GetValue(exception, _ => span);
}
public ISpan? GetSpan() => CurrentScope.Span;
public SentryTraceHeader GetTraceHeader()
{
if (GetSpan()?.GetTraceHeader() is { } traceHeader)
{
return traceHeader;
}
// With either tracing disabled or no active span on the current scope we fall back to the propagation context
var propagationContext = CurrentScope.PropagationContext;
// In either case, we must not append a sampling decision.
return new SentryTraceHeader(propagationContext.TraceId, propagationContext.SpanId, null);
}
public BaggageHeader GetBaggage()
{
var span = GetSpan();
if (span?.GetTransaction().GetDynamicSamplingContext() is { IsEmpty: false } dsc)
{
return dsc.ToBaggageHeader();
}
var propagationContext = CurrentScope.PropagationContext;
return propagationContext.GetOrCreateDynamicSamplingContext(_options, _replaySession).ToBaggageHeader();
}
public W3CTraceparentHeader? GetTraceparentHeader()
{
if (GetSpan()?.GetTraceHeader() is { } traceHeader)
{
return new W3CTraceparentHeader(traceHeader.TraceId, traceHeader.SpanId, traceHeader.IsSampled);
}
// We fall back to the propagation context
var propagationContext = CurrentScope.PropagationContext;
return new W3CTraceparentHeader(propagationContext.TraceId, propagationContext.SpanId, null);
}
public TransactionContext ContinueTrace(
string? traceHeader,
string? baggageHeader,
string? name = null,
string? operation = null)
{
SentryTraceHeader? sentryTraceHeader = null;
if (traceHeader is not null)
{
sentryTraceHeader = SentryTraceHeader.Parse(traceHeader);
}
BaggageHeader? sentryBaggageHeader = null;
if (baggageHeader is not null)
{
sentryBaggageHeader = BaggageHeader.TryParse(baggageHeader, onlySentry: true);
}
return ContinueTrace(sentryTraceHeader, sentryBaggageHeader, name, operation);
}
public TransactionContext ContinueTrace(
SentryTraceHeader? traceHeader,
BaggageHeader? baggageHeader,
string? name = null,
string? operation = null)
{
var propagationContext = SentryPropagationContext.CreateFromHeaders(_options.DiagnosticLogger, traceHeader, baggageHeader, _replaySession);
ConfigureScope(static (scope, propagationContext) => scope.SetPropagationContext(propagationContext), propagationContext);
return new TransactionContext(
name: name ?? string.Empty,
operation: operation ?? string.Empty,
spanId: propagationContext.SpanId,
parentSpanId: propagationContext.ParentSpanId,
traceId: propagationContext.TraceId,
isSampled: traceHeader?.IsSampled,
isParentSampled: traceHeader?.IsSampled);
}
public void StartSession()
{
// Attempt to recover persisted session left over from previous run
if (_isPersistedSessionRecovered.Exchange(true) != true)
{
try
{
var recoveredSessionUpdate = _sessionManager.TryRecoverPersistedSession();
if (recoveredSessionUpdate is not null)
{
CaptureSession(recoveredSessionUpdate);
}
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to recover persisted session.");
}
}
// Start a new session
try
{
var sessionUpdate = _sessionManager.StartSession();
if (sessionUpdate is not null)
{
CaptureSession(sessionUpdate);
}
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to start a session.");
}
}
public void PauseSession()
{
lock (_sessionPauseLock)
{
try
{
_sessionManager.PauseSession();
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to pause a session.");
}
}
}
public void ResumeSession()
{
lock (_sessionPauseLock)
{
try
{
foreach (var update in _sessionManager.ResumeSession())
{
CaptureSession(update);
}
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to resume a session.");
}
}
}
private void EndSession(DateTimeOffset timestamp, SessionEndStatus status)
{
try
{
var sessionUpdate = _sessionManager.EndSession(timestamp, status);
if (sessionUpdate is not null)
{
CaptureSession(sessionUpdate);
}
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to end a session.");
}
}
public void EndSession(SessionEndStatus status = SessionEndStatus.Exited) =>
EndSession(_clock.GetUtcNow(), status);
private ISpan? GetLinkedSpan(SentryEvent evt)
{
// Find the span which is bound to the same exception
if (evt.Exception is { } exception &&
ExceptionToSpanMap.TryGetValue(exception, out var spanBoundToException))
{
return spanBoundToException;
}
return null;
}
private void ApplyTraceContextToEvent(SentryEvent evt, ISpan span)
{
evt.Contexts.Trace.SpanId = span.SpanId;
evt.Contexts.Trace.TraceId = span.TraceId;
evt.Contexts.Trace.ParentSpanId = span.ParentSpanId;
if (span.GetTransaction().GetDynamicSamplingContext() is { } dsc)
{
evt.DynamicSamplingContext = dsc;
}
}
private void ApplyTraceContextToEvent(SentryEvent evt, SentryPropagationContext propagationContext)
{
evt.Contexts.Trace.TraceId = propagationContext.TraceId;
evt.Contexts.Trace.SpanId = propagationContext.SpanId;
evt.Contexts.Trace.ParentSpanId = propagationContext.ParentSpanId;
evt.DynamicSamplingContext = propagationContext.GetOrCreateDynamicSamplingContext(_options, _replaySession);
}
public bool CaptureEnvelope(Envelope envelope) => CurrentClient.CaptureEnvelope(envelope);
private void AddBreadcrumbForException(SentryEvent evt, Scope scope)
{
try
{
if (!IsEnabled || evt.Exception is not { } exception)
{
return;
}
var exceptionMessage = exception.Message ?? "";
var formatted = evt.Message?.Formatted;
string breadcrumbMessage;
Dictionary<string, string>? data = null;
if (string.IsNullOrWhiteSpace(formatted))
{
breadcrumbMessage = exceptionMessage;
}
else
{
breadcrumbMessage = formatted;
// Exception.Message won't be used as Breadcrumb message
// Avoid losing it by adding as data:
data = new Dictionary<string, string>
{
{"exception_message", exceptionMessage}
};
}
scope.AddBreadcrumb(breadcrumbMessage, "Exception", data: data, level: BreadcrumbLevel.Fatal);
}
catch (Exception e)
{
_options.LogError(e, "Failure to store breadcrumb for exception event: '{0}'", evt.EventId);
}
}
public SentryId CaptureEvent(SentryEvent evt, Action<Scope> configureScope)
=> CaptureEvent(evt, null, configureScope);
public SentryId CaptureEvent(SentryEvent evt, SentryHint? hint, Action<Scope> configureScope)
{
if (!IsEnabled)
{
return SentryId.Empty;
}
try
{
var clonedScope = CurrentScope.Clone();
configureScope(clonedScope);
// Although we clone a temporary scope for the configureScope action, for the second scope
// argument (the breadcrumbScope) we pass in the current scope... this is because we want
// a breadcrumb to be left on the current scope for exception events
var eventId = CaptureEvent(evt, hint, clonedScope);
AddBreadcrumbForException(evt, CurrentScope);
return eventId;
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture event: {0}", evt.EventId);
return SentryId.Empty;
}
}
public SentryId CaptureEvent(SentryEvent evt, Scope? scope = null, SentryHint? hint = null)
{
scope ??= CurrentScope;
var eventId = CaptureEvent(evt, hint, scope);
AddBreadcrumbForException(evt, scope);
return eventId;
}
private SentryId CaptureEvent(SentryEvent evt, SentryHint? hint, Scope scope)
{
if (!IsEnabled)
{
return SentryId.Empty;
}
try
{
// We get the span linked to the event or fall back to the current span
var span = GetLinkedSpan(evt) ?? scope.Span;
if (span is not null)
{
ApplyTraceContextToEvent(evt, span);
}
else
{
// If there is no span on the scope (and not just no sampled one), fall back to the propagation context
ApplyTraceContextToEvent(evt, scope.PropagationContext);
}
// Now capture the event with the Sentry client on the current scope.
var id = CurrentClient.CaptureEvent(evt, scope, hint);
scope.LastEventId = id;
scope.SessionUpdate = null;
if (evt.GetExceptionType() is SentryEvent.ExceptionType.UnhandledTerminal
&& scope.Transaction is { } transaction)
{
// Event contains a terminal exception -> finish any current transaction as aborted
// Do this *after* the event was captured, so that the event is still linked to the transaction.
_options.LogDebug("Ending transaction as Aborted, due to unhandled exception.");
transaction.Finish(SpanStatus.Aborted);
}
return id;
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture event: {0}", evt.EventId);
return SentryId.Empty;
}
}
public SentryId CaptureFeedback(SentryFeedback feedback, out CaptureFeedbackResult result,
Action<Scope> configureScope, SentryHint? hint = null)
{
if (!IsEnabled)
{
result = CaptureFeedbackResult.DisabledHub;
return SentryId.Empty;
}
try
{
var clonedScope = CurrentScope.Clone();
configureScope(clonedScope);
return CaptureFeedback(feedback, out result, clonedScope, hint);
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture feedback");
result = CaptureFeedbackResult.UnknownError;
return SentryId.Empty;
}
}
public SentryId CaptureFeedback(SentryFeedback feedback, out CaptureFeedbackResult result, Scope? scope = null,
SentryHint? hint = null)
{
if (!IsEnabled)
{
result = CaptureFeedbackResult.DisabledHub;
return SentryId.Empty;
}
try
{
if (!string.IsNullOrWhiteSpace(feedback.ContactEmail) && !EmailValidator.IsValidEmail(feedback.ContactEmail))
{
_options.LogWarning("Feedback email scrubbed due to invalid email format: '{0}'", feedback.ContactEmail);
feedback.ContactEmail = null;
}
scope ??= CurrentScope;
return CurrentClient.CaptureFeedback(feedback, out result, scope, hint);
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture feedback");
result = CaptureFeedbackResult.UnknownError;
return SentryId.Empty;
}
}
#if MEMORY_DUMP_SUPPORTED
internal void CaptureHeapDump(string dumpFile)
{
if (!IsEnabled)
{
return;
}
try
{
_options.LogDebug("Capturing heap dump '{0}'", dumpFile);
var evt = new SentryEvent
{
Message = "Memory threshold exceeded",
Level = _options.HeapDumpOptions?.Level ?? SentryLevel.Warning,
};
var hint = new SentryHint(_options);
hint.AddAttachment(dumpFile);
CaptureEvent(evt, CurrentScope, hint);
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture heap dump");
}
}
#endif
public void CaptureTransaction(SentryTransaction transaction) => CaptureTransaction(transaction, null, null);
public void CaptureTransaction(SentryTransaction transaction, Scope? scope, SentryHint? hint)
{
// Note: The hub should capture transactions even if it is disabled.
// This allows transactions to be reported as failed when they encountered an unhandled exception,
// in the case where the hub was disabled before the transaction was captured.
// For example, that can happen with a top-level async main because IDisposables are processed before
// the unhandled exception event fires.
//
// Any transactions started after the hub was disabled will already be sampled out and thus will
// not be passed along to sentry when captured here.
try
{
CurrentClient.CaptureTransaction(transaction, scope ?? CurrentScope, hint);
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture transaction: {0}", transaction.SpanId);
}
}
public void CaptureMetrics(IEnumerable<Metric> metrics)
{
if (!IsEnabled)
{
return;
}
Metric[]? enumerable = null;
try
{
enumerable = metrics as Metric[] ?? metrics.ToArray();
_options.LogDebug("Capturing metrics.");
CurrentClient.CaptureEnvelope(Envelope.FromMetrics(metrics));
}
catch (Exception e)
{
var metricEventIds = enumerable?.Select(m => m.EventId).ToArray() ?? [];
_options.LogError(e, "Failure to capture metrics: {0}", string.Join(",", metricEventIds));
}
}
public void CaptureCodeLocations(CodeLocations codeLocations)
{
if (!IsEnabled)
{
return;
}
try
{
_options.LogDebug("Capturing code locations for period: {0}", codeLocations.Timestamp);
CurrentClient.CaptureEnvelope(Envelope.FromCodeLocations(codeLocations));
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture code locations");
}
}
public void CaptureSession(SessionUpdate sessionUpdate)
{
if (!IsEnabled)
{
return;
}
try
{
CurrentClient.CaptureSession(sessionUpdate);
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture session update: {0}", sessionUpdate.Id);
}
}
public SentryId CaptureCheckIn(
string monitorSlug,
CheckInStatus status,
SentryId? sentryId = null,
TimeSpan? duration = null,
Scope? scope = null,
Action<SentryMonitorOptions>? configureMonitorOptions = null)
{
if (!IsEnabled)
{
return SentryId.Empty;
}
try
{
_options.LogDebug("Capturing '{0}' check-in for '{1}'", status, monitorSlug);
scope ??= CurrentScope;
return CurrentClient.CaptureCheckIn(monitorSlug, status, sentryId, duration, scope, configureMonitorOptions);
}
catch (Exception e)
{
_options.LogError(e, "Failed to capture check in for: {0}", monitorSlug);
}
return SentryId.Empty;
}
// Internal capture method that allows the Unity SDK to send attachments after an already captured event.
// Kept internal as the preferred way of adding attachments is either on the scope or directly on the event.
// See https://develop.sentry.dev/sdk/data-model/envelope-items/#attachment
internal bool CaptureAttachment(SentryId eventId, SentryAttachment attachment)
{
if (!IsEnabled || eventId == SentryId.Empty || attachment.IsNull())
{
return false;
}
try
{
var envelope = Envelope.FromAttachment(eventId, attachment, _options.DiagnosticLogger);
return CaptureEnvelope(envelope);
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture attachment");
return false;
}
}
public async Task FlushAsync(TimeSpan timeout)
{
try
{
Logger.Flush();
Metrics.Flush();
await CurrentClient.FlushAsync(timeout).ConfigureAwait(false);
}
catch (Exception e)
{
_options.LogError(e, "Failure to Flush events");
}
}
public void Dispose()
{
_options.LogInfo("Disposing the Hub.");
if (!_isEnabled.Exchange(false))
{
return;
}
foreach (var integration in _integrationsToCleanup)
{
try
{
integration.Dispose();
}
catch (Exception e)
{
_options.LogError("Failed to dispose integration {0}: {1}", integration.GetType().Name, e);
}
}
#if MEMORY_DUMP_SUPPORTED
_memoryMonitor?.Dispose();
#endif
Logger.Flush();
Metrics.Flush();
(Logger as IDisposable)?.Dispose(); // see Sentry.Internal.DefaultSentryStructuredLogger
(Metrics as IDisposable)?.Dispose(); // see Sentry.Internal.DefaultSentryMetricEmitter
try
{
CurrentClient.FlushAsync(_options.ShutdownTimeout).ConfigureAwait(false).GetAwaiter().GetResult();
}
catch (Exception e)
{
_options.LogError(e, "Failed to wait on disposing tasks to flush.");
}
//Don't dispose of ScopeManager since we want dangling transactions to still be able to access tags.
// Don't dispose of _backpressureMonitor since we want the client to continue to process envelopes without
// throwing an ObjectDisposedException.
#if __IOS__
// TODO
#elif ANDROID
// TODO: For some reason the integration tests on Android fail if we Close on the Java SDK...
// https://github.com/getsentry/sentry-dotnet/blob/0adaddb7ad91d0b41a2c38aacc64727ce54b2a3b/integration-test/android.Tests.ps1#L154
// JavaSdk.Sentry.Close();
#elif NET8_0_OR_GREATER
if (SentryNative.IsAvailable)
{
_options?.LogDebug("Closing native SDK");
SentrySdk.CloseNativeSdk();
}
#endif
}
public SentryId LastEventId => CurrentScope.LastEventId;
public SentryStructuredLogger Logger { get; }
public SentryMetricEmitter Metrics { get; }
}