scope.py 65 KB

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