-
Notifications
You must be signed in to change notification settings - Fork 591
Expand file tree
/
Copy pathscope.py
More file actions
2132 lines (1708 loc) · 72.3 KB
/
scope.py
File metadata and controls
2132 lines (1708 loc) · 72.3 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
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
import os
import sys
import warnings
from copy import copy, deepcopy
from collections import deque
from contextlib import contextmanager
from enum import Enum
from datetime import datetime, timezone
from functools import wraps
from itertools import chain
import sentry_sdk
from sentry_sdk._types import AnnotatedValue
from sentry_sdk.attachments import Attachment
from sentry_sdk.consts import (
DEFAULT_MAX_BREADCRUMBS,
FALSE_VALUES,
INSTRUMENTER,
SPANDATA,
)
from sentry_sdk.feature_flags import FlagBuffer, DEFAULT_FLAG_CAPACITY
from sentry_sdk.profiler.continuous_profiler import (
get_profiler_id,
try_autostart_continuous_profiler,
try_profile_lifecycle_trace_start,
)
from sentry_sdk.profiler.transaction_profiler import Profile
from sentry_sdk.session import Session
from sentry_sdk.tracing_utils import (
Baggage,
has_tracing_enabled,
has_span_streaming_enabled,
is_ignored_span,
_make_sampling_decision,
PropagationContext,
)
from sentry_sdk.traces import _DEFAULT_PARENT_SPAN, StreamedSpan, NoOpStreamedSpan
from sentry_sdk.tracing import (
BAGGAGE_HEADER_NAME,
SENTRY_TRACE_HEADER_NAME,
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk.utils import (
capture_internal_exception,
capture_internal_exceptions,
ContextVar,
datetime_from_isoformat,
disable_capture_event,
event_from_exception,
exc_info_from_error,
format_attribute,
logger,
has_logs_enabled,
has_metrics_enabled,
)
from typing import TYPE_CHECKING, cast
if TYPE_CHECKING:
from collections.abc import Mapping
from typing import Any
from typing import Callable
from typing import Deque
from typing import Dict
from typing import Generator
from typing import Iterator
from typing import List
from typing import Optional
from typing import ParamSpec
from typing import Tuple
from typing import TypeVar
from typing import Union
from typing_extensions import Unpack
from sentry_sdk._types import (
Attributes,
AttributeValue,
Breadcrumb,
BreadcrumbHint,
ErrorProcessor,
Event,
EventProcessor,
ExcInfo,
Hint,
Log,
LogLevelStr,
Metric,
SamplingContext,
Type,
)
from sentry_sdk.tracing import TransactionKwargs
import sentry_sdk
P = ParamSpec("P")
R = TypeVar("R")
F = TypeVar("F", bound=Callable[..., Any])
T = TypeVar("T")
# Holds data that will be added to **all** events sent by this process.
# In case this is a http server (think web framework) with multiple users
# the data will be added to events of all users.
# Typically this is used for process wide data such as the release.
_global_scope: "Optional[Scope]" = None
# Holds data for the active request.
# This is used to isolate data for different requests or users.
# The isolation scope is usually created by integrations, but may also
# be created manually
_isolation_scope = ContextVar("isolation_scope", default=None)
# Holds data for the active span.
# This can be used to manually add additional data to a span.
_current_scope = ContextVar("current_scope", default=None)
global_event_processors: "List[EventProcessor]" = []
# A function returning a (trace_id, span_id) tuple
# from an external tracing source (such as otel)
_external_propagation_context_fn: "Optional[Callable[[], Optional[Tuple[str, str]]]]" = None
class ScopeType(Enum):
CURRENT = "current"
ISOLATION = "isolation"
GLOBAL = "global"
MERGED = "merged"
class _ScopeManager:
def __init__(self, hub: "Optional[Any]" = None) -> None:
self._old_scopes: "List[Scope]" = []
def __enter__(self) -> "Scope":
isolation_scope = Scope.get_isolation_scope()
self._old_scopes.append(isolation_scope)
forked_scope = isolation_scope.fork()
_isolation_scope.set(forked_scope)
return forked_scope
def __exit__(self, exc_type: "Any", exc_value: "Any", tb: "Any") -> None:
old_scope = self._old_scopes.pop()
_isolation_scope.set(old_scope)
def add_global_event_processor(processor: "EventProcessor") -> None:
global_event_processors.append(processor)
def register_external_propagation_context(
fn: "Callable[[], Optional[Tuple[str, str]]]",
) -> None:
global _external_propagation_context_fn
_external_propagation_context_fn = fn
def remove_external_propagation_context() -> None:
global _external_propagation_context_fn
_external_propagation_context_fn = None
def get_external_propagation_context() -> "Optional[Tuple[str, str]]":
return (
_external_propagation_context_fn() if _external_propagation_context_fn else None
)
def has_external_propagation_context() -> bool:
return _external_propagation_context_fn is not None
def _attr_setter(fn: "Any") -> "Any":
return property(fset=fn, doc=fn.__doc__)
def _disable_capture(fn: "F") -> "F":
@wraps(fn)
def wrapper(self: "Any", *args: "Dict[str, Any]", **kwargs: "Any") -> "Any":
if not self._should_capture:
return
try:
self._should_capture = False
return fn(self, *args, **kwargs)
finally:
self._should_capture = True
return wrapper # type: ignore
class Scope:
"""The scope holds extra information that should be sent with all
events that belong to it.
"""
# NOTE: Even though it should not happen, the scope needs to not crash when
# accessed by multiple threads. It's fine if it's full of races, but those
# races should never make the user application crash.
#
# The same needs to hold for any accesses of the scope the SDK makes.
__slots__ = (
"_level",
"_name",
"_fingerprint",
# note that for legacy reasons, _transaction is the transaction *name*,
# not a Transaction object (the object is stored in _span)
"_transaction",
"_transaction_info",
"_user",
"_tags",
"_contexts",
"_extras",
"_breadcrumbs",
"_n_breadcrumbs_truncated",
"_gen_ai_original_message_count",
"_gen_ai_conversation_id",
"_event_processors",
"_error_processors",
"_should_capture",
"_span",
"_session",
"_attachments",
"_force_auto_session_tracking",
"_profile",
"_propagation_context",
"client",
"_type",
"_last_event_id",
"_flags",
"_attributes",
)
def __init__(
self,
ty: "Optional[ScopeType]" = None,
client: "Optional[sentry_sdk.Client]" = None,
) -> None:
self._type = ty
self._event_processors: "List[EventProcessor]" = []
self._error_processors: "List[ErrorProcessor]" = []
self._name: "Optional[str]" = None
self._propagation_context: "Optional[PropagationContext]" = None
self._n_breadcrumbs_truncated: int = 0
self._gen_ai_original_message_count: "Dict[str, int]" = {}
self.client: "sentry_sdk.client.BaseClient" = NonRecordingClient()
if client is not None:
self.set_client(client)
self.clear()
incoming_trace_information = self._load_trace_data_from_env()
self.generate_propagation_context(incoming_data=incoming_trace_information)
def __copy__(self) -> "Scope":
"""
Returns a copy of this scope.
This also creates a copy of all referenced data structures.
"""
rv: "Scope" = object.__new__(self.__class__)
rv._type = self._type
rv.client = self.client
rv._level = self._level
rv._name = self._name
rv._fingerprint = self._fingerprint
rv._transaction = self._transaction
rv._transaction_info = self._transaction_info.copy()
rv._user = self._user
rv._tags = self._tags.copy()
rv._contexts = self._contexts.copy()
rv._extras = self._extras.copy()
rv._breadcrumbs = copy(self._breadcrumbs)
rv._n_breadcrumbs_truncated = self._n_breadcrumbs_truncated
rv._gen_ai_original_message_count = self._gen_ai_original_message_count.copy()
rv._event_processors = self._event_processors.copy()
rv._error_processors = self._error_processors.copy()
rv._propagation_context = self._propagation_context
rv._should_capture = self._should_capture
rv._span = self._span
rv._session = self._session
rv._force_auto_session_tracking = self._force_auto_session_tracking
rv._attachments = self._attachments.copy()
rv._profile = self._profile
rv._last_event_id = self._last_event_id
rv._flags = deepcopy(self._flags)
rv._attributes = self._attributes.copy()
rv._gen_ai_conversation_id = self._gen_ai_conversation_id
return rv
@classmethod
def get_current_scope(cls) -> "Scope":
"""
.. versionadded:: 2.0.0
Returns the current scope.
"""
current_scope = _current_scope.get()
if current_scope is None:
current_scope = Scope(ty=ScopeType.CURRENT)
_current_scope.set(current_scope)
return current_scope
@classmethod
def set_current_scope(cls, new_current_scope: "Scope") -> None:
"""
.. versionadded:: 2.0.0
Sets the given scope as the new current scope overwriting the existing current scope.
:param new_current_scope: The scope to set as the new current scope.
"""
_current_scope.set(new_current_scope)
@classmethod
def get_isolation_scope(cls) -> "Scope":
"""
.. versionadded:: 2.0.0
Returns the isolation scope.
"""
isolation_scope = _isolation_scope.get()
if isolation_scope is None:
isolation_scope = Scope(ty=ScopeType.ISOLATION)
_isolation_scope.set(isolation_scope)
return isolation_scope
@classmethod
def set_isolation_scope(cls, new_isolation_scope: "Scope") -> None:
"""
.. versionadded:: 2.0.0
Sets the given scope as the new isolation scope overwriting the existing isolation scope.
:param new_isolation_scope: The scope to set as the new isolation scope.
"""
_isolation_scope.set(new_isolation_scope)
@classmethod
def get_global_scope(cls) -> "Scope":
"""
.. versionadded:: 2.0.0
Returns the global scope.
"""
global _global_scope
if _global_scope is None:
_global_scope = Scope(ty=ScopeType.GLOBAL)
return _global_scope
def set_global_attributes(self) -> None:
from sentry_sdk.client import SDK_INFO
self.set_attribute("sentry.sdk.name", SDK_INFO["name"])
self.set_attribute("sentry.sdk.version", SDK_INFO["version"])
options = sentry_sdk.get_client().options
server_name = options.get("server_name")
if server_name:
self.set_attribute(SPANDATA.SERVER_ADDRESS, server_name)
environment = options.get("environment")
if environment:
self.set_attribute("sentry.environment", environment)
release = options.get("release")
if release:
self.set_attribute("sentry.release", release)
@classmethod
def last_event_id(cls) -> "Optional[str]":
"""
.. versionadded:: 2.2.0
Returns event ID of the event most recently captured by the isolation scope, or None if no event
has been captured. We do not consider events that are dropped, e.g. by a before_send hook.
Transactions also are not considered events in this context.
The event corresponding to the returned event ID is NOT guaranteed to actually be sent to Sentry;
whether the event is sent depends on the transport. The event could be sent later or not at all.
Even a sent event could fail to arrive in Sentry due to network issues, exhausted quotas, or
various other reasons.
"""
return cls.get_isolation_scope()._last_event_id
def _merge_scopes(
self,
additional_scope: "Optional[Scope]" = None,
additional_scope_kwargs: "Optional[Dict[str, Any]]" = None,
) -> "Scope":
"""
Merges global, isolation and current scope into a new scope and
adds the given additional scope or additional scope kwargs to it.
"""
if additional_scope and additional_scope_kwargs:
raise TypeError("cannot provide scope and kwargs")
final_scope = copy(_global_scope) if _global_scope is not None else Scope()
final_scope._type = ScopeType.MERGED
isolation_scope = _isolation_scope.get()
if isolation_scope is not None:
final_scope.update_from_scope(isolation_scope)
current_scope = _current_scope.get()
if current_scope is not None:
final_scope.update_from_scope(current_scope)
if self != current_scope and self != isolation_scope:
final_scope.update_from_scope(self)
if additional_scope is not None:
if callable(additional_scope):
additional_scope(final_scope)
else:
final_scope.update_from_scope(additional_scope)
elif additional_scope_kwargs:
final_scope.update_from_kwargs(**additional_scope_kwargs)
return final_scope
@classmethod
def get_client(cls) -> "sentry_sdk.client.BaseClient":
"""
.. versionadded:: 2.0.0
Returns the currently used :py:class:`sentry_sdk.Client`.
This checks the current scope, the isolation scope and the global scope for a client.
If no client is available a :py:class:`sentry_sdk.client.NonRecordingClient` is returned.
"""
current_scope = _current_scope.get()
try:
client = current_scope.client
except AttributeError:
client = None
if client is not None and client.is_active():
return client
isolation_scope = _isolation_scope.get()
try:
client = isolation_scope.client
except AttributeError:
client = None
if client is not None and client.is_active():
return client
try:
client = _global_scope.client # type: ignore
except AttributeError:
client = None
if client is not None and client.is_active():
return client
return NonRecordingClient()
def set_client(
self, client: "Optional[sentry_sdk.client.BaseClient]" = None
) -> None:
"""
.. versionadded:: 2.0.0
Sets the client for this scope.
:param client: The client to use in this scope.
If `None` the client of the scope will be replaced by a :py:class:`sentry_sdk.NonRecordingClient`.
"""
if client is not None:
self.client = client
# We need a client to set the initial global attributes on the global
# scope since they mostly come from client options, so populate them
# as soon as a client is set
sentry_sdk.get_global_scope().set_global_attributes()
else:
self.client = NonRecordingClient()
def fork(self) -> "Scope":
"""
.. versionadded:: 2.0.0
Returns a fork of this scope.
"""
forked_scope = copy(self)
return forked_scope
def _load_trace_data_from_env(self) -> "Optional[Dict[str, str]]":
"""
Load Sentry trace id and baggage from environment variables.
Can be disabled by setting SENTRY_USE_ENVIRONMENT to "false".
"""
incoming_trace_information = None
sentry_use_environment = (
os.environ.get("SENTRY_USE_ENVIRONMENT") or ""
).lower()
use_environment = sentry_use_environment not in FALSE_VALUES
if use_environment:
incoming_trace_information = {}
if os.environ.get("SENTRY_TRACE"):
incoming_trace_information[SENTRY_TRACE_HEADER_NAME] = (
os.environ.get("SENTRY_TRACE") or ""
)
if os.environ.get("SENTRY_BAGGAGE"):
incoming_trace_information[BAGGAGE_HEADER_NAME] = (
os.environ.get("SENTRY_BAGGAGE") or ""
)
return incoming_trace_information or None
def set_new_propagation_context(self) -> None:
"""
Creates a new propagation context and sets it as `_propagation_context`. Overwriting existing one.
"""
self._propagation_context = PropagationContext()
def generate_propagation_context(
self, incoming_data: "Optional[Dict[str, str]]" = None
) -> None:
"""
Makes sure the propagation context is set on the scope.
If there is `incoming_data` overwrite existing propagation context.
If there is no `incoming_data` create new propagation context, but do NOT overwrite if already existing.
"""
if incoming_data is not None:
self._propagation_context = PropagationContext.from_incoming_data(
incoming_data
)
# TODO-neel this below is a BIG code smell but requires a bunch of other refactoring
if self._type != ScopeType.CURRENT:
if self._propagation_context is None:
self.set_new_propagation_context()
def get_dynamic_sampling_context(self) -> "Optional[Dict[str, str]]":
"""
Returns the Dynamic Sampling Context from the Propagation Context.
If not existing, creates a new one.
Deprecated: Logic moved to PropagationContext, don't use directly.
"""
if self._propagation_context is None:
return None
return self._propagation_context.dynamic_sampling_context
def get_traceparent(self, *args: "Any", **kwargs: "Any") -> "Optional[str]":
"""
Returns the Sentry "sentry-trace" header (aka the traceparent) from the
currently active span or the scopes Propagation Context.
"""
client = self.get_client()
# If we have an active span, return traceparent from there
if (
has_tracing_enabled(client.options)
and self.span is not None
and not isinstance(self.span, NoOpStreamedSpan)
):
return self.span._to_traceparent()
# else return traceparent from the propagation context
return self.get_active_propagation_context().to_traceparent()
def get_baggage(self, *args: "Any", **kwargs: "Any") -> "Optional[Baggage]":
"""
Returns the Sentry "baggage" header containing trace information from the
currently active span or the scopes Propagation Context.
"""
client = self.get_client()
# If we have an active span, return baggage from there
if (
has_tracing_enabled(client.options)
and self.span is not None
and not isinstance(self.span, NoOpStreamedSpan)
):
return self.span._to_baggage()
# else return baggage from the propagation context
return self.get_active_propagation_context().get_baggage()
def get_trace_context(self) -> "Dict[str, Any]":
"""
Returns the Sentry "trace" context from the Propagation Context.
"""
if (
has_tracing_enabled(self.get_client().options)
and self._span is not None
and not isinstance(self._span, NoOpStreamedSpan)
):
return self._span._get_trace_context()
# if we are tracing externally (otel), those values take precedence
external_propagation_context = get_external_propagation_context()
if external_propagation_context:
trace_id, span_id = external_propagation_context
return {"trace_id": trace_id, "span_id": span_id}
propagation_context = self.get_active_propagation_context()
return {
"trace_id": propagation_context.trace_id,
"span_id": propagation_context.span_id,
"parent_span_id": propagation_context.parent_span_id,
"dynamic_sampling_context": propagation_context.dynamic_sampling_context,
}
def trace_propagation_meta(self, *args: "Any", **kwargs: "Any") -> str:
"""
Return meta tags which should be injected into HTML templates
to allow propagation of trace information.
"""
span = kwargs.pop("span", None)
if span is not None:
logger.warning(
"The parameter `span` in trace_propagation_meta() is deprecated and will be removed in the future."
)
meta = ""
for name, content in self.iter_trace_propagation_headers():
meta += f'<meta name="{name}" content="{content}">'
return meta
def iter_headers(self) -> "Iterator[Tuple[str, str]]":
"""
Creates a generator which returns the `sentry-trace` and `baggage` headers from the Propagation Context.
Deprecated: use PropagationContext.iter_headers instead.
"""
if self._propagation_context is not None:
yield from self._propagation_context.iter_headers()
def iter_trace_propagation_headers(
self, *args: "Any", **kwargs: "Any"
) -> "Generator[Tuple[str, str], None, None]":
"""
Return HTTP headers which allow propagation of trace data.
If a span is given, the trace data will taken from the span.
If no span is given, the trace data is taken from the scope.
"""
client = self.get_client()
if not client.options.get("propagate_traces"):
warnings.warn(
"The `propagate_traces` parameter is deprecated. Please use `trace_propagation_targets` instead.",
DeprecationWarning,
stacklevel=2,
)
return
span = kwargs.pop("span", None)
span = span or self.span
if (
has_tracing_enabled(client.options)
and span is not None
and not isinstance(span, NoOpStreamedSpan)
):
for header in span._iter_headers():
yield header
elif has_external_propagation_context():
# when we have an external_propagation_context (otlp)
# we leave outgoing propagation to the propagator
return
else:
for header in self.get_active_propagation_context().iter_headers():
yield header
def get_active_propagation_context(self) -> "PropagationContext":
if self._propagation_context is not None:
return self._propagation_context
current_scope = self.get_current_scope()
if current_scope._propagation_context is not None:
return current_scope._propagation_context
isolation_scope = self.get_isolation_scope()
# should actually never happen, but just in case someone calls scope.clear
if isolation_scope._propagation_context is None:
isolation_scope._propagation_context = PropagationContext()
return isolation_scope._propagation_context
def set_custom_sampling_context(
self, custom_sampling_context: "dict[str, Any]"
) -> None:
self.get_active_propagation_context()._set_custom_sampling_context(
custom_sampling_context
)
def clear(self) -> None:
"""Clears the entire scope."""
self._level: "Optional[LogLevelStr]" = None
self._fingerprint: "Optional[List[str]]" = None
self._transaction: "Optional[str]" = None
self._transaction_info: "dict[str, str]" = {}
self._user: "Optional[Dict[str, Any]]" = None
self._tags: "Dict[str, Any]" = {}
self._contexts: "Dict[str, Dict[str, Any]]" = {}
self._extras: "dict[str, Any]" = {}
self._attachments: "List[Attachment]" = []
self.clear_breadcrumbs()
self._should_capture: bool = True
self._span: "Optional[Union[Span, StreamedSpan]]" = None
self._session: "Optional[Session]" = None
self._force_auto_session_tracking: "Optional[bool]" = None
self._profile: "Optional[Profile]" = None
self._propagation_context = None
# self._last_event_id is only applicable to isolation scopes
self._last_event_id: "Optional[str]" = None
self._flags: "Optional[FlagBuffer]" = None
self._attributes: "Attributes" = {}
self._gen_ai_conversation_id: "Optional[str]" = None
@_attr_setter
def level(self, value: "LogLevelStr") -> None:
"""
When set this overrides the level.
.. deprecated:: 1.0.0
Use :func:`set_level` instead.
:param value: The level to set.
"""
logger.warning(
"Deprecated: use .set_level() instead. This will be removed in the future."
)
self._level = value
def set_level(self, value: "LogLevelStr") -> None:
"""
Sets the level for the scope.
:param value: The level to set.
"""
self._level = value
@_attr_setter
def fingerprint(self, value: "Optional[List[str]]") -> None:
"""When set this overrides the default fingerprint."""
self._fingerprint = value
@property
def transaction(self) -> "Any":
# would be type: () -> Optional[Transaction], see https://github.com/python/mypy/issues/3004
"""Return the transaction (root span) in the scope, if any."""
# there is no span/transaction on the scope
if self._span is None:
return None
if isinstance(self._span, StreamedSpan):
warnings.warn(
"Scope.transaction is not available in streaming mode.",
DeprecationWarning,
stacklevel=2,
)
return None
# there is an orphan span on the scope
if self._span.containing_transaction is None:
return None
# there is either a transaction (which is its own containing
# transaction) or a non-orphan span on the scope
return self._span.containing_transaction
@transaction.setter
def transaction(self, value: "Any") -> None:
# would be type: (Optional[str]) -> None, see https://github.com/python/mypy/issues/3004
"""When set this forces a specific transaction name to be set.
Deprecated: use set_transaction_name instead."""
# XXX: the docstring above is misleading. The implementation of
# apply_to_event prefers an existing value of event.transaction over
# anything set in the scope.
# XXX: note that with the introduction of the Scope.transaction getter,
# there is a semantic and type mismatch between getter and setter. The
# getter returns a Transaction, the setter sets a transaction name.
# Without breaking version compatibility, we could make the setter set a
# transaction name or transaction (self._span) depending on the type of
# the value argument.
logger.warning(
"Assigning to scope.transaction directly is deprecated: use scope.set_transaction_name() instead."
)
self._transaction = value
if self._span:
if isinstance(self._span, StreamedSpan):
warnings.warn(
"Scope.transaction is not available in streaming mode.",
DeprecationWarning,
stacklevel=2,
)
return None
if self._span.containing_transaction:
self._span.containing_transaction.name = value
def set_transaction_name(self, name: str, source: "Optional[str]" = None) -> None:
"""Set the transaction name and optionally the transaction source."""
self._transaction = name
if self._span:
if isinstance(self._span, NoOpStreamedSpan):
return
elif isinstance(self._span, StreamedSpan):
self._span._segment.name = name
if source:
self._span._segment.set_attribute(
"sentry.span.source", getattr(source, "value", source)
)
elif self._span.containing_transaction:
self._span.containing_transaction.name = name
if source:
self._span.containing_transaction.source = source
if source:
self._transaction_info["source"] = source
@_attr_setter
def user(self, value: "Optional[Dict[str, Any]]") -> None:
"""When set a specific user is bound to the scope. Deprecated in favor of set_user."""
warnings.warn(
"The `Scope.user` setter is deprecated in favor of `Scope.set_user()`.",
DeprecationWarning,
stacklevel=2,
)
self.set_user(value)
def set_user(self, value: "Optional[Dict[str, Any]]") -> None:
"""Sets a user for the scope."""
self._user = value
session = self.get_isolation_scope()._session
if session is not None:
session.update(user=value)
@property
def span(self) -> "Optional[Union[Span, StreamedSpan]]":
"""Get/set current tracing span or transaction."""
return self._span
@span.setter
def span(self, span: "Optional[Union[Span, StreamedSpan]]") -> None:
self._span = span
# XXX: this differs from the implementation in JS, there Scope.setSpan
# does not set Scope._transactionName.
if isinstance(span, Transaction):
transaction = span
if transaction.name:
self._transaction = transaction.name
if transaction.source:
self._transaction_info["source"] = transaction.source
@property
def profile(self) -> "Optional[Profile]":
return self._profile
@profile.setter
def profile(self, profile: "Optional[Profile]") -> None:
self._profile = profile
def set_tag(self, key: str, value: "Any") -> None:
"""
Sets a tag for a key to a specific value.
:param key: Key of the tag to set.
:param value: Value of the tag to set.
"""
self._tags[key] = value
def set_tags(self, tags: "Mapping[str, object]") -> None:
"""Sets multiple tags at once.
This method updates multiple tags at once. The tags are passed as a dictionary
or other mapping type.
Calling this method is equivalent to calling `set_tag` on each key-value pair
in the mapping. If a tag key already exists in the scope, its value will be
updated. If the tag key does not exist in the scope, the key-value pair will
be added to the scope.
This method only modifies tag keys in the `tags` mapping passed to the method.
`scope.set_tags({})` is, therefore, a no-op.
:param tags: A mapping of tag keys to tag values to set.
"""
self._tags.update(tags)
def remove_tag(self, key: str) -> None:
"""
Removes a specific tag.
:param key: Key of the tag to remove.
"""
self._tags.pop(key, None)
def set_context(
self,
key: str,
value: "Dict[str, Any]",
) -> None:
"""
Binds a context at a certain key to a specific value.
"""
self._contexts[key] = value
def remove_context(
self,
key: str,
) -> None:
"""Removes a context."""
self._contexts.pop(key, None)
def set_extra(
self,
key: str,
value: "Any",
) -> None:
"""Sets an extra key to a specific value."""
self._extras[key] = value
def remove_extra(
self,
key: str,
) -> None:
"""Removes a specific extra key."""
self._extras.pop(key, None)
def set_conversation_id(self, conversation_id: str) -> None:
"""
Sets the conversation ID for gen_ai spans.
:param conversation_id: The conversation ID to set.
"""
self._gen_ai_conversation_id = conversation_id
def get_conversation_id(self) -> "Optional[str]":
"""
Gets the conversation ID for gen_ai spans.
:returns: The conversation ID, or None if not set.
"""
return self._gen_ai_conversation_id
def remove_conversation_id(self) -> None:
"""Removes the conversation ID."""
self._gen_ai_conversation_id = None
def clear_breadcrumbs(self) -> None:
"""Clears breadcrumb buffer."""
self._breadcrumbs: "Deque[Breadcrumb]" = deque()
self._n_breadcrumbs_truncated = 0
def add_attachment(
self,
bytes: "Union[None, bytes, Callable[[], bytes]]" = None,
filename: "Optional[str]" = None,