tracing.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  1. import uuid
  2. import warnings
  3. from datetime import datetime, timedelta, timezone
  4. from enum import Enum
  5. from typing import TYPE_CHECKING
  6. import sentry_sdk
  7. from sentry_sdk.consts import INSTRUMENTER, SPANDATA, SPANSTATUS, SPANTEMPLATE
  8. from sentry_sdk.profiler.continuous_profiler import get_profiler_id
  9. from sentry_sdk.utils import (
  10. capture_internal_exceptions,
  11. get_current_thread_meta,
  12. is_valid_sample_rate,
  13. logger,
  14. nanosecond_time,
  15. should_be_treated_as_error,
  16. )
  17. if TYPE_CHECKING:
  18. from collections.abc import Callable, Mapping, MutableMapping
  19. from typing import (
  20. Any,
  21. Dict,
  22. Iterator,
  23. List,
  24. Optional,
  25. ParamSpec,
  26. Tuple,
  27. TypeVar,
  28. Union,
  29. overload,
  30. )
  31. from typing_extensions import TypedDict, Unpack
  32. P = ParamSpec("P")
  33. R = TypeVar("R")
  34. from sentry_sdk._types import (
  35. Event,
  36. MeasurementUnit,
  37. MeasurementValue,
  38. SamplingContext,
  39. )
  40. from sentry_sdk.profiler.continuous_profiler import ContinuousProfile
  41. from sentry_sdk.profiler.transaction_profiler import Profile
  42. class SpanKwargs(TypedDict, total=False):
  43. trace_id: str
  44. """
  45. The trace ID of the root span. If this new span is to be the root span,
  46. omit this parameter, and a new trace ID will be generated.
  47. """
  48. span_id: str
  49. """The span ID of this span. If omitted, a new span ID will be generated."""
  50. parent_span_id: str
  51. """The span ID of the parent span, if applicable."""
  52. same_process_as_parent: bool
  53. """Whether this span is in the same process as the parent span."""
  54. sampled: bool
  55. """
  56. Whether the span should be sampled. Overrides the default sampling decision
  57. for this span when provided.
  58. """
  59. op: str
  60. """
  61. The span's operation. A list of recommended values is available here:
  62. https://develop.sentry.dev/sdk/performance/span-operations/
  63. """
  64. description: str
  65. """A description of what operation is being performed within the span. This argument is DEPRECATED. Please use the `name` parameter, instead."""
  66. hub: "Optional[sentry_sdk.Hub]"
  67. """The hub to use for this span. This argument is DEPRECATED. Please use the `scope` parameter, instead."""
  68. status: str
  69. """The span's status. Possible values are listed at https://develop.sentry.dev/sdk/event-payloads/span/"""
  70. containing_transaction: "Optional[Transaction]"
  71. """The transaction that this span belongs to."""
  72. start_timestamp: "Optional[Union[datetime, float]]"
  73. """
  74. The timestamp when the span started. If omitted, the current time
  75. will be used.
  76. """
  77. scope: "sentry_sdk.Scope"
  78. """The scope to use for this span. If not provided, we use the current scope."""
  79. origin: str
  80. """
  81. The origin of the span.
  82. See https://develop.sentry.dev/sdk/performance/trace-origin/
  83. Default "manual".
  84. """
  85. name: str
  86. """A string describing what operation is being performed within the span/transaction."""
  87. class TransactionKwargs(SpanKwargs, total=False):
  88. source: str
  89. """
  90. A string describing the source of the transaction name. This will be used to determine the transaction's type.
  91. See https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations for more information.
  92. Default "custom".
  93. """
  94. parent_sampled: bool
  95. """Whether the parent transaction was sampled. If True this transaction will be kept, if False it will be discarded."""
  96. baggage: "Baggage"
  97. """The W3C baggage header value. (see https://www.w3.org/TR/baggage/)"""
  98. ProfileContext = TypedDict(
  99. "ProfileContext",
  100. {
  101. "profiler_id": str,
  102. },
  103. )
  104. BAGGAGE_HEADER_NAME = "baggage"
  105. SENTRY_TRACE_HEADER_NAME = "sentry-trace"
  106. # Transaction source
  107. # see https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations
  108. class TransactionSource(str, Enum):
  109. COMPONENT = "component"
  110. CUSTOM = "custom"
  111. ROUTE = "route"
  112. TASK = "task"
  113. URL = "url"
  114. VIEW = "view"
  115. def __str__(self) -> str:
  116. return self.value
  117. # These are typically high cardinality and the server hates them
  118. LOW_QUALITY_TRANSACTION_SOURCES = [
  119. TransactionSource.URL,
  120. ]
  121. SOURCE_FOR_STYLE = {
  122. "endpoint": TransactionSource.COMPONENT,
  123. "function_name": TransactionSource.COMPONENT,
  124. "handler_name": TransactionSource.COMPONENT,
  125. "method_and_path_pattern": TransactionSource.ROUTE,
  126. "path": TransactionSource.URL,
  127. "route_name": TransactionSource.COMPONENT,
  128. "route_pattern": TransactionSource.ROUTE,
  129. "uri_template": TransactionSource.ROUTE,
  130. "url": TransactionSource.ROUTE,
  131. }
  132. def get_span_status_from_http_code(http_status_code: int) -> str:
  133. """
  134. Returns the Sentry status corresponding to the given HTTP status code.
  135. See: https://develop.sentry.dev/sdk/event-payloads/contexts/#trace-context
  136. """
  137. if http_status_code < 400:
  138. return SPANSTATUS.OK
  139. elif 400 <= http_status_code < 500:
  140. if http_status_code == 403:
  141. return SPANSTATUS.PERMISSION_DENIED
  142. elif http_status_code == 404:
  143. return SPANSTATUS.NOT_FOUND
  144. elif http_status_code == 429:
  145. return SPANSTATUS.RESOURCE_EXHAUSTED
  146. elif http_status_code == 413:
  147. return SPANSTATUS.FAILED_PRECONDITION
  148. elif http_status_code == 401:
  149. return SPANSTATUS.UNAUTHENTICATED
  150. elif http_status_code == 409:
  151. return SPANSTATUS.ALREADY_EXISTS
  152. else:
  153. return SPANSTATUS.INVALID_ARGUMENT
  154. elif 500 <= http_status_code < 600:
  155. if http_status_code == 504:
  156. return SPANSTATUS.DEADLINE_EXCEEDED
  157. elif http_status_code == 501:
  158. return SPANSTATUS.UNIMPLEMENTED
  159. elif http_status_code == 503:
  160. return SPANSTATUS.UNAVAILABLE
  161. else:
  162. return SPANSTATUS.INTERNAL_ERROR
  163. return SPANSTATUS.UNKNOWN_ERROR
  164. class _SpanRecorder:
  165. """Limits the number of spans recorded in a transaction."""
  166. __slots__ = ("maxlen", "spans", "dropped_spans")
  167. def __init__(self, maxlen: int) -> None:
  168. # FIXME: this is `maxlen - 1` only to preserve historical behavior
  169. # enforced by tests.
  170. # Either this should be changed to `maxlen` or the JS SDK implementation
  171. # should be changed to match a consistent interpretation of what maxlen
  172. # limits: either transaction+spans or only child spans.
  173. self.maxlen = maxlen - 1
  174. self.spans: "List[Span]" = []
  175. self.dropped_spans: int = 0
  176. def add(self, span: "Span") -> None:
  177. if len(self.spans) > self.maxlen:
  178. span._span_recorder = None
  179. self.dropped_spans += 1
  180. else:
  181. self.spans.append(span)
  182. class Span:
  183. """A span holds timing information of a block of code.
  184. Spans can have multiple child spans thus forming a span tree.
  185. :param trace_id: The trace ID of the root span. If this new span is to be the root span,
  186. omit this parameter, and a new trace ID will be generated.
  187. :param span_id: The span ID of this span. If omitted, a new span ID will be generated.
  188. :param parent_span_id: The span ID of the parent span, if applicable.
  189. :param same_process_as_parent: Whether this span is in the same process as the parent span.
  190. :param sampled: Whether the span should be sampled. Overrides the default sampling decision
  191. for this span when provided.
  192. :param op: The span's operation. A list of recommended values is available here:
  193. https://develop.sentry.dev/sdk/performance/span-operations/
  194. :param description: A description of what operation is being performed within the span.
  195. .. deprecated:: 2.15.0
  196. Please use the `name` parameter, instead.
  197. :param name: A string describing what operation is being performed within the span.
  198. :param hub: The hub to use for this span.
  199. .. deprecated:: 2.0.0
  200. Please use the `scope` parameter, instead.
  201. :param status: The span's status. Possible values are listed at
  202. https://develop.sentry.dev/sdk/event-payloads/span/
  203. :param containing_transaction: The transaction that this span belongs to.
  204. :param start_timestamp: The timestamp when the span started. If omitted, the current time
  205. will be used.
  206. :param scope: The scope to use for this span. If not provided, we use the current scope.
  207. """
  208. __slots__ = (
  209. "_trace_id",
  210. "_span_id",
  211. "parent_span_id",
  212. "same_process_as_parent",
  213. "sampled",
  214. "op",
  215. "description",
  216. "_measurements",
  217. "start_timestamp",
  218. "_start_timestamp_monotonic_ns",
  219. "status",
  220. "timestamp",
  221. "_tags",
  222. "_data",
  223. "_span_recorder",
  224. "hub",
  225. "_context_manager_state",
  226. "_containing_transaction",
  227. "scope",
  228. "origin",
  229. "name",
  230. "_flags",
  231. "_flags_capacity",
  232. )
  233. def __init__(
  234. self,
  235. trace_id: "Optional[str]" = None,
  236. span_id: "Optional[str]" = None,
  237. parent_span_id: "Optional[str]" = None,
  238. same_process_as_parent: bool = True,
  239. sampled: "Optional[bool]" = None,
  240. op: "Optional[str]" = None,
  241. description: "Optional[str]" = None,
  242. hub: "Optional[sentry_sdk.Hub]" = None, # deprecated
  243. status: "Optional[str]" = None,
  244. containing_transaction: "Optional[Transaction]" = None,
  245. start_timestamp: "Optional[Union[datetime, float]]" = None,
  246. scope: "Optional[sentry_sdk.Scope]" = None,
  247. origin: str = "manual",
  248. name: "Optional[str]" = None,
  249. ) -> None:
  250. self._trace_id = trace_id
  251. self._span_id = span_id
  252. self.parent_span_id = parent_span_id
  253. self.same_process_as_parent = same_process_as_parent
  254. self.sampled = sampled
  255. self.op = op
  256. self.description = name or description
  257. self.status = status
  258. self.hub = hub # backwards compatibility
  259. self.scope = scope
  260. self.origin = origin
  261. self._measurements: "Dict[str, MeasurementValue]" = {}
  262. self._tags: "MutableMapping[str, str]" = {}
  263. self._data: "Dict[str, Any]" = {}
  264. self._containing_transaction = containing_transaction
  265. self._flags: "Dict[str, bool]" = {}
  266. self._flags_capacity = 10
  267. if hub is not None:
  268. warnings.warn(
  269. "The `hub` parameter is deprecated. Please use `scope` instead.",
  270. DeprecationWarning,
  271. stacklevel=2,
  272. )
  273. self.scope = self.scope or hub.scope
  274. if start_timestamp is None:
  275. start_timestamp = datetime.now(timezone.utc)
  276. elif isinstance(start_timestamp, float):
  277. start_timestamp = datetime.fromtimestamp(start_timestamp, timezone.utc)
  278. self.start_timestamp = start_timestamp
  279. try:
  280. # profiling depends on this value and requires that
  281. # it is measured in nanoseconds
  282. self._start_timestamp_monotonic_ns = nanosecond_time()
  283. except AttributeError:
  284. pass
  285. #: End timestamp of span
  286. self.timestamp: "Optional[datetime]" = None
  287. self._span_recorder: "Optional[_SpanRecorder]" = None
  288. self.update_active_thread()
  289. self.set_profiler_id(get_profiler_id())
  290. # TODO this should really live on the Transaction class rather than the Span
  291. # class
  292. def init_span_recorder(self, maxlen: int) -> None:
  293. if self._span_recorder is None:
  294. self._span_recorder = _SpanRecorder(maxlen)
  295. @property
  296. def trace_id(self) -> str:
  297. if not self._trace_id:
  298. self._trace_id = uuid.uuid4().hex
  299. return self._trace_id
  300. @trace_id.setter
  301. def trace_id(self, value: str) -> None:
  302. self._trace_id = value
  303. @property
  304. def span_id(self) -> str:
  305. if not self._span_id:
  306. self._span_id = uuid.uuid4().hex[16:]
  307. return self._span_id
  308. @span_id.setter
  309. def span_id(self, value: str) -> None:
  310. self._span_id = value
  311. def __repr__(self) -> str:
  312. return (
  313. "<%s(op=%r, description:%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r, origin=%r)>"
  314. % (
  315. self.__class__.__name__,
  316. self.op,
  317. self.description,
  318. self.trace_id,
  319. self.span_id,
  320. self.parent_span_id,
  321. self.sampled,
  322. self.origin,
  323. )
  324. )
  325. def __enter__(self) -> "Span":
  326. scope = self.scope or sentry_sdk.get_current_scope()
  327. old_span = scope.span
  328. scope.span = self
  329. self._context_manager_state = (scope, old_span)
  330. return self
  331. def __exit__(
  332. self, ty: "Optional[Any]", value: "Optional[Any]", tb: "Optional[Any]"
  333. ) -> None:
  334. if value is not None and should_be_treated_as_error(ty, value):
  335. self.set_status(SPANSTATUS.INTERNAL_ERROR)
  336. with capture_internal_exceptions():
  337. scope, old_span = self._context_manager_state
  338. del self._context_manager_state
  339. self.finish(scope)
  340. scope.span = old_span
  341. @property
  342. def containing_transaction(self) -> "Optional[Transaction]":
  343. """The ``Transaction`` that this span belongs to.
  344. The ``Transaction`` is the root of the span tree,
  345. so one could also think of this ``Transaction`` as the "root span"."""
  346. # this is a getter rather than a regular attribute so that transactions
  347. # can return `self` here instead (as a way to prevent them circularly
  348. # referencing themselves)
  349. return self._containing_transaction
  350. def start_child(
  351. self, instrumenter: str = INSTRUMENTER.SENTRY, **kwargs: "Any"
  352. ) -> "Span":
  353. """
  354. Start a sub-span from the current span or transaction.
  355. Takes the same arguments as the initializer of :py:class:`Span`. The
  356. trace id, sampling decision, transaction pointer, and span recorder are
  357. inherited from the current span/transaction.
  358. The instrumenter parameter is deprecated for user code, and it will
  359. be removed in the next major version. Going forward, it should only
  360. be used by the SDK itself.
  361. """
  362. if kwargs.get("description") is not None:
  363. warnings.warn(
  364. "The `description` parameter is deprecated. Please use `name` instead.",
  365. DeprecationWarning,
  366. stacklevel=2,
  367. )
  368. configuration_instrumenter = sentry_sdk.get_client().options["instrumenter"]
  369. if instrumenter != configuration_instrumenter:
  370. return NoOpSpan()
  371. kwargs.setdefault("sampled", self.sampled)
  372. child = Span(
  373. trace_id=self.trace_id,
  374. parent_span_id=self.span_id,
  375. containing_transaction=self.containing_transaction,
  376. **kwargs,
  377. )
  378. span_recorder = (
  379. self.containing_transaction and self.containing_transaction._span_recorder
  380. )
  381. if span_recorder:
  382. span_recorder.add(child)
  383. return child
  384. @classmethod
  385. def continue_from_environ(
  386. cls,
  387. environ: "Mapping[str, str]",
  388. **kwargs: "Any",
  389. ) -> "Transaction":
  390. """
  391. DEPRECATED: Use :py:meth:`sentry_sdk.continue_trace`.
  392. Create a Transaction with the given params, then add in data pulled from
  393. the ``sentry-trace`` and ``baggage`` headers from the environ (if any)
  394. before returning the Transaction.
  395. This is different from :py:meth:`~sentry_sdk.tracing.Span.continue_from_headers`
  396. in that it assumes header names in the form ``HTTP_HEADER_NAME`` -
  397. such as you would get from a WSGI/ASGI environ -
  398. rather than the form ``header-name``.
  399. :param environ: The ASGI/WSGI environ to pull information from.
  400. """
  401. return Transaction.continue_from_headers(EnvironHeaders(environ), **kwargs)
  402. @classmethod
  403. def continue_from_headers(
  404. cls,
  405. headers: "Mapping[str, str]",
  406. *,
  407. _sample_rand: "Optional[str]" = None,
  408. **kwargs: "Any",
  409. ) -> "Transaction":
  410. """
  411. DEPRECATED: Use :py:meth:`sentry_sdk.continue_trace`.
  412. Create a transaction with the given params (including any data pulled from
  413. the ``sentry-trace`` and ``baggage`` headers).
  414. :param headers: The dictionary with the HTTP headers to pull information from.
  415. :param _sample_rand: If provided, we override the sample_rand value from the
  416. incoming headers with this value. (internal use only)
  417. """
  418. logger.warning("Deprecated: use sentry_sdk.continue_trace instead.")
  419. # TODO-neel move away from this kwargs stuff, it's confusing and opaque
  420. # make more explicit
  421. baggage = Baggage.from_incoming_header(
  422. headers.get(BAGGAGE_HEADER_NAME), _sample_rand=_sample_rand
  423. )
  424. kwargs.update({BAGGAGE_HEADER_NAME: baggage})
  425. sentrytrace_kwargs = extract_sentrytrace_data(
  426. headers.get(SENTRY_TRACE_HEADER_NAME)
  427. )
  428. if sentrytrace_kwargs is not None:
  429. kwargs.update(sentrytrace_kwargs)
  430. # If there's an incoming sentry-trace but no incoming baggage header,
  431. # for instance in traces coming from older SDKs,
  432. # baggage will be empty and immutable and won't be populated as head SDK.
  433. baggage.freeze()
  434. transaction = Transaction(**kwargs)
  435. transaction.same_process_as_parent = False
  436. return transaction
  437. def iter_headers(self) -> "Iterator[Tuple[str, str]]":
  438. """
  439. Creates a generator which returns the span's ``sentry-trace`` and ``baggage`` headers.
  440. If the span's containing transaction doesn't yet have a ``baggage`` value,
  441. this will cause one to be generated and stored.
  442. """
  443. if not self.containing_transaction:
  444. # Do not propagate headers if there is no containing transaction. Otherwise, this
  445. # span ends up being the root span of a new trace, and since it does not get sent
  446. # to Sentry, the trace will be missing a root transaction. The dynamic sampling
  447. # context will also be missing, breaking dynamic sampling & traces.
  448. return
  449. yield SENTRY_TRACE_HEADER_NAME, self.to_traceparent()
  450. baggage = self.containing_transaction.get_baggage().serialize()
  451. if baggage:
  452. yield BAGGAGE_HEADER_NAME, baggage
  453. @classmethod
  454. def from_traceparent(
  455. cls,
  456. traceparent: "Optional[str]",
  457. **kwargs: "Any",
  458. ) -> "Optional[Transaction]":
  459. """
  460. DEPRECATED: Use :py:meth:`sentry_sdk.continue_trace`.
  461. Create a ``Transaction`` with the given params, then add in data pulled from
  462. the given ``sentry-trace`` header value before returning the ``Transaction``.
  463. """
  464. if not traceparent:
  465. return None
  466. return cls.continue_from_headers(
  467. {SENTRY_TRACE_HEADER_NAME: traceparent}, **kwargs
  468. )
  469. def to_traceparent(self) -> str:
  470. if self.sampled is True:
  471. sampled = "1"
  472. elif self.sampled is False:
  473. sampled = "0"
  474. else:
  475. sampled = None
  476. traceparent = "%s-%s" % (self.trace_id, self.span_id)
  477. if sampled is not None:
  478. traceparent += "-%s" % (sampled,)
  479. return traceparent
  480. def to_baggage(self) -> "Optional[Baggage]":
  481. """Returns the :py:class:`~sentry_sdk.tracing_utils.Baggage`
  482. associated with this ``Span``, if any. (Taken from the root of the span tree.)
  483. """
  484. if self.containing_transaction:
  485. return self.containing_transaction.get_baggage()
  486. return None
  487. def set_tag(self, key: str, value: "Any") -> None:
  488. self._tags[key] = value
  489. def set_data(self, key: str, value: "Any") -> None:
  490. self._data[key] = value
  491. def update_data(self, data: "Dict[str, Any]") -> None:
  492. self._data.update(data)
  493. def set_flag(self, flag: str, result: bool) -> None:
  494. if len(self._flags) < self._flags_capacity:
  495. self._flags[flag] = result
  496. def set_status(self, value: str) -> None:
  497. self.status = value
  498. def set_measurement(
  499. self, name: str, value: float, unit: "MeasurementUnit" = ""
  500. ) -> None:
  501. """
  502. .. deprecated:: 2.28.0
  503. This function is deprecated and will be removed in the next major release.
  504. """
  505. warnings.warn(
  506. "`set_measurement()` is deprecated and will be removed in the next major version. Please use `set_data()` instead.",
  507. DeprecationWarning,
  508. stacklevel=2,
  509. )
  510. self._measurements[name] = {"value": value, "unit": unit}
  511. def set_thread(
  512. self, thread_id: "Optional[int]", thread_name: "Optional[str]"
  513. ) -> None:
  514. if thread_id is not None:
  515. self.set_data(SPANDATA.THREAD_ID, str(thread_id))
  516. if thread_name is not None:
  517. self.set_data(SPANDATA.THREAD_NAME, thread_name)
  518. def set_profiler_id(self, profiler_id: "Optional[str]") -> None:
  519. if profiler_id is not None:
  520. self.set_data(SPANDATA.PROFILER_ID, profiler_id)
  521. def set_http_status(self, http_status: int) -> None:
  522. self.set_tag(
  523. "http.status_code", str(http_status)
  524. ) # TODO-neel remove in major, we keep this for backwards compatibility
  525. self.set_data(SPANDATA.HTTP_STATUS_CODE, http_status)
  526. self.set_status(get_span_status_from_http_code(http_status))
  527. def is_success(self) -> bool:
  528. return self.status == "ok"
  529. def finish(
  530. self,
  531. scope: "Optional[sentry_sdk.Scope]" = None,
  532. end_timestamp: "Optional[Union[float, datetime]]" = None,
  533. ) -> "Optional[str]":
  534. """
  535. Sets the end timestamp of the span.
  536. Additionally it also creates a breadcrumb from the span,
  537. if the span represents a database or HTTP request.
  538. :param scope: The scope to use for this transaction.
  539. If not provided, the current scope will be used.
  540. :param end_timestamp: Optional timestamp that should
  541. be used as timestamp instead of the current time.
  542. :return: Always ``None``. The type is ``Optional[str]`` to match
  543. the return value of :py:meth:`sentry_sdk.tracing.Transaction.finish`.
  544. """
  545. if self.timestamp is not None:
  546. # This span is already finished, ignore.
  547. return None
  548. try:
  549. if end_timestamp:
  550. if isinstance(end_timestamp, float):
  551. end_timestamp = datetime.fromtimestamp(end_timestamp, timezone.utc)
  552. self.timestamp = end_timestamp
  553. else:
  554. elapsed = nanosecond_time() - self._start_timestamp_monotonic_ns
  555. self.timestamp = self.start_timestamp + timedelta(
  556. microseconds=elapsed / 1000
  557. )
  558. except AttributeError:
  559. self.timestamp = datetime.now(timezone.utc)
  560. scope = scope or sentry_sdk.get_current_scope()
  561. # Copy conversation_id from scope to span data if this is an AI span
  562. conversation_id = scope.get_conversation_id()
  563. if conversation_id:
  564. has_ai_op = SPANDATA.GEN_AI_OPERATION_NAME in self._data
  565. is_ai_span_op = self.op is not None and (
  566. self.op.startswith("ai.") or self.op.startswith("gen_ai.")
  567. )
  568. if has_ai_op or is_ai_span_op:
  569. self.set_data("gen_ai.conversation.id", conversation_id)
  570. maybe_create_breadcrumbs_from_span(scope, self)
  571. return None
  572. def to_json(self) -> "Dict[str, Any]":
  573. """Returns a JSON-compatible representation of the span."""
  574. rv: "Dict[str, Any]" = {
  575. "trace_id": self.trace_id,
  576. "span_id": self.span_id,
  577. "parent_span_id": self.parent_span_id,
  578. "same_process_as_parent": self.same_process_as_parent,
  579. "op": self.op,
  580. "description": self.description,
  581. "start_timestamp": self.start_timestamp,
  582. "timestamp": self.timestamp,
  583. "origin": self.origin,
  584. }
  585. if self.status:
  586. rv["status"] = self.status
  587. # TODO-neel remove redundant tag in major
  588. self._tags["status"] = self.status
  589. if len(self._measurements) > 0:
  590. rv["measurements"] = self._measurements
  591. tags = self._tags
  592. if tags:
  593. rv["tags"] = tags
  594. data = {}
  595. data.update(self._flags)
  596. data.update(self._data)
  597. if data:
  598. rv["data"] = data
  599. return rv
  600. def get_trace_context(self) -> "Any":
  601. rv: "Dict[str, Any]" = {
  602. "trace_id": self.trace_id,
  603. "span_id": self.span_id,
  604. "parent_span_id": self.parent_span_id,
  605. "op": self.op,
  606. "description": self.description,
  607. "origin": self.origin,
  608. }
  609. if self.status:
  610. rv["status"] = self.status
  611. if self.containing_transaction:
  612. rv["dynamic_sampling_context"] = (
  613. self.containing_transaction.get_baggage().dynamic_sampling_context()
  614. )
  615. data = {}
  616. thread_id = self._data.get(SPANDATA.THREAD_ID)
  617. if thread_id is not None:
  618. data["thread.id"] = thread_id
  619. thread_name = self._data.get(SPANDATA.THREAD_NAME)
  620. if thread_name is not None:
  621. data["thread.name"] = thread_name
  622. if data:
  623. rv["data"] = data
  624. return rv
  625. def get_profile_context(self) -> "Optional[ProfileContext]":
  626. profiler_id = self._data.get(SPANDATA.PROFILER_ID)
  627. if profiler_id is None:
  628. return None
  629. return {
  630. "profiler_id": profiler_id,
  631. }
  632. def update_active_thread(self) -> None:
  633. thread_id, thread_name = get_current_thread_meta()
  634. self.set_thread(thread_id, thread_name)
  635. # Private aliases matching StreamedSpan's private API
  636. _to_traceparent = to_traceparent
  637. _to_baggage = to_baggage
  638. _iter_headers = iter_headers
  639. _get_trace_context = get_trace_context
  640. class Transaction(Span):
  641. """The Transaction is the root element that holds all the spans
  642. for Sentry performance instrumentation.
  643. :param name: Identifier of the transaction.
  644. Will show up in the Sentry UI.
  645. :param parent_sampled: Whether the parent transaction was sampled.
  646. If True this transaction will be kept, if False it will be discarded.
  647. :param baggage: The W3C baggage header value.
  648. (see https://www.w3.org/TR/baggage/)
  649. :param source: A string describing the source of the transaction name.
  650. This will be used to determine the transaction's type.
  651. See https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations
  652. for more information. Default "custom".
  653. :param kwargs: Additional arguments to be passed to the Span constructor.
  654. See :py:class:`sentry_sdk.tracing.Span` for available arguments.
  655. """
  656. __slots__ = (
  657. "name",
  658. "source",
  659. "parent_sampled",
  660. # used to create baggage value for head SDKs in dynamic sampling
  661. "sample_rate",
  662. "_measurements",
  663. "_contexts",
  664. "_profile",
  665. "_continuous_profile",
  666. "_baggage",
  667. "_sample_rand",
  668. )
  669. def __init__( # type: ignore[misc]
  670. self,
  671. name: str = "",
  672. parent_sampled: "Optional[bool]" = None,
  673. baggage: "Optional[Baggage]" = None,
  674. source: str = TransactionSource.CUSTOM,
  675. **kwargs: "Unpack[SpanKwargs]",
  676. ) -> None:
  677. super().__init__(**kwargs)
  678. self.name = name
  679. self.source = source
  680. self.sample_rate: "Optional[float]" = None
  681. self.parent_sampled = parent_sampled
  682. self._measurements: "Dict[str, MeasurementValue]" = {}
  683. self._contexts: "Dict[str, Any]" = {}
  684. self._profile: "Optional[Profile]" = None
  685. self._continuous_profile: "Optional[ContinuousProfile]" = None
  686. self._baggage = baggage
  687. baggage_sample_rand = (
  688. None if self._baggage is None else self._baggage._sample_rand()
  689. )
  690. if baggage_sample_rand is not None:
  691. self._sample_rand = baggage_sample_rand
  692. else:
  693. self._sample_rand = _generate_sample_rand(self.trace_id)
  694. def __repr__(self) -> str:
  695. return (
  696. "<%s(name=%r, op=%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r, source=%r, origin=%r)>"
  697. % (
  698. self.__class__.__name__,
  699. self.name,
  700. self.op,
  701. self.trace_id,
  702. self.span_id,
  703. self.parent_span_id,
  704. self.sampled,
  705. self.source,
  706. self.origin,
  707. )
  708. )
  709. def _possibly_started(self) -> bool:
  710. """Returns whether the transaction might have been started.
  711. If this returns False, we know that the transaction was not started
  712. with sentry_sdk.start_transaction, and therefore the transaction will
  713. be discarded.
  714. """
  715. # We must explicitly check self.sampled is False since self.sampled can be None
  716. return self._span_recorder is not None or self.sampled is False
  717. def __enter__(self) -> "Transaction":
  718. if not self._possibly_started():
  719. logger.debug(
  720. "Transaction was entered without being started with sentry_sdk.start_transaction."
  721. "The transaction will not be sent to Sentry. To fix, start the transaction by"
  722. "passing it to sentry_sdk.start_transaction."
  723. )
  724. super().__enter__()
  725. if self._profile is not None:
  726. self._profile.__enter__()
  727. return self
  728. def __exit__(
  729. self, ty: "Optional[Any]", value: "Optional[Any]", tb: "Optional[Any]"
  730. ) -> None:
  731. if self._profile is not None:
  732. self._profile.__exit__(ty, value, tb)
  733. if self._continuous_profile is not None:
  734. self._continuous_profile.stop()
  735. super().__exit__(ty, value, tb)
  736. @property
  737. def containing_transaction(self) -> "Transaction":
  738. """The root element of the span tree.
  739. In the case of a transaction it is the transaction itself.
  740. """
  741. # Transactions (as spans) belong to themselves (as transactions). This
  742. # is a getter rather than a regular attribute to avoid having a circular
  743. # reference.
  744. return self
  745. def _get_scope_from_finish_args(
  746. self,
  747. scope_arg: "Optional[Union[sentry_sdk.Scope, sentry_sdk.Hub]]",
  748. hub_arg: "Optional[Union[sentry_sdk.Scope, sentry_sdk.Hub]]",
  749. ) -> "Optional[sentry_sdk.Scope]":
  750. """
  751. Logic to get the scope from the arguments passed to finish. This
  752. function exists for backwards compatibility with the old finish.
  753. TODO: Remove this function in the next major version.
  754. """
  755. scope_or_hub = scope_arg
  756. if hub_arg is not None:
  757. warnings.warn(
  758. "The `hub` parameter is deprecated. Please use the `scope` parameter, instead.",
  759. DeprecationWarning,
  760. stacklevel=3,
  761. )
  762. scope_or_hub = hub_arg
  763. if isinstance(scope_or_hub, sentry_sdk.Hub):
  764. warnings.warn(
  765. "Passing a Hub to finish is deprecated. Please pass a Scope, instead.",
  766. DeprecationWarning,
  767. stacklevel=3,
  768. )
  769. return scope_or_hub.scope
  770. return scope_or_hub
  771. def _get_log_representation(self) -> str:
  772. return "{op}transaction <{name}>".format(
  773. op=("<" + self.op + "> " if self.op else ""), name=self.name
  774. )
  775. def finish(
  776. self,
  777. scope: "Optional[sentry_sdk.Scope]" = None,
  778. end_timestamp: "Optional[Union[float, datetime]]" = None,
  779. *,
  780. hub: "Optional[sentry_sdk.Hub]" = None,
  781. ) -> "Optional[str]":
  782. """Finishes the transaction and sends it to Sentry.
  783. All finished spans in the transaction will also be sent to Sentry.
  784. :param scope: The Scope to use for this transaction.
  785. If not provided, the current Scope will be used.
  786. :param end_timestamp: Optional timestamp that should
  787. be used as timestamp instead of the current time.
  788. :param hub: The hub to use for this transaction.
  789. This argument is DEPRECATED. Please use the `scope`
  790. parameter, instead.
  791. :return: The event ID if the transaction was sent to Sentry,
  792. otherwise None.
  793. """
  794. if self.timestamp is not None:
  795. # This transaction is already finished, ignore.
  796. return None
  797. # For backwards compatibility, we must handle the case where `scope`
  798. # or `hub` could both either be a `Scope` or a `Hub`.
  799. scope: "Optional[sentry_sdk.Scope]" = self._get_scope_from_finish_args(
  800. scope, hub
  801. )
  802. scope = scope or self.scope or sentry_sdk.get_current_scope()
  803. client = sentry_sdk.get_client()
  804. if not client.is_active():
  805. # We have no active client and therefore nowhere to send this transaction.
  806. return None
  807. if self._span_recorder is None:
  808. # Explicit check against False needed because self.sampled might be None
  809. if self.sampled is False:
  810. logger.debug("Discarding transaction because sampled = False")
  811. else:
  812. logger.debug(
  813. "Discarding transaction because it was not started with sentry_sdk.start_transaction"
  814. )
  815. # This is not entirely accurate because discards here are not
  816. # exclusively based on sample rate but also traces sampler, but
  817. # we handle this the same here.
  818. if client.transport and has_tracing_enabled(client.options):
  819. if client.monitor and client.monitor.downsample_factor > 0:
  820. reason = "backpressure"
  821. else:
  822. reason = "sample_rate"
  823. client.transport.record_lost_event(reason, data_category="transaction")
  824. # Only one span (the transaction itself) is discarded, since we did not record any spans here.
  825. client.transport.record_lost_event(reason, data_category="span")
  826. return None
  827. if not self.name:
  828. logger.warning(
  829. "Transaction has no name, falling back to `<unlabeled transaction>`."
  830. )
  831. self.name = "<unlabeled transaction>"
  832. super().finish(scope, end_timestamp)
  833. status_code = self._data.get(SPANDATA.HTTP_STATUS_CODE)
  834. if (
  835. status_code is not None
  836. and status_code in client.options["trace_ignore_status_codes"]
  837. ):
  838. logger.debug(
  839. "[Tracing] Discarding {transaction_description} because the HTTP status code {status_code} is matched by trace_ignore_status_codes: {trace_ignore_status_codes}".format(
  840. transaction_description=self._get_log_representation(),
  841. status_code=self._data[SPANDATA.HTTP_STATUS_CODE],
  842. trace_ignore_status_codes=client.options[
  843. "trace_ignore_status_codes"
  844. ],
  845. )
  846. )
  847. if client.transport:
  848. client.transport.record_lost_event(
  849. "event_processor", data_category="transaction"
  850. )
  851. num_spans = len(self._span_recorder.spans) + 1
  852. client.transport.record_lost_event(
  853. "event_processor", data_category="span", quantity=num_spans
  854. )
  855. self.sampled = False
  856. if not self.sampled:
  857. # At this point a `sampled = None` should have already been resolved
  858. # to a concrete decision.
  859. if self.sampled is None:
  860. logger.warning("Discarding transaction without sampling decision.")
  861. return None
  862. finished_spans = [
  863. span.to_json()
  864. for span in self._span_recorder.spans
  865. if span.timestamp is not None
  866. ]
  867. len_diff = len(self._span_recorder.spans) - len(finished_spans)
  868. dropped_spans = len_diff + self._span_recorder.dropped_spans
  869. # we do this to break the circular reference of transaction -> span
  870. # recorder -> span -> containing transaction (which is where we started)
  871. # before either the spans or the transaction goes out of scope and has
  872. # to be garbage collected
  873. self._span_recorder = None
  874. contexts = {}
  875. contexts.update(self._contexts)
  876. contexts.update({"trace": self.get_trace_context()})
  877. profile_context = self.get_profile_context()
  878. if profile_context is not None:
  879. contexts.update({"profile": profile_context})
  880. event: "Event" = {
  881. "type": "transaction",
  882. "transaction": self.name,
  883. "transaction_info": {"source": self.source},
  884. "contexts": contexts,
  885. "tags": self._tags,
  886. "timestamp": self.timestamp,
  887. "start_timestamp": self.start_timestamp,
  888. "spans": finished_spans,
  889. }
  890. if dropped_spans > 0:
  891. event["_dropped_spans"] = dropped_spans
  892. if self._profile is not None and self._profile.valid():
  893. event["profile"] = self._profile
  894. self._profile = None
  895. event["measurements"] = self._measurements
  896. return scope.capture_event(event)
  897. def set_measurement(
  898. self, name: str, value: float, unit: "MeasurementUnit" = ""
  899. ) -> None:
  900. """
  901. .. deprecated:: 2.28.0
  902. This function is deprecated and will be removed in the next major release.
  903. """
  904. warnings.warn(
  905. "`set_measurement()` is deprecated and will be removed in the next major version. Please use `set_data()` instead.",
  906. DeprecationWarning,
  907. stacklevel=2,
  908. )
  909. self._measurements[name] = {"value": value, "unit": unit}
  910. def set_context(self, key: str, value: "dict[str, Any]") -> None:
  911. """Sets a context. Transactions can have multiple contexts
  912. and they should follow the format described in the "Contexts Interface"
  913. documentation.
  914. :param key: The name of the context.
  915. :param value: The information about the context.
  916. """
  917. self._contexts[key] = value
  918. def set_http_status(self, http_status: int) -> None:
  919. """Sets the status of the Transaction according to the given HTTP status.
  920. :param http_status: The HTTP status code."""
  921. super().set_http_status(http_status)
  922. self.set_context("response", {"status_code": http_status})
  923. def to_json(self) -> "Dict[str, Any]":
  924. """Returns a JSON-compatible representation of the transaction."""
  925. rv = super().to_json()
  926. rv["name"] = self.name
  927. rv["source"] = self.source
  928. rv["sampled"] = self.sampled
  929. return rv
  930. def get_trace_context(self) -> "Any":
  931. trace_context = super().get_trace_context()
  932. if self._data:
  933. trace_context["data"] = self._data
  934. return trace_context
  935. def get_baggage(self) -> "Baggage":
  936. """Returns the :py:class:`~sentry_sdk.tracing_utils.Baggage`
  937. associated with the Transaction.
  938. The first time a new baggage with Sentry items is made,
  939. it will be frozen."""
  940. if not self._baggage or self._baggage.mutable:
  941. self._baggage = Baggage.populate_from_transaction(self)
  942. return self._baggage
  943. def _set_initial_sampling_decision(
  944. self, sampling_context: "SamplingContext"
  945. ) -> None:
  946. """
  947. Sets the transaction's sampling decision, according to the following
  948. precedence rules:
  949. 1. If a sampling decision is passed to `start_transaction`
  950. (`start_transaction(name: "my transaction", sampled: True)`), that
  951. decision will be used, regardless of anything else
  952. 2. If `traces_sampler` is defined, its decision will be used. It can
  953. choose to keep or ignore any parent sampling decision, or use the
  954. sampling context data to make its own decision or to choose a sample
  955. rate for the transaction.
  956. 3. If `traces_sampler` is not defined, but there's a parent sampling
  957. decision, the parent sampling decision will be used.
  958. 4. If `traces_sampler` is not defined and there's no parent sampling
  959. decision, `traces_sample_rate` will be used.
  960. """
  961. client = sentry_sdk.get_client()
  962. transaction_description = self._get_log_representation()
  963. # nothing to do if tracing is disabled
  964. if not has_tracing_enabled(client.options):
  965. self.sampled = False
  966. return
  967. # if the user has forced a sampling decision by passing a `sampled`
  968. # value when starting the transaction, go with that
  969. if self.sampled is not None:
  970. self.sample_rate = float(self.sampled)
  971. return
  972. # we would have bailed already if neither `traces_sampler` nor
  973. # `traces_sample_rate` were defined, so one of these should work; prefer
  974. # the hook if so
  975. sample_rate = (
  976. client.options["traces_sampler"](sampling_context)
  977. if callable(client.options.get("traces_sampler"))
  978. # default inheritance behavior
  979. else (
  980. sampling_context["parent_sampled"]
  981. if sampling_context["parent_sampled"] is not None
  982. else client.options["traces_sample_rate"]
  983. )
  984. )
  985. # Since this is coming from the user (or from a function provided by the
  986. # user), who knows what we might get. (The only valid values are
  987. # booleans or numbers between 0 and 1.)
  988. if not is_valid_sample_rate(sample_rate, source="Tracing"):
  989. logger.warning(
  990. "[Tracing] Discarding {transaction_description} because of invalid sample rate.".format(
  991. transaction_description=transaction_description,
  992. )
  993. )
  994. self.sampled = False
  995. return
  996. self.sample_rate = float(sample_rate)
  997. if client.monitor:
  998. self.sample_rate /= 2**client.monitor.downsample_factor
  999. # if the function returned 0 (or false), or if `traces_sample_rate` is
  1000. # 0, it's a sign the transaction should be dropped
  1001. if not self.sample_rate:
  1002. logger.debug(
  1003. "[Tracing] Discarding {transaction_description} because {reason}".format(
  1004. transaction_description=transaction_description,
  1005. reason=(
  1006. "traces_sampler returned 0 or False"
  1007. if callable(client.options.get("traces_sampler"))
  1008. else "traces_sample_rate is set to 0"
  1009. ),
  1010. )
  1011. )
  1012. self.sampled = False
  1013. return
  1014. # Now we roll the dice.
  1015. self.sampled = self._sample_rand < self.sample_rate
  1016. if self.sampled:
  1017. logger.debug(
  1018. "[Tracing] Starting {transaction_description}".format(
  1019. transaction_description=transaction_description,
  1020. )
  1021. )
  1022. else:
  1023. logger.debug(
  1024. "[Tracing] Discarding {transaction_description} because it's not included in the random sample (sampling rate = {sample_rate})".format(
  1025. transaction_description=transaction_description,
  1026. sample_rate=self.sample_rate,
  1027. )
  1028. )
  1029. # Private aliases matching StreamedSpan's private API
  1030. _get_baggage = get_baggage
  1031. _get_trace_context = get_trace_context
  1032. class NoOpSpan(Span):
  1033. def __repr__(self) -> str:
  1034. return "<%s>" % self.__class__.__name__
  1035. @property
  1036. def containing_transaction(self) -> "Optional[Transaction]":
  1037. return None
  1038. def start_child(
  1039. self, instrumenter: str = INSTRUMENTER.SENTRY, **kwargs: "Any"
  1040. ) -> "NoOpSpan":
  1041. return NoOpSpan()
  1042. def to_traceparent(self) -> str:
  1043. return ""
  1044. def to_baggage(self) -> "Optional[Baggage]":
  1045. return None
  1046. def get_baggage(self) -> "Optional[Baggage]":
  1047. return None
  1048. def iter_headers(self) -> "Iterator[Tuple[str, str]]":
  1049. return iter(())
  1050. def set_tag(self, key: str, value: "Any") -> None:
  1051. pass
  1052. def set_data(self, key: str, value: "Any") -> None:
  1053. pass
  1054. def update_data(self, data: "Dict[str, Any]") -> None:
  1055. pass
  1056. def set_status(self, value: str) -> None:
  1057. pass
  1058. def set_http_status(self, http_status: int) -> None:
  1059. pass
  1060. def is_success(self) -> bool:
  1061. return True
  1062. def to_json(self) -> "Dict[str, Any]":
  1063. return {}
  1064. def get_trace_context(self) -> "Any":
  1065. return {}
  1066. def get_profile_context(self) -> "Any":
  1067. return {}
  1068. def finish(
  1069. self,
  1070. scope: "Optional[sentry_sdk.Scope]" = None,
  1071. end_timestamp: "Optional[Union[float, datetime]]" = None,
  1072. *,
  1073. hub: "Optional[sentry_sdk.Hub]" = None,
  1074. ) -> "Optional[str]":
  1075. """
  1076. The `hub` parameter is deprecated. Please use the `scope` parameter, instead.
  1077. """
  1078. pass
  1079. def set_measurement(
  1080. self, name: str, value: float, unit: "MeasurementUnit" = ""
  1081. ) -> None:
  1082. pass
  1083. def set_context(self, key: str, value: "dict[str, Any]") -> None:
  1084. pass
  1085. def init_span_recorder(self, maxlen: int) -> None:
  1086. pass
  1087. def _set_initial_sampling_decision(
  1088. self, sampling_context: "SamplingContext"
  1089. ) -> None:
  1090. pass
  1091. # Private aliases matching StreamedSpan's private API
  1092. _to_traceparent = to_traceparent
  1093. _to_baggage = to_baggage
  1094. _get_baggage = get_baggage
  1095. _iter_headers = iter_headers
  1096. _get_trace_context = get_trace_context
  1097. if TYPE_CHECKING:
  1098. @overload
  1099. def trace(
  1100. func: None = None,
  1101. *,
  1102. op: "Optional[str]" = None,
  1103. name: "Optional[str]" = None,
  1104. attributes: "Optional[dict[str, Any]]" = None,
  1105. template: "SPANTEMPLATE" = SPANTEMPLATE.DEFAULT,
  1106. ) -> "Callable[[Callable[P, R]], Callable[P, R]]":
  1107. # Handles: @trace() and @trace(op="custom")
  1108. pass
  1109. @overload
  1110. def trace(func: "Callable[P, R]") -> "Callable[P, R]":
  1111. # Handles: @trace
  1112. pass
  1113. def trace(
  1114. func: "Optional[Callable[P, R]]" = None,
  1115. *,
  1116. op: "Optional[str]" = None,
  1117. name: "Optional[str]" = None,
  1118. attributes: "Optional[dict[str, Any]]" = None,
  1119. template: "SPANTEMPLATE" = SPANTEMPLATE.DEFAULT,
  1120. ) -> "Union[Callable[P, R], Callable[[Callable[P, R]], Callable[P, R]]]":
  1121. """
  1122. Decorator to start a child span around a function call.
  1123. This decorator automatically creates a new span when the decorated function
  1124. is called, and finishes the span when the function returns or raises an exception.
  1125. :param func: The function to trace. When used as a decorator without parentheses,
  1126. this is the function being decorated. When used with parameters (e.g.,
  1127. ``@trace(op="custom")``, this should be None.
  1128. :type func: Callable or None
  1129. :param op: The operation name for the span. This is a high-level description
  1130. of what the span represents (e.g., "http.client", "db.query").
  1131. You can use predefined constants from :py:class:`sentry_sdk.consts.OP`
  1132. or provide your own string. If not provided, a default operation will
  1133. be assigned based on the template.
  1134. :type op: str or None
  1135. :param name: The human-readable name/description for the span. If not provided,
  1136. defaults to the function name. This provides more specific details about
  1137. what the span represents (e.g., "GET /api/users", "process_user_data").
  1138. :type name: str or None
  1139. :param attributes: A dictionary of key-value pairs to add as attributes to the span.
  1140. Attribute values must be strings, integers, floats, or booleans. These
  1141. attributes provide additional context about the span's execution.
  1142. :type attributes: dict[str, Any] or None
  1143. :param template: The type of span to create. This determines what kind of
  1144. span instrumentation and data collection will be applied. Use predefined
  1145. constants from :py:class:`sentry_sdk.consts.SPANTEMPLATE`.
  1146. The default is `SPANTEMPLATE.DEFAULT` which is the right choice for most
  1147. use cases.
  1148. :type template: :py:class:`sentry_sdk.consts.SPANTEMPLATE`
  1149. :returns: When used as ``@trace``, returns the decorated function. When used as
  1150. ``@trace(...)`` with parameters, returns a decorator function.
  1151. :rtype: Callable or decorator function
  1152. Example::
  1153. import sentry_sdk
  1154. from sentry_sdk.consts import OP, SPANTEMPLATE
  1155. # Simple usage with default values
  1156. @sentry_sdk.trace
  1157. def process_data():
  1158. # Function implementation
  1159. pass
  1160. # With custom parameters
  1161. @sentry_sdk.trace(
  1162. op=OP.DB_QUERY,
  1163. name="Get user data",
  1164. attributes={"postgres": True}
  1165. )
  1166. def make_db_query(sql):
  1167. # Function implementation
  1168. pass
  1169. # With a custom template
  1170. @sentry_sdk.trace(template=SPANTEMPLATE.AI_TOOL)
  1171. def calculate_interest_rate(amount, rate, years):
  1172. # Function implementation
  1173. pass
  1174. """
  1175. from sentry_sdk.tracing_utils import create_span_decorator
  1176. decorator = create_span_decorator(
  1177. op=op,
  1178. name=name,
  1179. attributes=attributes,
  1180. template=template,
  1181. )
  1182. if func:
  1183. return decorator(func)
  1184. else:
  1185. return decorator
  1186. # Circular imports
  1187. from sentry_sdk.tracing_utils import (
  1188. Baggage,
  1189. EnvironHeaders,
  1190. _generate_sample_rand,
  1191. extract_sentrytrace_data,
  1192. has_tracing_enabled,
  1193. maybe_create_breadcrumbs_from_span,
  1194. )