scope.py 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132
  1. import os
  2. import sys
  3. import warnings
  4. from copy import copy, deepcopy
  5. from collections import deque
  6. from contextlib import contextmanager
  7. from enum import Enum
  8. from datetime import datetime, timezone
  9. from functools import wraps
  10. from itertools import chain
  11. import sentry_sdk
  12. from sentry_sdk._types import AnnotatedValue
  13. from sentry_sdk.attachments import Attachment
  14. from sentry_sdk.consts import (
  15. DEFAULT_MAX_BREADCRUMBS,
  16. FALSE_VALUES,
  17. INSTRUMENTER,
  18. SPANDATA,
  19. )
  20. from sentry_sdk.feature_flags import FlagBuffer, DEFAULT_FLAG_CAPACITY
  21. from sentry_sdk.profiler.continuous_profiler import (
  22. get_profiler_id,
  23. try_autostart_continuous_profiler,
  24. try_profile_lifecycle_trace_start,
  25. )
  26. from sentry_sdk.profiler.transaction_profiler import Profile
  27. from sentry_sdk.session import Session
  28. from sentry_sdk.tracing_utils import (
  29. Baggage,
  30. has_tracing_enabled,
  31. has_span_streaming_enabled,
  32. is_ignored_span,
  33. _make_sampling_decision,
  34. PropagationContext,
  35. )
  36. from sentry_sdk.traces import _DEFAULT_PARENT_SPAN, StreamedSpan, NoOpStreamedSpan
  37. from sentry_sdk.tracing import (
  38. BAGGAGE_HEADER_NAME,
  39. SENTRY_TRACE_HEADER_NAME,
  40. NoOpSpan,
  41. Span,
  42. Transaction,
  43. )
  44. from sentry_sdk.utils import (
  45. capture_internal_exception,
  46. capture_internal_exceptions,
  47. ContextVar,
  48. datetime_from_isoformat,
  49. disable_capture_event,
  50. event_from_exception,
  51. exc_info_from_error,
  52. format_attribute,
  53. logger,
  54. has_logs_enabled,
  55. has_metrics_enabled,
  56. )
  57. from typing import TYPE_CHECKING, cast
  58. if TYPE_CHECKING:
  59. from collections.abc import Mapping
  60. from typing import Any
  61. from typing import Callable
  62. from typing import Deque
  63. from typing import Dict
  64. from typing import Generator
  65. from typing import Iterator
  66. from typing import List
  67. from typing import Optional
  68. from typing import ParamSpec
  69. from typing import Tuple
  70. from typing import TypeVar
  71. from typing import Union
  72. from typing_extensions import Unpack
  73. from sentry_sdk._types import (
  74. Attributes,
  75. AttributeValue,
  76. Breadcrumb,
  77. BreadcrumbHint,
  78. ErrorProcessor,
  79. Event,
  80. EventProcessor,
  81. ExcInfo,
  82. Hint,
  83. Log,
  84. LogLevelStr,
  85. Metric,
  86. SamplingContext,
  87. Type,
  88. )
  89. from sentry_sdk.tracing import TransactionKwargs
  90. import sentry_sdk
  91. P = ParamSpec("P")
  92. R = TypeVar("R")
  93. F = TypeVar("F", bound=Callable[..., Any])
  94. T = TypeVar("T")
  95. # Holds data that will be added to **all** events sent by this process.
  96. # In case this is a http server (think web framework) with multiple users
  97. # the data will be added to events of all users.
  98. # Typically this is used for process wide data such as the release.
  99. _global_scope: "Optional[Scope]" = None
  100. # Holds data for the active request.
  101. # This is used to isolate data for different requests or users.
  102. # The isolation scope is usually created by integrations, but may also
  103. # be created manually
  104. _isolation_scope = ContextVar("isolation_scope", default=None)
  105. # Holds data for the active span.
  106. # This can be used to manually add additional data to a span.
  107. _current_scope = ContextVar("current_scope", default=None)
  108. global_event_processors: "List[EventProcessor]" = []
  109. # A function returning a (trace_id, span_id) tuple
  110. # from an external tracing source (such as otel)
  111. _external_propagation_context_fn: "Optional[Callable[[], Optional[Tuple[str, str]]]]" = None
  112. class ScopeType(Enum):
  113. CURRENT = "current"
  114. ISOLATION = "isolation"
  115. GLOBAL = "global"
  116. MERGED = "merged"
  117. class _ScopeManager:
  118. def __init__(self, hub: "Optional[Any]" = None) -> None:
  119. self._old_scopes: "List[Scope]" = []
  120. def __enter__(self) -> "Scope":
  121. isolation_scope = Scope.get_isolation_scope()
  122. self._old_scopes.append(isolation_scope)
  123. forked_scope = isolation_scope.fork()
  124. _isolation_scope.set(forked_scope)
  125. return forked_scope
  126. def __exit__(self, exc_type: "Any", exc_value: "Any", tb: "Any") -> None:
  127. old_scope = self._old_scopes.pop()
  128. _isolation_scope.set(old_scope)
  129. def add_global_event_processor(processor: "EventProcessor") -> None:
  130. global_event_processors.append(processor)
  131. def register_external_propagation_context(
  132. fn: "Callable[[], Optional[Tuple[str, str]]]",
  133. ) -> None:
  134. global _external_propagation_context_fn
  135. _external_propagation_context_fn = fn
  136. def remove_external_propagation_context() -> None:
  137. global _external_propagation_context_fn
  138. _external_propagation_context_fn = None
  139. def get_external_propagation_context() -> "Optional[Tuple[str, str]]":
  140. return (
  141. _external_propagation_context_fn() if _external_propagation_context_fn else None
  142. )
  143. def has_external_propagation_context() -> bool:
  144. return _external_propagation_context_fn is not None
  145. def _attr_setter(fn: "Any") -> "Any":
  146. return property(fset=fn, doc=fn.__doc__)
  147. def _disable_capture(fn: "F") -> "F":
  148. @wraps(fn)
  149. def wrapper(self: "Any", *args: "Dict[str, Any]", **kwargs: "Any") -> "Any":
  150. if not self._should_capture:
  151. return
  152. try:
  153. self._should_capture = False
  154. return fn(self, *args, **kwargs)
  155. finally:
  156. self._should_capture = True
  157. return wrapper # type: ignore
  158. class Scope:
  159. """The scope holds extra information that should be sent with all
  160. events that belong to it.
  161. """
  162. # NOTE: Even though it should not happen, the scope needs to not crash when
  163. # accessed by multiple threads. It's fine if it's full of races, but those
  164. # races should never make the user application crash.
  165. #
  166. # The same needs to hold for any accesses of the scope the SDK makes.
  167. __slots__ = (
  168. "_level",
  169. "_name",
  170. "_fingerprint",
  171. # note that for legacy reasons, _transaction is the transaction *name*,
  172. # not a Transaction object (the object is stored in _span)
  173. "_transaction",
  174. "_transaction_info",
  175. "_user",
  176. "_tags",
  177. "_contexts",
  178. "_extras",
  179. "_breadcrumbs",
  180. "_n_breadcrumbs_truncated",
  181. "_gen_ai_original_message_count",
  182. "_gen_ai_conversation_id",
  183. "_event_processors",
  184. "_error_processors",
  185. "_should_capture",
  186. "_span",
  187. "_session",
  188. "_attachments",
  189. "_force_auto_session_tracking",
  190. "_profile",
  191. "_propagation_context",
  192. "client",
  193. "_type",
  194. "_last_event_id",
  195. "_flags",
  196. "_attributes",
  197. )
  198. def __init__(
  199. self,
  200. ty: "Optional[ScopeType]" = None,
  201. client: "Optional[sentry_sdk.Client]" = None,
  202. ) -> None:
  203. self._type = ty
  204. self._event_processors: "List[EventProcessor]" = []
  205. self._error_processors: "List[ErrorProcessor]" = []
  206. self._name: "Optional[str]" = None
  207. self._propagation_context: "Optional[PropagationContext]" = None
  208. self._n_breadcrumbs_truncated: int = 0
  209. self._gen_ai_original_message_count: "Dict[str, int]" = {}
  210. self.client: "sentry_sdk.client.BaseClient" = NonRecordingClient()
  211. if client is not None:
  212. self.set_client(client)
  213. self.clear()
  214. incoming_trace_information = self._load_trace_data_from_env()
  215. self.generate_propagation_context(incoming_data=incoming_trace_information)
  216. def __copy__(self) -> "Scope":
  217. """
  218. Returns a copy of this scope.
  219. This also creates a copy of all referenced data structures.
  220. """
  221. rv: "Scope" = object.__new__(self.__class__)
  222. rv._type = self._type
  223. rv.client = self.client
  224. rv._level = self._level
  225. rv._name = self._name
  226. rv._fingerprint = self._fingerprint
  227. rv._transaction = self._transaction
  228. rv._transaction_info = self._transaction_info.copy()
  229. rv._user = self._user
  230. rv._tags = self._tags.copy()
  231. rv._contexts = self._contexts.copy()
  232. rv._extras = self._extras.copy()
  233. rv._breadcrumbs = copy(self._breadcrumbs)
  234. rv._n_breadcrumbs_truncated = self._n_breadcrumbs_truncated
  235. rv._gen_ai_original_message_count = self._gen_ai_original_message_count.copy()
  236. rv._event_processors = self._event_processors.copy()
  237. rv._error_processors = self._error_processors.copy()
  238. rv._propagation_context = self._propagation_context
  239. rv._should_capture = self._should_capture
  240. rv._span = self._span
  241. rv._session = self._session
  242. rv._force_auto_session_tracking = self._force_auto_session_tracking
  243. rv._attachments = self._attachments.copy()
  244. rv._profile = self._profile
  245. rv._last_event_id = self._last_event_id
  246. rv._flags = deepcopy(self._flags)
  247. rv._attributes = self._attributes.copy()
  248. rv._gen_ai_conversation_id = self._gen_ai_conversation_id
  249. return rv
  250. @classmethod
  251. def get_current_scope(cls) -> "Scope":
  252. """
  253. .. versionadded:: 2.0.0
  254. Returns the current scope.
  255. """
  256. current_scope = _current_scope.get()
  257. if current_scope is None:
  258. current_scope = Scope(ty=ScopeType.CURRENT)
  259. _current_scope.set(current_scope)
  260. return current_scope
  261. @classmethod
  262. def set_current_scope(cls, new_current_scope: "Scope") -> None:
  263. """
  264. .. versionadded:: 2.0.0
  265. Sets the given scope as the new current scope overwriting the existing current scope.
  266. :param new_current_scope: The scope to set as the new current scope.
  267. """
  268. _current_scope.set(new_current_scope)
  269. @classmethod
  270. def get_isolation_scope(cls) -> "Scope":
  271. """
  272. .. versionadded:: 2.0.0
  273. Returns the isolation scope.
  274. """
  275. isolation_scope = _isolation_scope.get()
  276. if isolation_scope is None:
  277. isolation_scope = Scope(ty=ScopeType.ISOLATION)
  278. _isolation_scope.set(isolation_scope)
  279. return isolation_scope
  280. @classmethod
  281. def set_isolation_scope(cls, new_isolation_scope: "Scope") -> None:
  282. """
  283. .. versionadded:: 2.0.0
  284. Sets the given scope as the new isolation scope overwriting the existing isolation scope.
  285. :param new_isolation_scope: The scope to set as the new isolation scope.
  286. """
  287. _isolation_scope.set(new_isolation_scope)
  288. @classmethod
  289. def get_global_scope(cls) -> "Scope":
  290. """
  291. .. versionadded:: 2.0.0
  292. Returns the global scope.
  293. """
  294. global _global_scope
  295. if _global_scope is None:
  296. _global_scope = Scope(ty=ScopeType.GLOBAL)
  297. return _global_scope
  298. def set_global_attributes(self) -> None:
  299. from sentry_sdk.client import SDK_INFO
  300. self.set_attribute("sentry.sdk.name", SDK_INFO["name"])
  301. self.set_attribute("sentry.sdk.version", SDK_INFO["version"])
  302. options = sentry_sdk.get_client().options
  303. server_name = options.get("server_name")
  304. if server_name:
  305. self.set_attribute(SPANDATA.SERVER_ADDRESS, server_name)
  306. environment = options.get("environment")
  307. if environment:
  308. self.set_attribute("sentry.environment", environment)
  309. release = options.get("release")
  310. if release:
  311. self.set_attribute("sentry.release", release)
  312. @classmethod
  313. def last_event_id(cls) -> "Optional[str]":
  314. """
  315. .. versionadded:: 2.2.0
  316. Returns event ID of the event most recently captured by the isolation scope, or None if no event
  317. has been captured. We do not consider events that are dropped, e.g. by a before_send hook.
  318. Transactions also are not considered events in this context.
  319. The event corresponding to the returned event ID is NOT guaranteed to actually be sent to Sentry;
  320. whether the event is sent depends on the transport. The event could be sent later or not at all.
  321. Even a sent event could fail to arrive in Sentry due to network issues, exhausted quotas, or
  322. various other reasons.
  323. """
  324. return cls.get_isolation_scope()._last_event_id
  325. def _merge_scopes(
  326. self,
  327. additional_scope: "Optional[Scope]" = None,
  328. additional_scope_kwargs: "Optional[Dict[str, Any]]" = None,
  329. ) -> "Scope":
  330. """
  331. Merges global, isolation and current scope into a new scope and
  332. adds the given additional scope or additional scope kwargs to it.
  333. """
  334. if additional_scope and additional_scope_kwargs:
  335. raise TypeError("cannot provide scope and kwargs")
  336. final_scope = copy(_global_scope) if _global_scope is not None else Scope()
  337. final_scope._type = ScopeType.MERGED
  338. isolation_scope = _isolation_scope.get()
  339. if isolation_scope is not None:
  340. final_scope.update_from_scope(isolation_scope)
  341. current_scope = _current_scope.get()
  342. if current_scope is not None:
  343. final_scope.update_from_scope(current_scope)
  344. if self != current_scope and self != isolation_scope:
  345. final_scope.update_from_scope(self)
  346. if additional_scope is not None:
  347. if callable(additional_scope):
  348. additional_scope(final_scope)
  349. else:
  350. final_scope.update_from_scope(additional_scope)
  351. elif additional_scope_kwargs:
  352. final_scope.update_from_kwargs(**additional_scope_kwargs)
  353. return final_scope
  354. @classmethod
  355. def get_client(cls) -> "sentry_sdk.client.BaseClient":
  356. """
  357. .. versionadded:: 2.0.0
  358. Returns the currently used :py:class:`sentry_sdk.Client`.
  359. This checks the current scope, the isolation scope and the global scope for a client.
  360. If no client is available a :py:class:`sentry_sdk.client.NonRecordingClient` is returned.
  361. """
  362. current_scope = _current_scope.get()
  363. try:
  364. client = current_scope.client
  365. except AttributeError:
  366. client = None
  367. if client is not None and client.is_active():
  368. return client
  369. isolation_scope = _isolation_scope.get()
  370. try:
  371. client = isolation_scope.client
  372. except AttributeError:
  373. client = None
  374. if client is not None and client.is_active():
  375. return client
  376. try:
  377. client = _global_scope.client # type: ignore
  378. except AttributeError:
  379. client = None
  380. if client is not None and client.is_active():
  381. return client
  382. return NonRecordingClient()
  383. def set_client(
  384. self, client: "Optional[sentry_sdk.client.BaseClient]" = None
  385. ) -> None:
  386. """
  387. .. versionadded:: 2.0.0
  388. Sets the client for this scope.
  389. :param client: The client to use in this scope.
  390. If `None` the client of the scope will be replaced by a :py:class:`sentry_sdk.NonRecordingClient`.
  391. """
  392. if client is not None:
  393. self.client = client
  394. # We need a client to set the initial global attributes on the global
  395. # scope since they mostly come from client options, so populate them
  396. # as soon as a client is set
  397. sentry_sdk.get_global_scope().set_global_attributes()
  398. else:
  399. self.client = NonRecordingClient()
  400. def fork(self) -> "Scope":
  401. """
  402. .. versionadded:: 2.0.0
  403. Returns a fork of this scope.
  404. """
  405. forked_scope = copy(self)
  406. return forked_scope
  407. def _load_trace_data_from_env(self) -> "Optional[Dict[str, str]]":
  408. """
  409. Load Sentry trace id and baggage from environment variables.
  410. Can be disabled by setting SENTRY_USE_ENVIRONMENT to "false".
  411. """
  412. incoming_trace_information = None
  413. sentry_use_environment = (
  414. os.environ.get("SENTRY_USE_ENVIRONMENT") or ""
  415. ).lower()
  416. use_environment = sentry_use_environment not in FALSE_VALUES
  417. if use_environment:
  418. incoming_trace_information = {}
  419. if os.environ.get("SENTRY_TRACE"):
  420. incoming_trace_information[SENTRY_TRACE_HEADER_NAME] = (
  421. os.environ.get("SENTRY_TRACE") or ""
  422. )
  423. if os.environ.get("SENTRY_BAGGAGE"):
  424. incoming_trace_information[BAGGAGE_HEADER_NAME] = (
  425. os.environ.get("SENTRY_BAGGAGE") or ""
  426. )
  427. return incoming_trace_information or None
  428. def set_new_propagation_context(self) -> None:
  429. """
  430. Creates a new propagation context and sets it as `_propagation_context`. Overwriting existing one.
  431. """
  432. self._propagation_context = PropagationContext()
  433. def generate_propagation_context(
  434. self, incoming_data: "Optional[Dict[str, str]]" = None
  435. ) -> None:
  436. """
  437. Makes sure the propagation context is set on the scope.
  438. If there is `incoming_data` overwrite existing propagation context.
  439. If there is no `incoming_data` create new propagation context, but do NOT overwrite if already existing.
  440. """
  441. if incoming_data is not None:
  442. self._propagation_context = PropagationContext.from_incoming_data(
  443. incoming_data
  444. )
  445. # TODO-neel this below is a BIG code smell but requires a bunch of other refactoring
  446. if self._type != ScopeType.CURRENT:
  447. if self._propagation_context is None:
  448. self.set_new_propagation_context()
  449. def get_dynamic_sampling_context(self) -> "Optional[Dict[str, str]]":
  450. """
  451. Returns the Dynamic Sampling Context from the Propagation Context.
  452. If not existing, creates a new one.
  453. Deprecated: Logic moved to PropagationContext, don't use directly.
  454. """
  455. if self._propagation_context is None:
  456. return None
  457. return self._propagation_context.dynamic_sampling_context
  458. def get_traceparent(self, *args: "Any", **kwargs: "Any") -> "Optional[str]":
  459. """
  460. Returns the Sentry "sentry-trace" header (aka the traceparent) from the
  461. currently active span or the scopes Propagation Context.
  462. """
  463. client = self.get_client()
  464. # If we have an active span, return traceparent from there
  465. if (
  466. has_tracing_enabled(client.options)
  467. and self.span is not None
  468. and not isinstance(self.span, NoOpStreamedSpan)
  469. ):
  470. return self.span._to_traceparent()
  471. # else return traceparent from the propagation context
  472. return self.get_active_propagation_context().to_traceparent()
  473. def get_baggage(self, *args: "Any", **kwargs: "Any") -> "Optional[Baggage]":
  474. """
  475. Returns the Sentry "baggage" header containing trace information from the
  476. currently active span or the scopes Propagation Context.
  477. """
  478. client = self.get_client()
  479. # If we have an active span, return baggage from there
  480. if (
  481. has_tracing_enabled(client.options)
  482. and self.span is not None
  483. and not isinstance(self.span, NoOpStreamedSpan)
  484. ):
  485. return self.span._to_baggage()
  486. # else return baggage from the propagation context
  487. return self.get_active_propagation_context().get_baggage()
  488. def get_trace_context(self) -> "Dict[str, Any]":
  489. """
  490. Returns the Sentry "trace" context from the Propagation Context.
  491. """
  492. if (
  493. has_tracing_enabled(self.get_client().options)
  494. and self._span is not None
  495. and not isinstance(self._span, NoOpStreamedSpan)
  496. ):
  497. return self._span._get_trace_context()
  498. # if we are tracing externally (otel), those values take precedence
  499. external_propagation_context = get_external_propagation_context()
  500. if external_propagation_context:
  501. trace_id, span_id = external_propagation_context
  502. return {"trace_id": trace_id, "span_id": span_id}
  503. propagation_context = self.get_active_propagation_context()
  504. return {
  505. "trace_id": propagation_context.trace_id,
  506. "span_id": propagation_context.span_id,
  507. "parent_span_id": propagation_context.parent_span_id,
  508. "dynamic_sampling_context": propagation_context.dynamic_sampling_context,
  509. }
  510. def trace_propagation_meta(self, *args: "Any", **kwargs: "Any") -> str:
  511. """
  512. Return meta tags which should be injected into HTML templates
  513. to allow propagation of trace information.
  514. """
  515. span = kwargs.pop("span", None)
  516. if span is not None:
  517. logger.warning(
  518. "The parameter `span` in trace_propagation_meta() is deprecated and will be removed in the future."
  519. )
  520. meta = ""
  521. for name, content in self.iter_trace_propagation_headers():
  522. meta += f'<meta name="{name}" content="{content}">'
  523. return meta
  524. def iter_headers(self) -> "Iterator[Tuple[str, str]]":
  525. """
  526. Creates a generator which returns the `sentry-trace` and `baggage` headers from the Propagation Context.
  527. Deprecated: use PropagationContext.iter_headers instead.
  528. """
  529. if self._propagation_context is not None:
  530. yield from self._propagation_context.iter_headers()
  531. def iter_trace_propagation_headers(
  532. self, *args: "Any", **kwargs: "Any"
  533. ) -> "Generator[Tuple[str, str], None, None]":
  534. """
  535. Return HTTP headers which allow propagation of trace data.
  536. If a span is given, the trace data will taken from the span.
  537. If no span is given, the trace data is taken from the scope.
  538. """
  539. client = self.get_client()
  540. if not client.options.get("propagate_traces"):
  541. warnings.warn(
  542. "The `propagate_traces` parameter is deprecated. Please use `trace_propagation_targets` instead.",
  543. DeprecationWarning,
  544. stacklevel=2,
  545. )
  546. return
  547. span = kwargs.pop("span", None)
  548. span = span or self.span
  549. if (
  550. has_tracing_enabled(client.options)
  551. and span is not None
  552. and not isinstance(span, NoOpStreamedSpan)
  553. ):
  554. for header in span._iter_headers():
  555. yield header
  556. elif has_external_propagation_context():
  557. # when we have an external_propagation_context (otlp)
  558. # we leave outgoing propagation to the propagator
  559. return
  560. else:
  561. for header in self.get_active_propagation_context().iter_headers():
  562. yield header
  563. def get_active_propagation_context(self) -> "PropagationContext":
  564. if self._propagation_context is not None:
  565. return self._propagation_context
  566. current_scope = self.get_current_scope()
  567. if current_scope._propagation_context is not None:
  568. return current_scope._propagation_context
  569. isolation_scope = self.get_isolation_scope()
  570. # should actually never happen, but just in case someone calls scope.clear
  571. if isolation_scope._propagation_context is None:
  572. isolation_scope._propagation_context = PropagationContext()
  573. return isolation_scope._propagation_context
  574. def set_custom_sampling_context(
  575. self, custom_sampling_context: "dict[str, Any]"
  576. ) -> None:
  577. self.get_active_propagation_context()._set_custom_sampling_context(
  578. custom_sampling_context
  579. )
  580. def clear(self) -> None:
  581. """Clears the entire scope."""
  582. self._level: "Optional[LogLevelStr]" = None
  583. self._fingerprint: "Optional[List[str]]" = None
  584. self._transaction: "Optional[str]" = None
  585. self._transaction_info: "dict[str, str]" = {}
  586. self._user: "Optional[Dict[str, Any]]" = None
  587. self._tags: "Dict[str, Any]" = {}
  588. self._contexts: "Dict[str, Dict[str, Any]]" = {}
  589. self._extras: "dict[str, Any]" = {}
  590. self._attachments: "List[Attachment]" = []
  591. self.clear_breadcrumbs()
  592. self._should_capture: bool = True
  593. self._span: "Optional[Union[Span, StreamedSpan]]" = None
  594. self._session: "Optional[Session]" = None
  595. self._force_auto_session_tracking: "Optional[bool]" = None
  596. self._profile: "Optional[Profile]" = None
  597. self._propagation_context = None
  598. # self._last_event_id is only applicable to isolation scopes
  599. self._last_event_id: "Optional[str]" = None
  600. self._flags: "Optional[FlagBuffer]" = None
  601. self._attributes: "Attributes" = {}
  602. self._gen_ai_conversation_id: "Optional[str]" = None
  603. @_attr_setter
  604. def level(self, value: "LogLevelStr") -> None:
  605. """
  606. When set this overrides the level.
  607. .. deprecated:: 1.0.0
  608. Use :func:`set_level` instead.
  609. :param value: The level to set.
  610. """
  611. logger.warning(
  612. "Deprecated: use .set_level() instead. This will be removed in the future."
  613. )
  614. self._level = value
  615. def set_level(self, value: "LogLevelStr") -> None:
  616. """
  617. Sets the level for the scope.
  618. :param value: The level to set.
  619. """
  620. self._level = value
  621. @_attr_setter
  622. def fingerprint(self, value: "Optional[List[str]]") -> None:
  623. """When set this overrides the default fingerprint."""
  624. self._fingerprint = value
  625. @property
  626. def transaction(self) -> "Any":
  627. # would be type: () -> Optional[Transaction], see https://github.com/python/mypy/issues/3004
  628. """Return the transaction (root span) in the scope, if any."""
  629. # there is no span/transaction on the scope
  630. if self._span is None:
  631. return None
  632. if isinstance(self._span, StreamedSpan):
  633. warnings.warn(
  634. "Scope.transaction is not available in streaming mode.",
  635. DeprecationWarning,
  636. stacklevel=2,
  637. )
  638. return None
  639. # there is an orphan span on the scope
  640. if self._span.containing_transaction is None:
  641. return None
  642. # there is either a transaction (which is its own containing
  643. # transaction) or a non-orphan span on the scope
  644. return self._span.containing_transaction
  645. @transaction.setter
  646. def transaction(self, value: "Any") -> None:
  647. # would be type: (Optional[str]) -> None, see https://github.com/python/mypy/issues/3004
  648. """When set this forces a specific transaction name to be set.
  649. Deprecated: use set_transaction_name instead."""
  650. # XXX: the docstring above is misleading. The implementation of
  651. # apply_to_event prefers an existing value of event.transaction over
  652. # anything set in the scope.
  653. # XXX: note that with the introduction of the Scope.transaction getter,
  654. # there is a semantic and type mismatch between getter and setter. The
  655. # getter returns a Transaction, the setter sets a transaction name.
  656. # Without breaking version compatibility, we could make the setter set a
  657. # transaction name or transaction (self._span) depending on the type of
  658. # the value argument.
  659. logger.warning(
  660. "Assigning to scope.transaction directly is deprecated: use scope.set_transaction_name() instead."
  661. )
  662. self._transaction = value
  663. if self._span:
  664. if isinstance(self._span, StreamedSpan):
  665. warnings.warn(
  666. "Scope.transaction is not available in streaming mode.",
  667. DeprecationWarning,
  668. stacklevel=2,
  669. )
  670. return None
  671. if self._span.containing_transaction:
  672. self._span.containing_transaction.name = value
  673. def set_transaction_name(self, name: str, source: "Optional[str]" = None) -> None:
  674. """Set the transaction name and optionally the transaction source."""
  675. self._transaction = name
  676. if self._span:
  677. if isinstance(self._span, NoOpStreamedSpan):
  678. return
  679. elif isinstance(self._span, StreamedSpan):
  680. self._span._segment.name = name
  681. if source:
  682. self._span._segment.set_attribute(
  683. "sentry.span.source", getattr(source, "value", source)
  684. )
  685. elif self._span.containing_transaction:
  686. self._span.containing_transaction.name = name
  687. if source:
  688. self._span.containing_transaction.source = source
  689. if source:
  690. self._transaction_info["source"] = source
  691. @_attr_setter
  692. def user(self, value: "Optional[Dict[str, Any]]") -> None:
  693. """When set a specific user is bound to the scope. Deprecated in favor of set_user."""
  694. warnings.warn(
  695. "The `Scope.user` setter is deprecated in favor of `Scope.set_user()`.",
  696. DeprecationWarning,
  697. stacklevel=2,
  698. )
  699. self.set_user(value)
  700. def set_user(self, value: "Optional[Dict[str, Any]]") -> None:
  701. """Sets a user for the scope."""
  702. self._user = value
  703. session = self.get_isolation_scope()._session
  704. if session is not None:
  705. session.update(user=value)
  706. @property
  707. def span(self) -> "Optional[Union[Span, StreamedSpan]]":
  708. """Get/set current tracing span or transaction."""
  709. return self._span
  710. @span.setter
  711. def span(self, span: "Optional[Union[Span, StreamedSpan]]") -> None:
  712. self._span = span
  713. # XXX: this differs from the implementation in JS, there Scope.setSpan
  714. # does not set Scope._transactionName.
  715. if isinstance(span, Transaction):
  716. transaction = span
  717. if transaction.name:
  718. self._transaction = transaction.name
  719. if transaction.source:
  720. self._transaction_info["source"] = transaction.source
  721. @property
  722. def profile(self) -> "Optional[Profile]":
  723. return self._profile
  724. @profile.setter
  725. def profile(self, profile: "Optional[Profile]") -> None:
  726. self._profile = profile
  727. def set_tag(self, key: str, value: "Any") -> None:
  728. """
  729. Sets a tag for a key to a specific value.
  730. :param key: Key of the tag to set.
  731. :param value: Value of the tag to set.
  732. """
  733. self._tags[key] = value
  734. def set_tags(self, tags: "Mapping[str, object]") -> None:
  735. """Sets multiple tags at once.
  736. This method updates multiple tags at once. The tags are passed as a dictionary
  737. or other mapping type.
  738. Calling this method is equivalent to calling `set_tag` on each key-value pair
  739. in the mapping. If a tag key already exists in the scope, its value will be
  740. updated. If the tag key does not exist in the scope, the key-value pair will
  741. be added to the scope.
  742. This method only modifies tag keys in the `tags` mapping passed to the method.
  743. `scope.set_tags({})` is, therefore, a no-op.
  744. :param tags: A mapping of tag keys to tag values to set.
  745. """
  746. self._tags.update(tags)
  747. def remove_tag(self, key: str) -> None:
  748. """
  749. Removes a specific tag.
  750. :param key: Key of the tag to remove.
  751. """
  752. self._tags.pop(key, None)
  753. def set_context(
  754. self,
  755. key: str,
  756. value: "Dict[str, Any]",
  757. ) -> None:
  758. """
  759. Binds a context at a certain key to a specific value.
  760. """
  761. self._contexts[key] = value
  762. def remove_context(
  763. self,
  764. key: str,
  765. ) -> None:
  766. """Removes a context."""
  767. self._contexts.pop(key, None)
  768. def set_extra(
  769. self,
  770. key: str,
  771. value: "Any",
  772. ) -> None:
  773. """Sets an extra key to a specific value."""
  774. self._extras[key] = value
  775. def remove_extra(
  776. self,
  777. key: str,
  778. ) -> None:
  779. """Removes a specific extra key."""
  780. self._extras.pop(key, None)
  781. def set_conversation_id(self, conversation_id: str) -> None:
  782. """
  783. Sets the conversation ID for gen_ai spans.
  784. :param conversation_id: The conversation ID to set.
  785. """
  786. self._gen_ai_conversation_id = conversation_id
  787. def get_conversation_id(self) -> "Optional[str]":
  788. """
  789. Gets the conversation ID for gen_ai spans.
  790. :returns: The conversation ID, or None if not set.
  791. """
  792. return self._gen_ai_conversation_id
  793. def remove_conversation_id(self) -> None:
  794. """Removes the conversation ID."""
  795. self._gen_ai_conversation_id = None
  796. def clear_breadcrumbs(self) -> None:
  797. """Clears breadcrumb buffer."""
  798. self._breadcrumbs: "Deque[Breadcrumb]" = deque()
  799. self._n_breadcrumbs_truncated = 0
  800. def add_attachment(
  801. self,
  802. bytes: "Union[None, bytes, Callable[[], bytes]]" = None,
  803. filename: "Optional[str]" = None,
  804. path: "Optional[str]" = None,
  805. content_type: "Optional[str]" = None,
  806. add_to_transactions: bool = False,
  807. ) -> None:
  808. """Adds an attachment to future events sent from this scope.
  809. The parameters are the same as for the :py:class:`sentry_sdk.attachments.Attachment` constructor.
  810. """
  811. self._attachments.append(
  812. Attachment(
  813. bytes=bytes,
  814. path=path,
  815. filename=filename,
  816. content_type=content_type,
  817. add_to_transactions=add_to_transactions,
  818. )
  819. )
  820. def add_breadcrumb(
  821. self,
  822. crumb: "Optional[Breadcrumb]" = None,
  823. hint: "Optional[BreadcrumbHint]" = None,
  824. **kwargs: "Any",
  825. ) -> None:
  826. """
  827. Adds a breadcrumb.
  828. :param crumb: Dictionary with the data as the sentry v7/v8 protocol expects.
  829. :param hint: An optional value that can be used by `before_breadcrumb`
  830. to customize the breadcrumbs that are emitted.
  831. """
  832. client = self.get_client()
  833. if not client.is_active():
  834. logger.info("Dropped breadcrumb because no client bound")
  835. return
  836. before_breadcrumb = client.options.get("before_breadcrumb")
  837. max_breadcrumbs = client.options.get("max_breadcrumbs", DEFAULT_MAX_BREADCRUMBS)
  838. crumb: "Breadcrumb" = dict(crumb or ())
  839. crumb.update(kwargs)
  840. if not crumb:
  841. return
  842. hint: "Hint" = dict(hint or ())
  843. if crumb.get("timestamp") is None:
  844. crumb["timestamp"] = datetime.now(timezone.utc)
  845. if crumb.get("type") is None:
  846. crumb["type"] = "default"
  847. if before_breadcrumb is not None:
  848. new_crumb = before_breadcrumb(crumb, hint)
  849. else:
  850. new_crumb = crumb
  851. if new_crumb is not None:
  852. self._breadcrumbs.append(new_crumb)
  853. else:
  854. logger.info("before breadcrumb dropped breadcrumb (%s)", crumb)
  855. while len(self._breadcrumbs) > max_breadcrumbs:
  856. self._breadcrumbs.popleft()
  857. self._n_breadcrumbs_truncated += 1
  858. def start_transaction(
  859. self,
  860. transaction: "Optional[Transaction]" = None,
  861. instrumenter: str = INSTRUMENTER.SENTRY,
  862. custom_sampling_context: "Optional[SamplingContext]" = None,
  863. **kwargs: "Unpack[TransactionKwargs]",
  864. ) -> "Union[Transaction, NoOpSpan]":
  865. """
  866. Start and return a transaction.
  867. Start an existing transaction if given, otherwise create and start a new
  868. transaction with kwargs.
  869. This is the entry point to manual tracing instrumentation.
  870. A tree structure can be built by adding child spans to the transaction,
  871. and child spans to other spans. To start a new child span within the
  872. transaction or any span, call the respective `.start_child()` method.
  873. Every child span must be finished before the transaction is finished,
  874. otherwise the unfinished spans are discarded.
  875. When used as context managers, spans and transactions are automatically
  876. finished at the end of the `with` block. If not using context managers,
  877. call the `.finish()` method.
  878. When the transaction is finished, it will be sent to Sentry with all its
  879. finished child spans.
  880. :param transaction: The transaction to start. If omitted, we create and
  881. start a new transaction.
  882. :param instrumenter: This parameter is meant for internal use only. It
  883. will be removed in the next major version.
  884. :param custom_sampling_context: The transaction's custom sampling context.
  885. :param kwargs: Optional keyword arguments to be passed to the Transaction
  886. constructor. See :py:class:`sentry_sdk.tracing.Transaction` for
  887. available arguments.
  888. """
  889. kwargs.setdefault("scope", self)
  890. client = self.get_client()
  891. configuration_instrumenter = client.options["instrumenter"]
  892. if instrumenter != configuration_instrumenter:
  893. return NoOpSpan()
  894. try_autostart_continuous_profiler()
  895. custom_sampling_context = custom_sampling_context or {}
  896. # kwargs at this point has type TransactionKwargs, since we have removed
  897. # the client and custom_sampling_context from it.
  898. transaction_kwargs: "TransactionKwargs" = kwargs
  899. # if we haven't been given a transaction, make one
  900. if transaction is None:
  901. transaction = Transaction(**transaction_kwargs)
  902. # use traces_sample_rate, traces_sampler, and/or inheritance to make a
  903. # sampling decision
  904. sampling_context = {
  905. "transaction_context": transaction.to_json(),
  906. "parent_sampled": transaction.parent_sampled,
  907. }
  908. sampling_context.update(custom_sampling_context)
  909. transaction._set_initial_sampling_decision(sampling_context=sampling_context)
  910. # update the sample rate in the dsc
  911. if transaction.sample_rate is not None:
  912. propagation_context = self.get_active_propagation_context()
  913. baggage = propagation_context.baggage
  914. if baggage is not None:
  915. baggage.sentry_items["sample_rate"] = str(transaction.sample_rate)
  916. if transaction._baggage:
  917. transaction._baggage.sentry_items["sample_rate"] = str(
  918. transaction.sample_rate
  919. )
  920. if transaction.sampled:
  921. profile = Profile(
  922. transaction.sampled, transaction._start_timestamp_monotonic_ns
  923. )
  924. profile._set_initial_sampling_decision(sampling_context=sampling_context)
  925. transaction._profile = profile
  926. transaction._continuous_profile = try_profile_lifecycle_trace_start()
  927. # Typically, the profiler is set when the transaction is created. But when
  928. # using the auto lifecycle, the profiler isn't running when the first
  929. # transaction is started. So make sure we update the profiler id on it.
  930. if transaction._continuous_profile is not None:
  931. transaction.set_profiler_id(get_profiler_id())
  932. # we don't bother to keep spans if we already know we're not going to
  933. # send the transaction
  934. max_spans = (client.options["_experiments"].get("max_spans")) or 1000
  935. transaction.init_span_recorder(maxlen=max_spans)
  936. return transaction
  937. def start_span(
  938. self, instrumenter: str = INSTRUMENTER.SENTRY, **kwargs: "Any"
  939. ) -> "Span":
  940. """
  941. Start a span whose parent is the currently active span or transaction, if any.
  942. The return value is a :py:class:`sentry_sdk.tracing.Span` instance,
  943. typically used as a context manager to start and stop timing in a `with`
  944. block.
  945. Only spans contained in a transaction are sent to Sentry. Most
  946. integrations start a transaction at the appropriate time, for example
  947. for every incoming HTTP request. Use
  948. :py:meth:`sentry_sdk.start_transaction` to start a new transaction when
  949. one is not already in progress.
  950. For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
  951. The instrumenter parameter is deprecated for user code, and it will
  952. be removed in the next major version. Going forward, it should only
  953. be used by the SDK itself.
  954. """
  955. client = sentry_sdk.get_client()
  956. if has_span_streaming_enabled(client.options):
  957. warnings.warn(
  958. "Scope.start_span is not available in streaming mode.",
  959. DeprecationWarning,
  960. stacklevel=2,
  961. )
  962. return NoOpSpan()
  963. if kwargs.get("description") is not None:
  964. warnings.warn(
  965. "The `description` parameter is deprecated. Please use `name` instead.",
  966. DeprecationWarning,
  967. stacklevel=2,
  968. )
  969. with new_scope():
  970. kwargs.setdefault("scope", self)
  971. client = self.get_client()
  972. configuration_instrumenter = client.options["instrumenter"]
  973. if instrumenter != configuration_instrumenter:
  974. return NoOpSpan()
  975. # get current span or transaction
  976. span = self.span or self.get_isolation_scope().span
  977. if isinstance(span, StreamedSpan):
  978. # make mypy happy
  979. return NoOpSpan()
  980. if span is None:
  981. # New spans get the `trace_id` from the scope
  982. if "trace_id" not in kwargs:
  983. propagation_context = self.get_active_propagation_context()
  984. kwargs["trace_id"] = propagation_context.trace_id
  985. span = Span(**kwargs)
  986. else:
  987. # Children take `trace_id`` from the parent span.
  988. span = span.start_child(**kwargs)
  989. return span
  990. def start_streamed_span(
  991. self,
  992. name: str,
  993. attributes: "Optional[Attributes]",
  994. parent_span: "Optional[StreamedSpan]",
  995. active: bool,
  996. ) -> "StreamedSpan":
  997. # TODO: rename to start_span once we drop the old API
  998. if isinstance(parent_span, NoOpStreamedSpan):
  999. # parent_span is only set if the user explicitly set it
  1000. logger.debug(
  1001. "Ignored parent span provided. Span will be parented to the "
  1002. "currently active span instead."
  1003. )
  1004. if parent_span is _DEFAULT_PARENT_SPAN or isinstance(
  1005. parent_span, NoOpStreamedSpan
  1006. ):
  1007. parent_span = self.span # type: ignore
  1008. # If no eligible parent_span was provided and there is no currently
  1009. # active span, this is a segment
  1010. if parent_span is None:
  1011. propagation_context = self.get_active_propagation_context()
  1012. if is_ignored_span(name, attributes):
  1013. return NoOpStreamedSpan(
  1014. scope=self,
  1015. unsampled_reason="ignored",
  1016. )
  1017. sampled, sample_rate, sample_rand, outcome = _make_sampling_decision(
  1018. name,
  1019. attributes,
  1020. self,
  1021. )
  1022. if sample_rate is not None:
  1023. self._update_sample_rate(sample_rate)
  1024. if sampled is False:
  1025. return NoOpStreamedSpan(
  1026. scope=self,
  1027. unsampled_reason=outcome,
  1028. )
  1029. return StreamedSpan(
  1030. name=name,
  1031. attributes=attributes,
  1032. active=active,
  1033. scope=self,
  1034. segment=None,
  1035. trace_id=propagation_context.trace_id,
  1036. parent_span_id=propagation_context.parent_span_id,
  1037. parent_sampled=propagation_context.parent_sampled,
  1038. baggage=propagation_context.baggage,
  1039. sample_rand=sample_rand,
  1040. sample_rate=sample_rate,
  1041. )
  1042. # This is a child span; take propagation context from the parent span
  1043. with new_scope():
  1044. if is_ignored_span(name, attributes):
  1045. return NoOpStreamedSpan(
  1046. unsampled_reason="ignored",
  1047. )
  1048. if isinstance(parent_span, NoOpStreamedSpan):
  1049. return NoOpStreamedSpan(unsampled_reason=parent_span._unsampled_reason)
  1050. return StreamedSpan(
  1051. name=name,
  1052. attributes=attributes,
  1053. active=active,
  1054. scope=self,
  1055. segment=parent_span._segment,
  1056. trace_id=parent_span.trace_id,
  1057. parent_span_id=parent_span.span_id,
  1058. parent_sampled=parent_span.sampled,
  1059. )
  1060. def _update_sample_rate(self, sample_rate: float) -> None:
  1061. # If we had to adjust the sample rate when setting the sampling decision
  1062. # for a span, it needs to be updated in the propagation context too
  1063. propagation_context = self.get_active_propagation_context()
  1064. baggage = propagation_context.baggage
  1065. if baggage is not None:
  1066. baggage.sentry_items["sample_rate"] = str(sample_rate)
  1067. def continue_trace(
  1068. self,
  1069. environ_or_headers: "Dict[str, Any]",
  1070. op: "Optional[str]" = None,
  1071. name: "Optional[str]" = None,
  1072. source: "Optional[str]" = None,
  1073. origin: str = "manual",
  1074. ) -> "Transaction":
  1075. """
  1076. Sets the propagation context from environment or headers and returns a transaction.
  1077. """
  1078. self.generate_propagation_context(environ_or_headers)
  1079. # generate_propagation_context ensures that the propagation_context is not None.
  1080. propagation_context = cast(PropagationContext, self._propagation_context)
  1081. optional_kwargs = {}
  1082. if name:
  1083. optional_kwargs["name"] = name
  1084. if source:
  1085. optional_kwargs["source"] = source
  1086. return Transaction(
  1087. op=op,
  1088. origin=origin,
  1089. baggage=propagation_context.baggage,
  1090. parent_sampled=propagation_context.parent_sampled,
  1091. trace_id=propagation_context.trace_id,
  1092. parent_span_id=propagation_context.parent_span_id,
  1093. same_process_as_parent=False,
  1094. **optional_kwargs,
  1095. )
  1096. def capture_event(
  1097. self,
  1098. event: "Event",
  1099. hint: "Optional[Hint]" = None,
  1100. scope: "Optional[Scope]" = None,
  1101. **scope_kwargs: "Any",
  1102. ) -> "Optional[str]":
  1103. """
  1104. Captures an event.
  1105. Merges given scope data and calls :py:meth:`sentry_sdk.client._Client.capture_event`.
  1106. :param event: A ready-made event that can be directly sent to Sentry.
  1107. :param hint: Contains metadata about the event that can be read from `before_send`, such as the original exception object or a HTTP request object.
  1108. :param scope: An optional :py:class:`sentry_sdk.Scope` to apply to events.
  1109. The `scope` and `scope_kwargs` parameters are mutually exclusive.
  1110. :param scope_kwargs: Optional data to apply to event.
  1111. For supported `**scope_kwargs` see :py:meth:`sentry_sdk.Scope.update_from_kwargs`.
  1112. The `scope` and `scope_kwargs` parameters are mutually exclusive.
  1113. :returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.client._Client.capture_event`).
  1114. """
  1115. if disable_capture_event.get(False):
  1116. return None
  1117. scope = self._merge_scopes(scope, scope_kwargs)
  1118. event_id = self.get_client().capture_event(event=event, hint=hint, scope=scope)
  1119. if event_id is not None and event.get("type") != "transaction":
  1120. self.get_isolation_scope()._last_event_id = event_id
  1121. return event_id
  1122. def _capture_log(self, log: "Optional[Log]") -> None:
  1123. if log is None:
  1124. return
  1125. client = self.get_client()
  1126. if not has_logs_enabled(client.options):
  1127. return
  1128. merged_scope = self._merge_scopes()
  1129. debug = client.options.get("debug", False)
  1130. if debug:
  1131. logger.debug(
  1132. f"[Sentry Logs] [{log.get('severity_text')}] {log.get('body')}"
  1133. )
  1134. client._capture_log(log, scope=merged_scope)
  1135. def _capture_metric(self, metric: "Optional[Metric]") -> None:
  1136. if metric is None:
  1137. return
  1138. client = self.get_client()
  1139. if not has_metrics_enabled(client.options):
  1140. return
  1141. merged_scope = self._merge_scopes()
  1142. debug = client.options.get("debug", False)
  1143. if debug:
  1144. logger.debug(
  1145. f"[Sentry Metrics] [{metric.get('type')}] {metric.get('name')}: {metric.get('value')}"
  1146. )
  1147. client._capture_metric(metric, scope=merged_scope)
  1148. def _capture_span(self, span: "Optional[StreamedSpan]") -> None:
  1149. if span is None:
  1150. return
  1151. client = self.get_client()
  1152. if not has_span_streaming_enabled(client.options):
  1153. return
  1154. merged_scope = self._merge_scopes()
  1155. client._capture_span(span, scope=merged_scope)
  1156. def capture_message(
  1157. self,
  1158. message: str,
  1159. level: "Optional[LogLevelStr]" = None,
  1160. scope: "Optional[Scope]" = None,
  1161. **scope_kwargs: "Any",
  1162. ) -> "Optional[str]":
  1163. """
  1164. Captures a message.
  1165. :param message: The string to send as the message.
  1166. :param level: If no level is provided, the default level is `info`.
  1167. :param scope: An optional :py:class:`sentry_sdk.Scope` to apply to events.
  1168. The `scope` and `scope_kwargs` parameters are mutually exclusive.
  1169. :param scope_kwargs: Optional data to apply to event.
  1170. For supported `**scope_kwargs` see :py:meth:`sentry_sdk.Scope.update_from_kwargs`.
  1171. The `scope` and `scope_kwargs` parameters are mutually exclusive.
  1172. :returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.client._Client.capture_event`).
  1173. """
  1174. if disable_capture_event.get(False):
  1175. return None
  1176. if level is None:
  1177. level = "info"
  1178. event: "Event" = {
  1179. "message": message,
  1180. "level": level,
  1181. }
  1182. return self.capture_event(event, scope=scope, **scope_kwargs)
  1183. def capture_exception(
  1184. self,
  1185. error: "Optional[Union[BaseException, ExcInfo]]" = None,
  1186. scope: "Optional[Scope]" = None,
  1187. **scope_kwargs: "Any",
  1188. ) -> "Optional[str]":
  1189. """Captures an exception.
  1190. :param error: An exception to capture. If `None`, `sys.exc_info()` will be used.
  1191. :param scope: An optional :py:class:`sentry_sdk.Scope` to apply to events.
  1192. The `scope` and `scope_kwargs` parameters are mutually exclusive.
  1193. :param scope_kwargs: Optional data to apply to event.
  1194. For supported `**scope_kwargs` see :py:meth:`sentry_sdk.Scope.update_from_kwargs`.
  1195. The `scope` and `scope_kwargs` parameters are mutually exclusive.
  1196. :returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.client._Client.capture_event`).
  1197. """
  1198. if disable_capture_event.get(False):
  1199. return None
  1200. if error is not None:
  1201. exc_info = exc_info_from_error(error)
  1202. else:
  1203. exc_info = sys.exc_info()
  1204. event, hint = event_from_exception(
  1205. exc_info, client_options=self.get_client().options
  1206. )
  1207. try:
  1208. return self.capture_event(event, hint=hint, scope=scope, **scope_kwargs)
  1209. except Exception:
  1210. capture_internal_exception(sys.exc_info())
  1211. return None
  1212. def start_session(self, *args: "Any", **kwargs: "Any") -> None:
  1213. """Starts a new session."""
  1214. session_mode = kwargs.pop("session_mode", "application")
  1215. self.end_session()
  1216. client = self.get_client()
  1217. self._session = Session(
  1218. release=client.options.get("release"),
  1219. environment=client.options.get("environment"),
  1220. user=self._user,
  1221. session_mode=session_mode,
  1222. )
  1223. def end_session(self, *args: "Any", **kwargs: "Any") -> None:
  1224. """Ends the current session if there is one."""
  1225. session = self._session
  1226. self._session = None
  1227. if session is not None:
  1228. session.close()
  1229. self.get_client().capture_session(session)
  1230. def stop_auto_session_tracking(self, *args: "Any", **kwargs: "Any") -> None:
  1231. """Stops automatic session tracking.
  1232. This temporarily session tracking for the current scope when called.
  1233. To resume session tracking call `resume_auto_session_tracking`.
  1234. """
  1235. self.end_session()
  1236. self._force_auto_session_tracking = False
  1237. def resume_auto_session_tracking(self) -> None:
  1238. """Resumes automatic session tracking for the current scope if
  1239. disabled earlier. This requires that generally automatic session
  1240. tracking is enabled.
  1241. """
  1242. self._force_auto_session_tracking = None
  1243. def add_event_processor(
  1244. self,
  1245. func: "EventProcessor",
  1246. ) -> None:
  1247. """Register a scope local event processor on the scope.
  1248. :param func: This function behaves like `before_send.`
  1249. """
  1250. if len(self._event_processors) > 20:
  1251. logger.warning(
  1252. "Too many event processors on scope! Clearing list to free up some memory: %r",
  1253. self._event_processors,
  1254. )
  1255. del self._event_processors[:]
  1256. self._event_processors.append(func)
  1257. def add_error_processor(
  1258. self,
  1259. func: "ErrorProcessor",
  1260. cls: "Optional[Type[BaseException]]" = None,
  1261. ) -> None:
  1262. """Register a scope local error processor on the scope.
  1263. :param func: A callback that works similar to an event processor but is invoked with the original exception info triple as second argument.
  1264. :param cls: Optionally, only process exceptions of this type.
  1265. """
  1266. if cls is not None:
  1267. cls_ = cls # For mypy.
  1268. real_func = func
  1269. def func(event: "Event", exc_info: "ExcInfo") -> "Optional[Event]":
  1270. try:
  1271. is_inst = isinstance(exc_info[1], cls_)
  1272. except Exception:
  1273. is_inst = False
  1274. if is_inst:
  1275. return real_func(event, exc_info)
  1276. return event
  1277. self._error_processors.append(func)
  1278. def _apply_level_to_event(
  1279. self, event: "Event", hint: "Hint", options: "Optional[Dict[str, Any]]"
  1280. ) -> None:
  1281. if self._level is not None:
  1282. event["level"] = self._level
  1283. def _apply_breadcrumbs_to_event(
  1284. self, event: "Event", hint: "Hint", options: "Optional[Dict[str, Any]]"
  1285. ) -> None:
  1286. event.setdefault("breadcrumbs", {})
  1287. # This check is just for mypy -
  1288. if not isinstance(event["breadcrumbs"], AnnotatedValue):
  1289. event["breadcrumbs"].setdefault("values", [])
  1290. event["breadcrumbs"]["values"].extend(self._breadcrumbs)
  1291. # Attempt to sort timestamps
  1292. try:
  1293. if not isinstance(event["breadcrumbs"], AnnotatedValue):
  1294. for crumb in event["breadcrumbs"]["values"]:
  1295. if isinstance(crumb["timestamp"], str):
  1296. crumb["timestamp"] = datetime_from_isoformat(crumb["timestamp"])
  1297. event["breadcrumbs"]["values"].sort(
  1298. key=lambda crumb: crumb["timestamp"]
  1299. )
  1300. except Exception as err:
  1301. logger.debug("Error when sorting breadcrumbs", exc_info=err)
  1302. pass
  1303. def _apply_user_to_event(
  1304. self, event: "Event", hint: "Hint", options: "Optional[Dict[str, Any]]"
  1305. ) -> None:
  1306. if event.get("user") is None and self._user is not None:
  1307. event["user"] = self._user
  1308. def _apply_transaction_name_to_event(
  1309. self, event: "Event", hint: "Hint", options: "Optional[Dict[str, Any]]"
  1310. ) -> None:
  1311. if event.get("transaction") is None and self._transaction is not None:
  1312. event["transaction"] = self._transaction
  1313. def _apply_transaction_info_to_event(
  1314. self, event: "Event", hint: "Hint", options: "Optional[Dict[str, Any]]"
  1315. ) -> None:
  1316. if event.get("transaction_info") is None and self._transaction_info is not None:
  1317. event["transaction_info"] = self._transaction_info
  1318. def _apply_fingerprint_to_event(
  1319. self, event: "Event", hint: "Hint", options: "Optional[Dict[str, Any]]"
  1320. ) -> None:
  1321. if event.get("fingerprint") is None and self._fingerprint is not None:
  1322. event["fingerprint"] = self._fingerprint
  1323. def _apply_extra_to_event(
  1324. self, event: "Event", hint: "Hint", options: "Optional[Dict[str, Any]]"
  1325. ) -> None:
  1326. if self._extras:
  1327. event.setdefault("extra", {}).update(self._extras)
  1328. def _apply_tags_to_event(
  1329. self, event: "Event", hint: "Hint", options: "Optional[Dict[str, Any]]"
  1330. ) -> None:
  1331. if self._tags:
  1332. event.setdefault("tags", {}).update(self._tags)
  1333. def _apply_contexts_to_event(
  1334. self, event: "Event", hint: "Hint", options: "Optional[Dict[str, Any]]"
  1335. ) -> None:
  1336. if self._contexts:
  1337. event.setdefault("contexts", {}).update(self._contexts)
  1338. contexts = event.setdefault("contexts", {})
  1339. # Add "trace" context
  1340. if contexts.get("trace") is None:
  1341. contexts["trace"] = self.get_trace_context()
  1342. def _apply_flags_to_event(
  1343. self, event: "Event", hint: "Hint", options: "Optional[Dict[str, Any]]"
  1344. ) -> None:
  1345. flags = self.flags.get()
  1346. if len(flags) > 0:
  1347. event.setdefault("contexts", {}).setdefault("flags", {}).update(
  1348. {"values": flags}
  1349. )
  1350. def _apply_scope_attributes_to_telemetry(
  1351. self, telemetry: "Union[Log, Metric, StreamedSpan]"
  1352. ) -> None:
  1353. # TODO: turn Logs, Metrics into actual classes
  1354. if isinstance(telemetry, dict):
  1355. attributes = telemetry["attributes"]
  1356. else:
  1357. attributes = telemetry._attributes
  1358. for attribute, value in self._attributes.items():
  1359. if attribute not in attributes:
  1360. attributes[attribute] = value
  1361. def _apply_user_attributes_to_telemetry(
  1362. self, telemetry: "Union[Log, Metric, StreamedSpan]"
  1363. ) -> None:
  1364. if isinstance(telemetry, dict):
  1365. attributes = telemetry["attributes"]
  1366. else:
  1367. attributes = telemetry._attributes
  1368. if not should_send_default_pii() or self._user is None:
  1369. return
  1370. for attribute_name, user_attribute in (
  1371. ("user.id", "id"),
  1372. ("user.name", "username"),
  1373. ("user.email", "email"),
  1374. ):
  1375. if user_attribute in self._user and attribute_name not in attributes:
  1376. attributes[attribute_name] = self._user[user_attribute]
  1377. def _drop(self, cause: "Any", ty: str) -> "Optional[Any]":
  1378. logger.info("%s (%s) dropped event", ty, cause)
  1379. return None
  1380. def run_error_processors(self, event: "Event", hint: "Hint") -> "Optional[Event]":
  1381. """
  1382. Runs the error processors on the event and returns the modified event.
  1383. """
  1384. exc_info = hint.get("exc_info")
  1385. if exc_info is not None:
  1386. error_processors = chain(
  1387. self.get_global_scope()._error_processors,
  1388. self.get_isolation_scope()._error_processors,
  1389. self.get_current_scope()._error_processors,
  1390. )
  1391. for error_processor in error_processors:
  1392. new_event = error_processor(event, exc_info)
  1393. if new_event is None:
  1394. return self._drop(error_processor, "error processor")
  1395. event = new_event
  1396. return event
  1397. def run_event_processors(self, event: "Event", hint: "Hint") -> "Optional[Event]":
  1398. """
  1399. Runs the event processors on the event and returns the modified event.
  1400. """
  1401. ty = event.get("type")
  1402. is_check_in = ty == "check_in"
  1403. if not is_check_in:
  1404. # Get scopes without creating them to prevent infinite recursion
  1405. isolation_scope = _isolation_scope.get()
  1406. current_scope = _current_scope.get()
  1407. event_processors = chain(
  1408. global_event_processors,
  1409. _global_scope and _global_scope._event_processors or [],
  1410. isolation_scope and isolation_scope._event_processors or [],
  1411. current_scope and current_scope._event_processors or [],
  1412. )
  1413. for event_processor in event_processors:
  1414. new_event = event
  1415. with capture_internal_exceptions():
  1416. new_event = event_processor(event, hint)
  1417. if new_event is None:
  1418. return self._drop(event_processor, "event processor")
  1419. event = new_event
  1420. return event
  1421. @_disable_capture
  1422. def apply_to_event(
  1423. self,
  1424. event: "Event",
  1425. hint: "Hint",
  1426. options: "Optional[Dict[str, Any]]" = None,
  1427. ) -> "Optional[Event]":
  1428. """Applies the information contained on the scope to the given event."""
  1429. ty = event.get("type")
  1430. is_transaction = ty == "transaction"
  1431. is_check_in = ty == "check_in"
  1432. # put all attachments into the hint. This lets callbacks play around
  1433. # with attachments. We also later pull this out of the hint when we
  1434. # create the envelope.
  1435. attachments_to_send = hint.get("attachments") or []
  1436. for attachment in self._attachments:
  1437. if not is_transaction or attachment.add_to_transactions:
  1438. attachments_to_send.append(attachment)
  1439. hint["attachments"] = attachments_to_send
  1440. self._apply_contexts_to_event(event, hint, options)
  1441. if is_check_in:
  1442. # Check-ins only support the trace context, strip all others
  1443. event["contexts"] = {
  1444. "trace": event.setdefault("contexts", {}).get("trace", {})
  1445. }
  1446. if not is_check_in:
  1447. self._apply_level_to_event(event, hint, options)
  1448. self._apply_fingerprint_to_event(event, hint, options)
  1449. self._apply_user_to_event(event, hint, options)
  1450. self._apply_transaction_name_to_event(event, hint, options)
  1451. self._apply_transaction_info_to_event(event, hint, options)
  1452. self._apply_tags_to_event(event, hint, options)
  1453. self._apply_extra_to_event(event, hint, options)
  1454. if not is_transaction and not is_check_in:
  1455. self._apply_breadcrumbs_to_event(event, hint, options)
  1456. self._apply_flags_to_event(event, hint, options)
  1457. event = self.run_error_processors(event, hint)
  1458. if event is None:
  1459. return None
  1460. event = self.run_event_processors(event, hint)
  1461. if event is None:
  1462. return None
  1463. return event
  1464. @_disable_capture
  1465. def apply_to_telemetry(self, telemetry: "Union[Log, Metric, StreamedSpan]") -> None:
  1466. # Attributes-based events and telemetry go through here (logs, metrics,
  1467. # spansV2)
  1468. if not isinstance(telemetry, StreamedSpan):
  1469. trace_context = self.get_trace_context()
  1470. trace_id = trace_context.get("trace_id")
  1471. if telemetry.get("trace_id") is None:
  1472. telemetry["trace_id"] = (
  1473. trace_id or "00000000-0000-0000-0000-000000000000"
  1474. )
  1475. span_id = trace_context.get("span_id")
  1476. if telemetry.get("span_id") is None and span_id:
  1477. telemetry["span_id"] = span_id
  1478. self._apply_scope_attributes_to_telemetry(telemetry)
  1479. self._apply_user_attributes_to_telemetry(telemetry)
  1480. def update_from_scope(self, scope: "Scope") -> None:
  1481. """Update the scope with another scope's data."""
  1482. if scope._level is not None:
  1483. self._level = scope._level
  1484. if scope._fingerprint is not None:
  1485. self._fingerprint = scope._fingerprint
  1486. if scope._transaction is not None:
  1487. self._transaction = scope._transaction
  1488. if scope._transaction_info is not None:
  1489. self._transaction_info.update(scope._transaction_info)
  1490. if scope._user is not None:
  1491. self._user = scope._user
  1492. if scope._tags:
  1493. self._tags.update(scope._tags)
  1494. if scope._contexts:
  1495. self._contexts.update(scope._contexts)
  1496. if scope._extras:
  1497. self._extras.update(scope._extras)
  1498. if scope._breadcrumbs:
  1499. self._breadcrumbs.extend(scope._breadcrumbs)
  1500. if scope._n_breadcrumbs_truncated:
  1501. self._n_breadcrumbs_truncated = (
  1502. self._n_breadcrumbs_truncated + scope._n_breadcrumbs_truncated
  1503. )
  1504. if scope._gen_ai_original_message_count:
  1505. self._gen_ai_original_message_count.update(
  1506. scope._gen_ai_original_message_count
  1507. )
  1508. if scope._gen_ai_conversation_id:
  1509. self._gen_ai_conversation_id = scope._gen_ai_conversation_id
  1510. if scope._span:
  1511. self._span = scope._span
  1512. if scope._attachments:
  1513. self._attachments.extend(scope._attachments)
  1514. if scope._profile:
  1515. self._profile = scope._profile
  1516. if scope._propagation_context:
  1517. self._propagation_context = scope._propagation_context
  1518. if scope._session:
  1519. self._session = scope._session
  1520. if scope._flags:
  1521. if not self._flags:
  1522. self._flags = deepcopy(scope._flags)
  1523. else:
  1524. for flag in scope._flags.get():
  1525. self._flags.set(flag["flag"], flag["result"])
  1526. if scope._attributes:
  1527. self._attributes.update(scope._attributes)
  1528. def update_from_kwargs(
  1529. self,
  1530. user: "Optional[Any]" = None,
  1531. level: "Optional[LogLevelStr]" = None,
  1532. extras: "Optional[Dict[str, Any]]" = None,
  1533. contexts: "Optional[Dict[str, Dict[str, Any]]]" = None,
  1534. tags: "Optional[Dict[str, str]]" = None,
  1535. fingerprint: "Optional[List[str]]" = None,
  1536. attributes: "Optional[Attributes]" = None,
  1537. ) -> None:
  1538. """Update the scope's attributes."""
  1539. if level is not None:
  1540. self._level = level
  1541. if user is not None:
  1542. self._user = user
  1543. if extras is not None:
  1544. self._extras.update(extras)
  1545. if contexts is not None:
  1546. self._contexts.update(contexts)
  1547. if tags is not None:
  1548. self._tags.update(tags)
  1549. if fingerprint is not None:
  1550. self._fingerprint = fingerprint
  1551. if attributes is not None:
  1552. self._attributes.update(attributes)
  1553. def __repr__(self) -> str:
  1554. return "<%s id=%s name=%s type=%s>" % (
  1555. self.__class__.__name__,
  1556. hex(id(self)),
  1557. self._name,
  1558. self._type,
  1559. )
  1560. @property
  1561. def flags(self) -> "FlagBuffer":
  1562. if self._flags is None:
  1563. max_flags = (
  1564. self.get_client().options["_experiments"].get("max_flags")
  1565. or DEFAULT_FLAG_CAPACITY
  1566. )
  1567. self._flags = FlagBuffer(capacity=max_flags)
  1568. return self._flags
  1569. def set_attribute(self, attribute: str, value: "AttributeValue") -> None:
  1570. """
  1571. Set an attribute on the scope.
  1572. Any attributes-based telemetry (logs, metrics) captured while this scope
  1573. is active will inherit attributes set on the scope.
  1574. """
  1575. self._attributes[attribute] = format_attribute(value)
  1576. def remove_attribute(self, attribute: str) -> None:
  1577. """Remove an attribute if set on the scope. No-op if there is no such attribute."""
  1578. try:
  1579. del self._attributes[attribute]
  1580. except KeyError:
  1581. pass
  1582. @contextmanager
  1583. def new_scope() -> "Generator[Scope, None, None]":
  1584. """
  1585. .. versionadded:: 2.0.0
  1586. Context manager that forks the current scope and runs the wrapped code in it.
  1587. After the wrapped code is executed, the original scope is restored.
  1588. Example Usage:
  1589. .. code-block:: python
  1590. import sentry_sdk
  1591. with sentry_sdk.new_scope() as scope:
  1592. scope.set_tag("color", "green")
  1593. sentry_sdk.capture_message("hello") # will include `color` tag.
  1594. sentry_sdk.capture_message("hello, again") # will NOT include `color` tag.
  1595. """
  1596. # fork current scope
  1597. current_scope = Scope.get_current_scope()
  1598. new_scope = current_scope.fork()
  1599. token = _current_scope.set(new_scope)
  1600. try:
  1601. yield new_scope
  1602. finally:
  1603. try:
  1604. # restore original scope
  1605. _current_scope.reset(token)
  1606. except (LookupError, ValueError):
  1607. capture_internal_exception(sys.exc_info())
  1608. @contextmanager
  1609. def use_scope(scope: "Scope") -> "Generator[Scope, None, None]":
  1610. """
  1611. .. versionadded:: 2.0.0
  1612. Context manager that uses the given `scope` and runs the wrapped code in it.
  1613. After the wrapped code is executed, the original scope is restored.
  1614. Example Usage:
  1615. Suppose the variable `scope` contains a `Scope` object, which is not currently
  1616. the active scope.
  1617. .. code-block:: python
  1618. import sentry_sdk
  1619. with sentry_sdk.use_scope(scope):
  1620. scope.set_tag("color", "green")
  1621. sentry_sdk.capture_message("hello") # will include `color` tag.
  1622. sentry_sdk.capture_message("hello, again") # will NOT include `color` tag.
  1623. """
  1624. # set given scope as current scope
  1625. token = _current_scope.set(scope)
  1626. try:
  1627. yield scope
  1628. finally:
  1629. try:
  1630. # restore original scope
  1631. _current_scope.reset(token)
  1632. except (LookupError, ValueError):
  1633. capture_internal_exception(sys.exc_info())
  1634. @contextmanager
  1635. def isolation_scope() -> "Generator[Scope, None, None]":
  1636. """
  1637. .. versionadded:: 2.0.0
  1638. Context manager that forks the current isolation scope and runs the wrapped code in it.
  1639. The current scope is also forked to not bleed data into the existing current scope.
  1640. After the wrapped code is executed, the original scopes are restored.
  1641. Example Usage:
  1642. .. code-block:: python
  1643. import sentry_sdk
  1644. with sentry_sdk.isolation_scope() as scope:
  1645. scope.set_tag("color", "green")
  1646. sentry_sdk.capture_message("hello") # will include `color` tag.
  1647. sentry_sdk.capture_message("hello, again") # will NOT include `color` tag.
  1648. """
  1649. # fork current scope
  1650. current_scope = Scope.get_current_scope()
  1651. forked_current_scope = current_scope.fork()
  1652. current_token = _current_scope.set(forked_current_scope)
  1653. # fork isolation scope
  1654. isolation_scope = Scope.get_isolation_scope()
  1655. new_isolation_scope = isolation_scope.fork()
  1656. isolation_token = _isolation_scope.set(new_isolation_scope)
  1657. try:
  1658. yield new_isolation_scope
  1659. finally:
  1660. # restore original scopes
  1661. try:
  1662. _current_scope.reset(current_token)
  1663. except (LookupError, ValueError):
  1664. capture_internal_exception(sys.exc_info())
  1665. try:
  1666. _isolation_scope.reset(isolation_token)
  1667. except (LookupError, ValueError):
  1668. capture_internal_exception(sys.exc_info())
  1669. @contextmanager
  1670. def use_isolation_scope(isolation_scope: "Scope") -> "Generator[Scope, None, None]":
  1671. """
  1672. .. versionadded:: 2.0.0
  1673. Context manager that uses the given `isolation_scope` and runs the wrapped code in it.
  1674. The current scope is also forked to not bleed data into the existing current scope.
  1675. After the wrapped code is executed, the original scopes are restored.
  1676. Example Usage:
  1677. .. code-block:: python
  1678. import sentry_sdk
  1679. with sentry_sdk.isolation_scope() as scope:
  1680. scope.set_tag("color", "green")
  1681. sentry_sdk.capture_message("hello") # will include `color` tag.
  1682. sentry_sdk.capture_message("hello, again") # will NOT include `color` tag.
  1683. """
  1684. # fork current scope
  1685. current_scope = Scope.get_current_scope()
  1686. forked_current_scope = current_scope.fork()
  1687. current_token = _current_scope.set(forked_current_scope)
  1688. # set given scope as isolation scope
  1689. isolation_token = _isolation_scope.set(isolation_scope)
  1690. try:
  1691. yield isolation_scope
  1692. finally:
  1693. # restore original scopes
  1694. try:
  1695. _current_scope.reset(current_token)
  1696. except (LookupError, ValueError):
  1697. capture_internal_exception(sys.exc_info())
  1698. try:
  1699. _isolation_scope.reset(isolation_token)
  1700. except (LookupError, ValueError):
  1701. capture_internal_exception(sys.exc_info())
  1702. def should_send_default_pii() -> bool:
  1703. """Shortcut for `Scope.get_client().should_send_default_pii()`."""
  1704. return Scope.get_client().should_send_default_pii()
  1705. # Circular imports
  1706. from sentry_sdk.client import NonRecordingClient
  1707. if TYPE_CHECKING:
  1708. import sentry_sdk.client