sentry-sdk 0.18.0__py2.py3-none-any.whl → 2.46.0__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. sentry_sdk/__init__.py +48 -6
  2. sentry_sdk/_compat.py +64 -56
  3. sentry_sdk/_init_implementation.py +84 -0
  4. sentry_sdk/_log_batcher.py +172 -0
  5. sentry_sdk/_lru_cache.py +47 -0
  6. sentry_sdk/_metrics_batcher.py +167 -0
  7. sentry_sdk/_queue.py +81 -19
  8. sentry_sdk/_types.py +311 -11
  9. sentry_sdk/_werkzeug.py +98 -0
  10. sentry_sdk/ai/__init__.py +7 -0
  11. sentry_sdk/ai/monitoring.py +137 -0
  12. sentry_sdk/ai/utils.py +144 -0
  13. sentry_sdk/api.py +409 -67
  14. sentry_sdk/attachments.py +75 -0
  15. sentry_sdk/client.py +849 -103
  16. sentry_sdk/consts.py +1389 -34
  17. sentry_sdk/crons/__init__.py +10 -0
  18. sentry_sdk/crons/api.py +62 -0
  19. sentry_sdk/crons/consts.py +4 -0
  20. sentry_sdk/crons/decorator.py +135 -0
  21. sentry_sdk/debug.py +12 -15
  22. sentry_sdk/envelope.py +112 -61
  23. sentry_sdk/feature_flags.py +71 -0
  24. sentry_sdk/hub.py +442 -386
  25. sentry_sdk/integrations/__init__.py +228 -58
  26. sentry_sdk/integrations/_asgi_common.py +108 -0
  27. sentry_sdk/integrations/_wsgi_common.py +131 -40
  28. sentry_sdk/integrations/aiohttp.py +221 -72
  29. sentry_sdk/integrations/anthropic.py +439 -0
  30. sentry_sdk/integrations/argv.py +4 -6
  31. sentry_sdk/integrations/ariadne.py +161 -0
  32. sentry_sdk/integrations/arq.py +247 -0
  33. sentry_sdk/integrations/asgi.py +237 -135
  34. sentry_sdk/integrations/asyncio.py +144 -0
  35. sentry_sdk/integrations/asyncpg.py +208 -0
  36. sentry_sdk/integrations/atexit.py +13 -18
  37. sentry_sdk/integrations/aws_lambda.py +233 -80
  38. sentry_sdk/integrations/beam.py +27 -35
  39. sentry_sdk/integrations/boto3.py +137 -0
  40. sentry_sdk/integrations/bottle.py +91 -69
  41. sentry_sdk/integrations/celery/__init__.py +529 -0
  42. sentry_sdk/integrations/celery/beat.py +293 -0
  43. sentry_sdk/integrations/celery/utils.py +43 -0
  44. sentry_sdk/integrations/chalice.py +35 -28
  45. sentry_sdk/integrations/clickhouse_driver.py +177 -0
  46. sentry_sdk/integrations/cloud_resource_context.py +280 -0
  47. sentry_sdk/integrations/cohere.py +274 -0
  48. sentry_sdk/integrations/dedupe.py +32 -8
  49. sentry_sdk/integrations/django/__init__.py +343 -89
  50. sentry_sdk/integrations/django/asgi.py +201 -22
  51. sentry_sdk/integrations/django/caching.py +204 -0
  52. sentry_sdk/integrations/django/middleware.py +80 -32
  53. sentry_sdk/integrations/django/signals_handlers.py +91 -0
  54. sentry_sdk/integrations/django/templates.py +69 -2
  55. sentry_sdk/integrations/django/transactions.py +39 -14
  56. sentry_sdk/integrations/django/views.py +69 -16
  57. sentry_sdk/integrations/dramatiq.py +226 -0
  58. sentry_sdk/integrations/excepthook.py +19 -13
  59. sentry_sdk/integrations/executing.py +5 -6
  60. sentry_sdk/integrations/falcon.py +128 -65
  61. sentry_sdk/integrations/fastapi.py +141 -0
  62. sentry_sdk/integrations/flask.py +114 -75
  63. sentry_sdk/integrations/gcp.py +67 -36
  64. sentry_sdk/integrations/gnu_backtrace.py +14 -22
  65. sentry_sdk/integrations/google_genai/__init__.py +301 -0
  66. sentry_sdk/integrations/google_genai/consts.py +16 -0
  67. sentry_sdk/integrations/google_genai/streaming.py +155 -0
  68. sentry_sdk/integrations/google_genai/utils.py +576 -0
  69. sentry_sdk/integrations/gql.py +162 -0
  70. sentry_sdk/integrations/graphene.py +151 -0
  71. sentry_sdk/integrations/grpc/__init__.py +168 -0
  72. sentry_sdk/integrations/grpc/aio/__init__.py +7 -0
  73. sentry_sdk/integrations/grpc/aio/client.py +95 -0
  74. sentry_sdk/integrations/grpc/aio/server.py +100 -0
  75. sentry_sdk/integrations/grpc/client.py +91 -0
  76. sentry_sdk/integrations/grpc/consts.py +1 -0
  77. sentry_sdk/integrations/grpc/server.py +66 -0
  78. sentry_sdk/integrations/httpx.py +178 -0
  79. sentry_sdk/integrations/huey.py +174 -0
  80. sentry_sdk/integrations/huggingface_hub.py +378 -0
  81. sentry_sdk/integrations/langchain.py +1132 -0
  82. sentry_sdk/integrations/langgraph.py +337 -0
  83. sentry_sdk/integrations/launchdarkly.py +61 -0
  84. sentry_sdk/integrations/litellm.py +287 -0
  85. sentry_sdk/integrations/litestar.py +315 -0
  86. sentry_sdk/integrations/logging.py +261 -85
  87. sentry_sdk/integrations/loguru.py +213 -0
  88. sentry_sdk/integrations/mcp.py +566 -0
  89. sentry_sdk/integrations/modules.py +6 -33
  90. sentry_sdk/integrations/openai.py +725 -0
  91. sentry_sdk/integrations/openai_agents/__init__.py +61 -0
  92. sentry_sdk/integrations/openai_agents/consts.py +1 -0
  93. sentry_sdk/integrations/openai_agents/patches/__init__.py +5 -0
  94. sentry_sdk/integrations/openai_agents/patches/agent_run.py +140 -0
  95. sentry_sdk/integrations/openai_agents/patches/error_tracing.py +77 -0
  96. sentry_sdk/integrations/openai_agents/patches/models.py +50 -0
  97. sentry_sdk/integrations/openai_agents/patches/runner.py +45 -0
  98. sentry_sdk/integrations/openai_agents/patches/tools.py +77 -0
  99. sentry_sdk/integrations/openai_agents/spans/__init__.py +5 -0
  100. sentry_sdk/integrations/openai_agents/spans/agent_workflow.py +21 -0
  101. sentry_sdk/integrations/openai_agents/spans/ai_client.py +42 -0
  102. sentry_sdk/integrations/openai_agents/spans/execute_tool.py +48 -0
  103. sentry_sdk/integrations/openai_agents/spans/handoff.py +19 -0
  104. sentry_sdk/integrations/openai_agents/spans/invoke_agent.py +86 -0
  105. sentry_sdk/integrations/openai_agents/utils.py +199 -0
  106. sentry_sdk/integrations/openfeature.py +35 -0
  107. sentry_sdk/integrations/opentelemetry/__init__.py +7 -0
  108. sentry_sdk/integrations/opentelemetry/consts.py +5 -0
  109. sentry_sdk/integrations/opentelemetry/integration.py +58 -0
  110. sentry_sdk/integrations/opentelemetry/propagator.py +117 -0
  111. sentry_sdk/integrations/opentelemetry/span_processor.py +391 -0
  112. sentry_sdk/integrations/otlp.py +82 -0
  113. sentry_sdk/integrations/pure_eval.py +20 -11
  114. sentry_sdk/integrations/pydantic_ai/__init__.py +47 -0
  115. sentry_sdk/integrations/pydantic_ai/consts.py +1 -0
  116. sentry_sdk/integrations/pydantic_ai/patches/__init__.py +4 -0
  117. sentry_sdk/integrations/pydantic_ai/patches/agent_run.py +215 -0
  118. sentry_sdk/integrations/pydantic_ai/patches/graph_nodes.py +110 -0
  119. sentry_sdk/integrations/pydantic_ai/patches/model_request.py +40 -0
  120. sentry_sdk/integrations/pydantic_ai/patches/tools.py +98 -0
  121. sentry_sdk/integrations/pydantic_ai/spans/__init__.py +3 -0
  122. sentry_sdk/integrations/pydantic_ai/spans/ai_client.py +246 -0
  123. sentry_sdk/integrations/pydantic_ai/spans/execute_tool.py +49 -0
  124. sentry_sdk/integrations/pydantic_ai/spans/invoke_agent.py +112 -0
  125. sentry_sdk/integrations/pydantic_ai/utils.py +223 -0
  126. sentry_sdk/integrations/pymongo.py +214 -0
  127. sentry_sdk/integrations/pyramid.py +71 -60
  128. sentry_sdk/integrations/quart.py +237 -0
  129. sentry_sdk/integrations/ray.py +165 -0
  130. sentry_sdk/integrations/redis/__init__.py +48 -0
  131. sentry_sdk/integrations/redis/_async_common.py +116 -0
  132. sentry_sdk/integrations/redis/_sync_common.py +119 -0
  133. sentry_sdk/integrations/redis/consts.py +19 -0
  134. sentry_sdk/integrations/redis/modules/__init__.py +0 -0
  135. sentry_sdk/integrations/redis/modules/caches.py +118 -0
  136. sentry_sdk/integrations/redis/modules/queries.py +65 -0
  137. sentry_sdk/integrations/redis/rb.py +32 -0
  138. sentry_sdk/integrations/redis/redis.py +69 -0
  139. sentry_sdk/integrations/redis/redis_cluster.py +107 -0
  140. sentry_sdk/integrations/redis/redis_py_cluster_legacy.py +50 -0
  141. sentry_sdk/integrations/redis/utils.py +148 -0
  142. sentry_sdk/integrations/rq.py +62 -52
  143. sentry_sdk/integrations/rust_tracing.py +284 -0
  144. sentry_sdk/integrations/sanic.py +248 -114
  145. sentry_sdk/integrations/serverless.py +13 -22
  146. sentry_sdk/integrations/socket.py +96 -0
  147. sentry_sdk/integrations/spark/spark_driver.py +115 -62
  148. sentry_sdk/integrations/spark/spark_worker.py +42 -50
  149. sentry_sdk/integrations/sqlalchemy.py +82 -37
  150. sentry_sdk/integrations/starlette.py +737 -0
  151. sentry_sdk/integrations/starlite.py +292 -0
  152. sentry_sdk/integrations/statsig.py +37 -0
  153. sentry_sdk/integrations/stdlib.py +100 -58
  154. sentry_sdk/integrations/strawberry.py +394 -0
  155. sentry_sdk/integrations/sys_exit.py +70 -0
  156. sentry_sdk/integrations/threading.py +142 -38
  157. sentry_sdk/integrations/tornado.py +68 -53
  158. sentry_sdk/integrations/trytond.py +15 -20
  159. sentry_sdk/integrations/typer.py +60 -0
  160. sentry_sdk/integrations/unleash.py +33 -0
  161. sentry_sdk/integrations/unraisablehook.py +53 -0
  162. sentry_sdk/integrations/wsgi.py +126 -125
  163. sentry_sdk/logger.py +96 -0
  164. sentry_sdk/metrics.py +81 -0
  165. sentry_sdk/monitor.py +120 -0
  166. sentry_sdk/profiler/__init__.py +49 -0
  167. sentry_sdk/profiler/continuous_profiler.py +730 -0
  168. sentry_sdk/profiler/transaction_profiler.py +839 -0
  169. sentry_sdk/profiler/utils.py +195 -0
  170. sentry_sdk/scope.py +1542 -112
  171. sentry_sdk/scrubber.py +177 -0
  172. sentry_sdk/serializer.py +152 -210
  173. sentry_sdk/session.py +177 -0
  174. sentry_sdk/sessions.py +202 -179
  175. sentry_sdk/spotlight.py +242 -0
  176. sentry_sdk/tracing.py +1202 -294
  177. sentry_sdk/tracing_utils.py +1236 -0
  178. sentry_sdk/transport.py +693 -189
  179. sentry_sdk/types.py +52 -0
  180. sentry_sdk/utils.py +1395 -228
  181. sentry_sdk/worker.py +30 -17
  182. sentry_sdk-2.46.0.dist-info/METADATA +268 -0
  183. sentry_sdk-2.46.0.dist-info/RECORD +189 -0
  184. {sentry_sdk-0.18.0.dist-info → sentry_sdk-2.46.0.dist-info}/WHEEL +1 -1
  185. sentry_sdk-2.46.0.dist-info/entry_points.txt +2 -0
  186. sentry_sdk-2.46.0.dist-info/licenses/LICENSE +21 -0
  187. sentry_sdk/_functools.py +0 -66
  188. sentry_sdk/integrations/celery.py +0 -275
  189. sentry_sdk/integrations/redis.py +0 -103
  190. sentry_sdk-0.18.0.dist-info/LICENSE +0 -9
  191. sentry_sdk-0.18.0.dist-info/METADATA +0 -66
  192. sentry_sdk-0.18.0.dist-info/RECORD +0 -65
  193. {sentry_sdk-0.18.0.dist-info → sentry_sdk-2.46.0.dist-info}/top_level.txt +0 -0
sentry_sdk/tracing.py CHANGED
@@ -1,75 +1,211 @@
1
- import re
2
1
  import uuid
3
- import contextlib
4
- import time
5
-
6
- from datetime import datetime, timedelta
2
+ import warnings
3
+ from datetime import datetime, timedelta, timezone
4
+ from enum import Enum
7
5
 
8
6
  import sentry_sdk
7
+ from sentry_sdk.consts import INSTRUMENTER, SPANSTATUS, SPANDATA, 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
+ )
9
17
 
10
- from sentry_sdk.utils import capture_internal_exceptions, logger, to_string
11
- from sentry_sdk._compat import PY2
12
- from sentry_sdk._types import MYPY
13
-
14
- if PY2:
15
- from collections import Mapping
16
- else:
17
- from collections.abc import Mapping
18
+ from typing import TYPE_CHECKING
18
19
 
19
- if MYPY:
20
- import typing
21
20
 
22
- from typing import Generator
23
- from typing import Optional
21
+ if TYPE_CHECKING:
22
+ from collections.abc import Callable, Mapping, MutableMapping
24
23
  from typing import Any
25
24
  from typing import Dict
25
+ from typing import Iterator
26
26
  from typing import List
27
+ from typing import Optional
28
+ from typing import overload
29
+ from typing import ParamSpec
27
30
  from typing import Tuple
31
+ from typing import Union
32
+ from typing import TypeVar
33
+ from typing import Set
34
+
35
+ from typing_extensions import TypedDict, Unpack
36
+
37
+ P = ParamSpec("P")
38
+ R = TypeVar("R")
39
+
40
+ from sentry_sdk.profiler.continuous_profiler import ContinuousProfile
41
+ from sentry_sdk.profiler.transaction_profiler import Profile
42
+ from sentry_sdk._types import (
43
+ Event,
44
+ MeasurementUnit,
45
+ SamplingContext,
46
+ MeasurementValue,
47
+ )
28
48
 
29
- _traceparent_header_format_re = re.compile(
30
- "^[ \t]*" # whitespace
31
- "([0-9a-f]{32})?" # trace_id
32
- "-?([0-9a-f]{16})?" # span_id
33
- "-?([01])?" # sampled
34
- "[ \t]*$" # whitespace
35
- )
49
+ class SpanKwargs(TypedDict, total=False):
50
+ trace_id: str
51
+ """
52
+ The trace ID of the root span. If this new span is to be the root span,
53
+ omit this parameter, and a new trace ID will be generated.
54
+ """
36
55
 
56
+ span_id: str
57
+ """The span ID of this span. If omitted, a new span ID will be generated."""
37
58
 
38
- class EnvironHeaders(Mapping): # type: ignore
39
- def __init__(
40
- self,
41
- environ, # type: typing.Mapping[str, str]
42
- prefix="HTTP_", # type: str
43
- ):
44
- # type: (...) -> None
45
- self.environ = environ
46
- self.prefix = prefix
59
+ parent_span_id: str
60
+ """The span ID of the parent span, if applicable."""
61
+
62
+ same_process_as_parent: bool
63
+ """Whether this span is in the same process as the parent span."""
64
+
65
+ sampled: bool
66
+ """
67
+ Whether the span should be sampled. Overrides the default sampling decision
68
+ for this span when provided.
69
+ """
47
70
 
48
- def __getitem__(self, key):
49
- # type: (str) -> Optional[Any]
50
- return self.environ[self.prefix + key.replace("-", "_").upper()]
71
+ op: str
72
+ """
73
+ The span's operation. A list of recommended values is available here:
74
+ https://develop.sentry.dev/sdk/performance/span-operations/
75
+ """
51
76
 
52
- def __len__(self):
53
- # type: () -> int
54
- return sum(1 for _ in iter(self))
77
+ description: str
78
+ """A description of what operation is being performed within the span. This argument is DEPRECATED. Please use the `name` parameter, instead."""
55
79
 
56
- def __iter__(self):
57
- # type: () -> Generator[str, None, None]
58
- for k in self.environ:
59
- if not isinstance(k, str):
60
- continue
80
+ hub: Optional["sentry_sdk.Hub"]
81
+ """The hub to use for this span. This argument is DEPRECATED. Please use the `scope` parameter, instead."""
61
82
 
62
- k = k.replace("-", "_").upper()
63
- if not k.startswith(self.prefix):
64
- continue
83
+ status: str
84
+ """The span's status. Possible values are listed at https://develop.sentry.dev/sdk/event-payloads/span/"""
65
85
 
66
- yield k[len(self.prefix) :]
86
+ containing_transaction: Optional["Transaction"]
87
+ """The transaction that this span belongs to."""
88
+
89
+ start_timestamp: Optional[Union[datetime, float]]
90
+ """
91
+ The timestamp when the span started. If omitted, the current time
92
+ will be used.
93
+ """
94
+
95
+ scope: "sentry_sdk.Scope"
96
+ """The scope to use for this span. If not provided, we use the current scope."""
97
+
98
+ origin: str
99
+ """
100
+ The origin of the span.
101
+ See https://develop.sentry.dev/sdk/performance/trace-origin/
102
+ Default "manual".
103
+ """
104
+
105
+ name: str
106
+ """A string describing what operation is being performed within the span/transaction."""
107
+
108
+ class TransactionKwargs(SpanKwargs, total=False):
109
+ source: str
110
+ """
111
+ A string describing the source of the transaction name. This will be used to determine the transaction's type.
112
+ See https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations for more information.
113
+ Default "custom".
114
+ """
115
+
116
+ parent_sampled: bool
117
+ """Whether the parent transaction was sampled. If True this transaction will be kept, if False it will be discarded."""
118
+
119
+ baggage: "Baggage"
120
+ """The W3C baggage header value. (see https://www.w3.org/TR/baggage/)"""
121
+
122
+ ProfileContext = TypedDict(
123
+ "ProfileContext",
124
+ {
125
+ "profiler_id": str,
126
+ },
127
+ )
128
+
129
+ BAGGAGE_HEADER_NAME = "baggage"
130
+ SENTRY_TRACE_HEADER_NAME = "sentry-trace"
131
+
132
+
133
+ # Transaction source
134
+ # see https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations
135
+ class TransactionSource(str, Enum):
136
+ COMPONENT = "component"
137
+ CUSTOM = "custom"
138
+ ROUTE = "route"
139
+ TASK = "task"
140
+ URL = "url"
141
+ VIEW = "view"
142
+
143
+ def __str__(self):
144
+ # type: () -> str
145
+ return self.value
146
+
147
+
148
+ # These are typically high cardinality and the server hates them
149
+ LOW_QUALITY_TRANSACTION_SOURCES = [
150
+ TransactionSource.URL,
151
+ ]
152
+
153
+ SOURCE_FOR_STYLE = {
154
+ "endpoint": TransactionSource.COMPONENT,
155
+ "function_name": TransactionSource.COMPONENT,
156
+ "handler_name": TransactionSource.COMPONENT,
157
+ "method_and_path_pattern": TransactionSource.ROUTE,
158
+ "path": TransactionSource.URL,
159
+ "route_name": TransactionSource.COMPONENT,
160
+ "route_pattern": TransactionSource.ROUTE,
161
+ "uri_template": TransactionSource.ROUTE,
162
+ "url": TransactionSource.ROUTE,
163
+ }
164
+
165
+
166
+ def get_span_status_from_http_code(http_status_code):
167
+ # type: (int) -> str
168
+ """
169
+ Returns the Sentry status corresponding to the given HTTP status code.
170
+
171
+ See: https://develop.sentry.dev/sdk/event-payloads/contexts/#trace-context
172
+ """
173
+ if http_status_code < 400:
174
+ return SPANSTATUS.OK
175
+
176
+ elif 400 <= http_status_code < 500:
177
+ if http_status_code == 403:
178
+ return SPANSTATUS.PERMISSION_DENIED
179
+ elif http_status_code == 404:
180
+ return SPANSTATUS.NOT_FOUND
181
+ elif http_status_code == 429:
182
+ return SPANSTATUS.RESOURCE_EXHAUSTED
183
+ elif http_status_code == 413:
184
+ return SPANSTATUS.FAILED_PRECONDITION
185
+ elif http_status_code == 401:
186
+ return SPANSTATUS.UNAUTHENTICATED
187
+ elif http_status_code == 409:
188
+ return SPANSTATUS.ALREADY_EXISTS
189
+ else:
190
+ return SPANSTATUS.INVALID_ARGUMENT
191
+
192
+ elif 500 <= http_status_code < 600:
193
+ if http_status_code == 504:
194
+ return SPANSTATUS.DEADLINE_EXCEEDED
195
+ elif http_status_code == 501:
196
+ return SPANSTATUS.UNIMPLEMENTED
197
+ elif http_status_code == 503:
198
+ return SPANSTATUS.UNAVAILABLE
199
+ else:
200
+ return SPANSTATUS.INTERNAL_ERROR
67
201
 
202
+ return SPANSTATUS.UNKNOWN_ERROR
68
203
 
69
- class _SpanRecorder(object):
204
+
205
+ class _SpanRecorder:
70
206
  """Limits the number of spans recorded in a transaction."""
71
207
 
72
- __slots__ = ("maxlen", "spans")
208
+ __slots__ = ("maxlen", "spans", "dropped_spans")
73
209
 
74
210
  def __init__(self, maxlen):
75
211
  # type: (int) -> None
@@ -80,26 +216,58 @@ class _SpanRecorder(object):
80
216
  # limits: either transaction+spans or only child spans.
81
217
  self.maxlen = maxlen - 1
82
218
  self.spans = [] # type: List[Span]
219
+ self.dropped_spans = 0 # type: int
83
220
 
84
221
  def add(self, span):
85
222
  # type: (Span) -> None
86
223
  if len(self.spans) > self.maxlen:
87
224
  span._span_recorder = None
225
+ self.dropped_spans += 1
88
226
  else:
89
227
  self.spans.append(span)
90
228
 
91
229
 
92
- class Span(object):
230
+ class Span:
231
+ """A span holds timing information of a block of code.
232
+ Spans can have multiple child spans thus forming a span tree.
233
+
234
+ :param trace_id: The trace ID of the root span. If this new span is to be the root span,
235
+ omit this parameter, and a new trace ID will be generated.
236
+ :param span_id: The span ID of this span. If omitted, a new span ID will be generated.
237
+ :param parent_span_id: The span ID of the parent span, if applicable.
238
+ :param same_process_as_parent: Whether this span is in the same process as the parent span.
239
+ :param sampled: Whether the span should be sampled. Overrides the default sampling decision
240
+ for this span when provided.
241
+ :param op: The span's operation. A list of recommended values is available here:
242
+ https://develop.sentry.dev/sdk/performance/span-operations/
243
+ :param description: A description of what operation is being performed within the span.
244
+
245
+ .. deprecated:: 2.15.0
246
+ Please use the `name` parameter, instead.
247
+ :param name: A string describing what operation is being performed within the span.
248
+ :param hub: The hub to use for this span.
249
+
250
+ .. deprecated:: 2.0.0
251
+ Please use the `scope` parameter, instead.
252
+ :param status: The span's status. Possible values are listed at
253
+ https://develop.sentry.dev/sdk/event-payloads/span/
254
+ :param containing_transaction: The transaction that this span belongs to.
255
+ :param start_timestamp: The timestamp when the span started. If omitted, the current time
256
+ will be used.
257
+ :param scope: The scope to use for this span. If not provided, we use the current scope.
258
+ """
259
+
93
260
  __slots__ = (
94
- "trace_id",
95
- "span_id",
261
+ "_trace_id",
262
+ "_span_id",
96
263
  "parent_span_id",
97
264
  "same_process_as_parent",
98
265
  "sampled",
99
266
  "op",
100
267
  "description",
268
+ "_measurements",
101
269
  "start_timestamp",
102
- "_start_timestamp_monotonic",
270
+ "_start_timestamp_monotonic_ns",
103
271
  "status",
104
272
  "timestamp",
105
273
  "_tags",
@@ -107,17 +275,14 @@ class Span(object):
107
275
  "_span_recorder",
108
276
  "hub",
109
277
  "_context_manager_state",
278
+ "_containing_transaction",
279
+ "scope",
280
+ "origin",
281
+ "name",
282
+ "_flags",
283
+ "_flags_capacity",
110
284
  )
111
285
 
112
- def __new__(cls, **kwargs):
113
- # type: (**Any) -> Any
114
- # TODO: consider removing this in a future release.
115
- # This is for backwards compatibility with releases before Transaction
116
- # existed, to allow for a smoother transition.
117
- if "transaction" in kwargs:
118
- return object.__new__(Transaction)
119
- return object.__new__(cls)
120
-
121
286
  def __init__(
122
287
  self,
123
288
  trace_id=None, # type: Optional[str]
@@ -127,29 +292,51 @@ class Span(object):
127
292
  sampled=None, # type: Optional[bool]
128
293
  op=None, # type: Optional[str]
129
294
  description=None, # type: Optional[str]
130
- hub=None, # type: Optional[sentry_sdk.Hub]
295
+ hub=None, # type: Optional[sentry_sdk.Hub] # deprecated
131
296
  status=None, # type: Optional[str]
132
- transaction=None, # type: Optional[str] # deprecated
297
+ containing_transaction=None, # type: Optional[Transaction]
298
+ start_timestamp=None, # type: Optional[Union[datetime, float]]
299
+ scope=None, # type: Optional[sentry_sdk.Scope]
300
+ origin="manual", # type: str
301
+ name=None, # type: Optional[str]
133
302
  ):
134
303
  # type: (...) -> None
135
- self.trace_id = trace_id or uuid.uuid4().hex
136
- self.span_id = span_id or uuid.uuid4().hex[16:]
304
+ self._trace_id = trace_id
305
+ self._span_id = span_id
137
306
  self.parent_span_id = parent_span_id
138
307
  self.same_process_as_parent = same_process_as_parent
139
308
  self.sampled = sampled
140
309
  self.op = op
141
- self.description = description
310
+ self.description = name or description
142
311
  self.status = status
143
- self.hub = hub
144
- self._tags = {} # type: Dict[str, str]
312
+ self.hub = hub # backwards compatibility
313
+ self.scope = scope
314
+ self.origin = origin
315
+ self._measurements = {} # type: Dict[str, MeasurementValue]
316
+ self._tags = {} # type: MutableMapping[str, str]
145
317
  self._data = {} # type: Dict[str, Any]
146
- self.start_timestamp = datetime.utcnow()
147
- try:
148
- # TODO: For Python 3.7+, we could use a clock with ns resolution:
149
- # self._start_timestamp_monotonic = time.perf_counter_ns()
318
+ self._containing_transaction = containing_transaction
319
+ self._flags = {} # type: Dict[str, bool]
320
+ self._flags_capacity = 10
321
+
322
+ if hub is not None:
323
+ warnings.warn(
324
+ "The `hub` parameter is deprecated. Please use `scope` instead.",
325
+ DeprecationWarning,
326
+ stacklevel=2,
327
+ )
328
+
329
+ self.scope = self.scope or hub.scope
150
330
 
151
- # Python 3.3+
152
- self._start_timestamp_monotonic = time.perf_counter()
331
+ if start_timestamp is None:
332
+ start_timestamp = datetime.now(timezone.utc)
333
+ elif isinstance(start_timestamp, float):
334
+ start_timestamp = datetime.fromtimestamp(start_timestamp, timezone.utc)
335
+ self.start_timestamp = start_timestamp
336
+ try:
337
+ # profiling depends on this value and requires that
338
+ # it is measured in nanoseconds
339
+ self._start_timestamp_monotonic_ns = nanosecond_time()
153
340
  except AttributeError:
154
341
  pass
155
342
 
@@ -158,75 +345,151 @@ class Span(object):
158
345
 
159
346
  self._span_recorder = None # type: Optional[_SpanRecorder]
160
347
 
348
+ self.update_active_thread()
349
+ self.set_profiler_id(get_profiler_id())
350
+
351
+ # TODO this should really live on the Transaction class rather than the Span
352
+ # class
161
353
  def init_span_recorder(self, maxlen):
162
354
  # type: (int) -> None
163
355
  if self._span_recorder is None:
164
356
  self._span_recorder = _SpanRecorder(maxlen)
165
- self._span_recorder.add(self)
357
+
358
+ @property
359
+ def trace_id(self):
360
+ # type: () -> str
361
+ if not self._trace_id:
362
+ self._trace_id = uuid.uuid4().hex
363
+
364
+ return self._trace_id
365
+
366
+ @trace_id.setter
367
+ def trace_id(self, value):
368
+ # type: (str) -> None
369
+ self._trace_id = value
370
+
371
+ @property
372
+ def span_id(self):
373
+ # type: () -> str
374
+ if not self._span_id:
375
+ self._span_id = uuid.uuid4().hex[16:]
376
+
377
+ return self._span_id
378
+
379
+ @span_id.setter
380
+ def span_id(self, value):
381
+ # type: (str) -> None
382
+ self._span_id = value
166
383
 
167
384
  def __repr__(self):
168
385
  # type: () -> str
169
- return "<%s(trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r)>" % (
170
- self.__class__.__name__,
171
- self.trace_id,
172
- self.span_id,
173
- self.parent_span_id,
174
- self.sampled,
386
+ return (
387
+ "<%s(op=%r, description:%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r, origin=%r)>"
388
+ % (
389
+ self.__class__.__name__,
390
+ self.op,
391
+ self.description,
392
+ self.trace_id,
393
+ self.span_id,
394
+ self.parent_span_id,
395
+ self.sampled,
396
+ self.origin,
397
+ )
175
398
  )
176
399
 
177
400
  def __enter__(self):
178
401
  # type: () -> Span
179
- hub = self.hub or sentry_sdk.Hub.current
180
-
181
- _, scope = hub._stack[-1]
402
+ scope = self.scope or sentry_sdk.get_current_scope()
182
403
  old_span = scope.span
183
404
  scope.span = self
184
- self._context_manager_state = (hub, scope, old_span)
405
+ self._context_manager_state = (scope, old_span)
185
406
  return self
186
407
 
187
408
  def __exit__(self, ty, value, tb):
188
409
  # type: (Optional[Any], Optional[Any], Optional[Any]) -> None
189
- if value is not None:
190
- self.set_status("internal_error")
191
-
192
- hub, scope, old_span = self._context_manager_state
193
- del self._context_manager_state
194
-
195
- self.finish(hub)
196
- scope.span = old_span
197
-
198
- def start_child(self, **kwargs):
199
- # type: (**Any) -> Span
410
+ if value is not None and should_be_treated_as_error(ty, value):
411
+ if self.status != SPANSTATUS.ERROR:
412
+ self.set_status(SPANSTATUS.INTERNAL_ERROR)
413
+
414
+ with capture_internal_exceptions():
415
+ scope, old_span = self._context_manager_state
416
+ del self._context_manager_state
417
+ self.finish(scope)
418
+ scope.span = old_span
419
+
420
+ @property
421
+ def containing_transaction(self):
422
+ # type: () -> Optional[Transaction]
423
+ """The ``Transaction`` that this span belongs to.
424
+ The ``Transaction`` is the root of the span tree,
425
+ so one could also think of this ``Transaction`` as the "root span"."""
426
+
427
+ # this is a getter rather than a regular attribute so that transactions
428
+ # can return `self` here instead (as a way to prevent them circularly
429
+ # referencing themselves)
430
+ return self._containing_transaction
431
+
432
+ def start_child(self, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
433
+ # type: (str, **Any) -> Span
200
434
  """
201
435
  Start a sub-span from the current span or transaction.
202
436
 
203
- Takes the same arguments as the initializer of :py:class:`Span`. No
204
- attributes other than the sample rate are inherited.
437
+ Takes the same arguments as the initializer of :py:class:`Span`. The
438
+ trace id, sampling decision, transaction pointer, and span recorder are
439
+ inherited from the current span/transaction.
440
+
441
+ The instrumenter parameter is deprecated for user code, and it will
442
+ be removed in the next major version. Going forward, it should only
443
+ be used by the SDK itself.
205
444
  """
445
+ if kwargs.get("description") is not None:
446
+ warnings.warn(
447
+ "The `description` parameter is deprecated. Please use `name` instead.",
448
+ DeprecationWarning,
449
+ stacklevel=2,
450
+ )
451
+
452
+ configuration_instrumenter = sentry_sdk.get_client().options["instrumenter"]
453
+
454
+ if instrumenter != configuration_instrumenter:
455
+ return NoOpSpan()
456
+
206
457
  kwargs.setdefault("sampled", self.sampled)
207
458
 
208
- rv = Span(
209
- trace_id=self.trace_id, span_id=None, parent_span_id=self.span_id, **kwargs
459
+ child = Span(
460
+ trace_id=self.trace_id,
461
+ parent_span_id=self.span_id,
462
+ containing_transaction=self.containing_transaction,
463
+ **kwargs,
210
464
  )
211
465
 
212
- rv._span_recorder = recorder = self._span_recorder
213
- if recorder:
214
- recorder.add(rv)
215
- return rv
466
+ span_recorder = (
467
+ self.containing_transaction and self.containing_transaction._span_recorder
468
+ )
469
+ if span_recorder:
470
+ span_recorder.add(child)
216
471
 
217
- def new_span(self, **kwargs):
218
- # type: (**Any) -> Span
219
- """Deprecated: use start_child instead."""
220
- logger.warning("Deprecated: use Span.start_child instead of Span.new_span.")
221
- return self.start_child(**kwargs)
472
+ return child
222
473
 
223
474
  @classmethod
224
475
  def continue_from_environ(
225
476
  cls,
226
- environ, # type: typing.Mapping[str, str]
227
- **kwargs # type: Any
477
+ environ, # type: Mapping[str, str]
478
+ **kwargs, # type: Any
228
479
  ):
229
480
  # type: (...) -> Transaction
481
+ """
482
+ Create a Transaction with the given params, then add in data pulled from
483
+ the ``sentry-trace`` and ``baggage`` headers from the environ (if any)
484
+ before returning the Transaction.
485
+
486
+ This is different from :py:meth:`~sentry_sdk.tracing.Span.continue_from_headers`
487
+ in that it assumes header names in the form ``HTTP_HEADER_NAME`` -
488
+ such as you would get from a WSGI/ASGI environ -
489
+ rather than the form ``header-name``.
490
+
491
+ :param environ: The ASGI/WSGI environ to pull information from.
492
+ """
230
493
  if cls is Span:
231
494
  logger.warning(
232
495
  "Deprecated: use Transaction.continue_from_environ "
@@ -237,72 +500,119 @@ class Span(object):
237
500
  @classmethod
238
501
  def continue_from_headers(
239
502
  cls,
240
- headers, # type: typing.Mapping[str, str]
241
- **kwargs # type: Any
503
+ headers, # type: Mapping[str, str]
504
+ *,
505
+ _sample_rand=None, # type: Optional[str]
506
+ **kwargs, # type: Any
242
507
  ):
243
508
  # type: (...) -> Transaction
509
+ """
510
+ Create a transaction with the given params (including any data pulled from
511
+ the ``sentry-trace`` and ``baggage`` headers).
512
+
513
+ :param headers: The dictionary with the HTTP headers to pull information from.
514
+ :param _sample_rand: If provided, we override the sample_rand value from the
515
+ incoming headers with this value. (internal use only)
516
+ """
517
+ # TODO move this to the Transaction class
244
518
  if cls is Span:
245
519
  logger.warning(
246
520
  "Deprecated: use Transaction.continue_from_headers "
247
521
  "instead of Span.continue_from_headers."
248
522
  )
249
- parent = Transaction.from_traceparent(headers.get("sentry-trace"), **kwargs)
250
- if parent is None:
251
- parent = Transaction(**kwargs)
252
- parent.same_process_as_parent = False
253
- return parent
523
+
524
+ # TODO-neel move away from this kwargs stuff, it's confusing and opaque
525
+ # make more explicit
526
+ baggage = Baggage.from_incoming_header(
527
+ headers.get(BAGGAGE_HEADER_NAME), _sample_rand=_sample_rand
528
+ )
529
+ kwargs.update({BAGGAGE_HEADER_NAME: baggage})
530
+
531
+ sentrytrace_kwargs = extract_sentrytrace_data(
532
+ headers.get(SENTRY_TRACE_HEADER_NAME)
533
+ )
534
+
535
+ if sentrytrace_kwargs is not None:
536
+ kwargs.update(sentrytrace_kwargs)
537
+
538
+ # If there's an incoming sentry-trace but no incoming baggage header,
539
+ # for instance in traces coming from older SDKs,
540
+ # baggage will be empty and immutable and won't be populated as head SDK.
541
+ baggage.freeze()
542
+
543
+ transaction = Transaction(**kwargs)
544
+ transaction.same_process_as_parent = False
545
+
546
+ return transaction
254
547
 
255
548
  def iter_headers(self):
256
- # type: () -> Generator[Tuple[str, str], None, None]
257
- yield "sentry-trace", self.to_traceparent()
549
+ # type: () -> Iterator[Tuple[str, str]]
550
+ """
551
+ Creates a generator which returns the span's ``sentry-trace`` and ``baggage`` headers.
552
+ If the span's containing transaction doesn't yet have a ``baggage`` value,
553
+ this will cause one to be generated and stored.
554
+ """
555
+ if not self.containing_transaction:
556
+ # Do not propagate headers if there is no containing transaction. Otherwise, this
557
+ # span ends up being the root span of a new trace, and since it does not get sent
558
+ # to Sentry, the trace will be missing a root transaction. The dynamic sampling
559
+ # context will also be missing, breaking dynamic sampling & traces.
560
+ return
561
+
562
+ yield SENTRY_TRACE_HEADER_NAME, self.to_traceparent()
563
+
564
+ baggage = self.containing_transaction.get_baggage().serialize()
565
+ if baggage:
566
+ yield BAGGAGE_HEADER_NAME, baggage
258
567
 
259
568
  @classmethod
260
569
  def from_traceparent(
261
570
  cls,
262
571
  traceparent, # type: Optional[str]
263
- **kwargs # type: Any
572
+ **kwargs, # type: Any
264
573
  ):
265
574
  # type: (...) -> Optional[Transaction]
266
- if cls is Span:
267
- logger.warning(
268
- "Deprecated: use Transaction.from_traceparent "
269
- "instead of Span.from_traceparent."
270
- )
271
-
272
- if not traceparent:
273
- return None
575
+ """
576
+ DEPRECATED: Use :py:meth:`sentry_sdk.tracing.Span.continue_from_headers`.
274
577
 
275
- if traceparent.startswith("00-") and traceparent.endswith("-00"):
276
- traceparent = traceparent[3:-3]
578
+ Create a ``Transaction`` with the given params, then add in data pulled from
579
+ the given ``sentry-trace`` header value before returning the ``Transaction``.
580
+ """
581
+ logger.warning(
582
+ "Deprecated: Use Transaction.continue_from_headers(headers, **kwargs) "
583
+ "instead of from_traceparent(traceparent, **kwargs)"
584
+ )
277
585
 
278
- match = _traceparent_header_format_re.match(str(traceparent))
279
- if match is None:
586
+ if not traceparent:
280
587
  return None
281
588
 
282
- trace_id, span_id, sampled_str = match.groups()
283
-
284
- if trace_id is not None:
285
- trace_id = "{:032x}".format(int(trace_id, 16))
286
- if span_id is not None:
287
- span_id = "{:016x}".format(int(span_id, 16))
288
-
289
- if sampled_str:
290
- sampled = sampled_str != "0" # type: Optional[bool]
291
- else:
292
- sampled = None
293
-
294
- return Transaction(
295
- trace_id=trace_id, parent_span_id=span_id, sampled=sampled, **kwargs
589
+ return cls.continue_from_headers(
590
+ {SENTRY_TRACE_HEADER_NAME: traceparent}, **kwargs
296
591
  )
297
592
 
298
593
  def to_traceparent(self):
299
594
  # type: () -> str
300
- sampled = ""
301
595
  if self.sampled is True:
302
596
  sampled = "1"
303
- if self.sampled is False:
597
+ elif self.sampled is False:
304
598
  sampled = "0"
305
- return "%s-%s-%s" % (self.trace_id, self.span_id, sampled)
599
+ else:
600
+ sampled = None
601
+
602
+ traceparent = "%s-%s" % (self.trace_id, self.span_id)
603
+ if sampled is not None:
604
+ traceparent += "-%s" % (sampled,)
605
+
606
+ return traceparent
607
+
608
+ def to_baggage(self):
609
+ # type: () -> Optional[Baggage]
610
+ """Returns the :py:class:`~sentry_sdk.tracing_utils.Baggage`
611
+ associated with this ``Span``, if any. (Taken from the root of the span tree.)
612
+ """
613
+ if self.containing_transaction:
614
+ return self.containing_transaction.get_baggage()
615
+ return None
306
616
 
307
617
  def set_tag(self, key, value):
308
618
  # type: (str, Any) -> None
@@ -312,68 +622,101 @@ class Span(object):
312
622
  # type: (str, Any) -> None
313
623
  self._data[key] = value
314
624
 
625
+ def update_data(self, data):
626
+ # type: (Dict[str, Any]) -> None
627
+ self._data.update(data)
628
+
629
+ def set_flag(self, flag, result):
630
+ # type: (str, bool) -> None
631
+ if len(self._flags) < self._flags_capacity:
632
+ self._flags[flag] = result
633
+
315
634
  def set_status(self, value):
316
635
  # type: (str) -> None
317
636
  self.status = value
318
637
 
638
+ def set_measurement(self, name, value, unit=""):
639
+ # type: (str, float, MeasurementUnit) -> None
640
+ """
641
+ .. deprecated:: 2.28.0
642
+ This function is deprecated and will be removed in the next major release.
643
+ """
644
+
645
+ warnings.warn(
646
+ "`set_measurement()` is deprecated and will be removed in the next major version. Please use `set_data()` instead.",
647
+ DeprecationWarning,
648
+ stacklevel=2,
649
+ )
650
+ self._measurements[name] = {"value": value, "unit": unit}
651
+
652
+ def set_thread(self, thread_id, thread_name):
653
+ # type: (Optional[int], Optional[str]) -> None
654
+
655
+ if thread_id is not None:
656
+ self.set_data(SPANDATA.THREAD_ID, str(thread_id))
657
+
658
+ if thread_name is not None:
659
+ self.set_data(SPANDATA.THREAD_NAME, thread_name)
660
+
661
+ def set_profiler_id(self, profiler_id):
662
+ # type: (Optional[str]) -> None
663
+ if profiler_id is not None:
664
+ self.set_data(SPANDATA.PROFILER_ID, profiler_id)
665
+
319
666
  def set_http_status(self, http_status):
320
667
  # type: (int) -> None
321
- self.set_tag("http.status_code", str(http_status))
322
-
323
- if http_status < 400:
324
- self.set_status("ok")
325
- elif 400 <= http_status < 500:
326
- if http_status == 403:
327
- self.set_status("permission_denied")
328
- elif http_status == 404:
329
- self.set_status("not_found")
330
- elif http_status == 429:
331
- self.set_status("resource_exhausted")
332
- elif http_status == 413:
333
- self.set_status("failed_precondition")
334
- elif http_status == 401:
335
- self.set_status("unauthenticated")
336
- elif http_status == 409:
337
- self.set_status("already_exists")
338
- else:
339
- self.set_status("invalid_argument")
340
- elif 500 <= http_status < 600:
341
- if http_status == 504:
342
- self.set_status("deadline_exceeded")
343
- elif http_status == 501:
344
- self.set_status("unimplemented")
345
- elif http_status == 503:
346
- self.set_status("unavailable")
347
- else:
348
- self.set_status("internal_error")
349
- else:
350
- self.set_status("unknown_error")
668
+ self.set_tag(
669
+ "http.status_code", str(http_status)
670
+ ) # we keep this for backwards compatibility
671
+ self.set_data(SPANDATA.HTTP_STATUS_CODE, http_status)
672
+ self.set_status(get_span_status_from_http_code(http_status))
351
673
 
352
674
  def is_success(self):
353
675
  # type: () -> bool
354
676
  return self.status == "ok"
355
677
 
356
- def finish(self, hub=None):
357
- # type: (Optional[sentry_sdk.Hub]) -> Optional[str]
358
- # XXX: would be type: (Optional[sentry_sdk.Hub]) -> None, but that leads
359
- # to incompatible return types for Span.finish and Transaction.finish.
678
+ def finish(self, scope=None, end_timestamp=None):
679
+ # type: (Optional[sentry_sdk.Scope], Optional[Union[float, datetime]]) -> Optional[str]
680
+ """
681
+ Sets the end timestamp of the span.
682
+
683
+ Additionally it also creates a breadcrumb from the span,
684
+ if the span represents a database or HTTP request.
685
+
686
+ :param scope: The scope to use for this transaction.
687
+ If not provided, the current scope will be used.
688
+ :param end_timestamp: Optional timestamp that should
689
+ be used as timestamp instead of the current time.
690
+
691
+ :return: Always ``None``. The type is ``Optional[str]`` to match
692
+ the return value of :py:meth:`sentry_sdk.tracing.Transaction.finish`.
693
+ """
360
694
  if self.timestamp is not None:
361
695
  # This span is already finished, ignore.
362
696
  return None
363
697
 
364
- hub = hub or self.hub or sentry_sdk.Hub.current
365
-
366
698
  try:
367
- duration_seconds = time.perf_counter() - self._start_timestamp_monotonic
368
- self.timestamp = self.start_timestamp + timedelta(seconds=duration_seconds)
699
+ if end_timestamp:
700
+ if isinstance(end_timestamp, float):
701
+ end_timestamp = datetime.fromtimestamp(end_timestamp, timezone.utc)
702
+ self.timestamp = end_timestamp
703
+ else:
704
+ elapsed = nanosecond_time() - self._start_timestamp_monotonic_ns
705
+ self.timestamp = self.start_timestamp + timedelta(
706
+ microseconds=elapsed / 1000
707
+ )
369
708
  except AttributeError:
370
- self.timestamp = datetime.utcnow()
709
+ self.timestamp = datetime.now(timezone.utc)
710
+
711
+ scope = scope or sentry_sdk.get_current_scope()
712
+ maybe_create_breadcrumbs_from_span(scope, self)
371
713
 
372
- _maybe_create_breadcrumbs_from_span(hub, self)
373
714
  return None
374
715
 
375
- def to_json(self, client):
376
- # type: (Optional[sentry_sdk.Client]) -> Dict[str, Any]
716
+ def to_json(self):
717
+ # type: () -> Dict[str, Any]
718
+ """Returns a JSON-compatible representation of the span."""
719
+
377
720
  rv = {
378
721
  "trace_id": self.trace_id,
379
722
  "span_id": self.span_id,
@@ -383,16 +726,22 @@ class Span(object):
383
726
  "description": self.description,
384
727
  "start_timestamp": self.start_timestamp,
385
728
  "timestamp": self.timestamp,
729
+ "origin": self.origin,
386
730
  } # type: Dict[str, Any]
387
731
 
388
732
  if self.status:
389
733
  self._tags["status"] = self.status
390
734
 
735
+ if len(self._measurements) > 0:
736
+ rv["measurements"] = self._measurements
737
+
391
738
  tags = self._tags
392
739
  if tags:
393
740
  rv["tags"] = tags
394
741
 
395
- data = self._data
742
+ data = {}
743
+ data.update(self._flags)
744
+ data.update(self._data)
396
745
  if data:
397
746
  rv["data"] = data
398
747
 
@@ -406,62 +755,273 @@ class Span(object):
406
755
  "parent_span_id": self.parent_span_id,
407
756
  "op": self.op,
408
757
  "description": self.description,
409
- }
758
+ "origin": self.origin,
759
+ } # type: Dict[str, Any]
410
760
  if self.status:
411
761
  rv["status"] = self.status
412
762
 
763
+ if self.containing_transaction:
764
+ rv["dynamic_sampling_context"] = (
765
+ self.containing_transaction.get_baggage().dynamic_sampling_context()
766
+ )
767
+
768
+ data = {}
769
+
770
+ thread_id = self._data.get(SPANDATA.THREAD_ID)
771
+ if thread_id is not None:
772
+ data["thread.id"] = thread_id
773
+
774
+ thread_name = self._data.get(SPANDATA.THREAD_NAME)
775
+ if thread_name is not None:
776
+ data["thread.name"] = thread_name
777
+
778
+ if data:
779
+ rv["data"] = data
780
+
413
781
  return rv
414
782
 
783
+ def get_profile_context(self):
784
+ # type: () -> Optional[ProfileContext]
785
+ profiler_id = self._data.get(SPANDATA.PROFILER_ID)
786
+ if profiler_id is None:
787
+ return None
788
+
789
+ return {
790
+ "profiler_id": profiler_id,
791
+ }
792
+
793
+ def update_active_thread(self):
794
+ # type: () -> None
795
+ thread_id, thread_name = get_current_thread_meta()
796
+ self.set_thread(thread_id, thread_name)
797
+
415
798
 
416
799
  class Transaction(Span):
417
- __slots__ = ("name",)
800
+ """The Transaction is the root element that holds all the spans
801
+ for Sentry performance instrumentation.
802
+
803
+ :param name: Identifier of the transaction.
804
+ Will show up in the Sentry UI.
805
+ :param parent_sampled: Whether the parent transaction was sampled.
806
+ If True this transaction will be kept, if False it will be discarded.
807
+ :param baggage: The W3C baggage header value.
808
+ (see https://www.w3.org/TR/baggage/)
809
+ :param source: A string describing the source of the transaction name.
810
+ This will be used to determine the transaction's type.
811
+ See https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations
812
+ for more information. Default "custom".
813
+ :param kwargs: Additional arguments to be passed to the Span constructor.
814
+ See :py:class:`sentry_sdk.tracing.Span` for available arguments.
815
+ """
418
816
 
419
- def __init__(
817
+ __slots__ = (
818
+ "name",
819
+ "source",
820
+ "parent_sampled",
821
+ # used to create baggage value for head SDKs in dynamic sampling
822
+ "sample_rate",
823
+ "_measurements",
824
+ "_contexts",
825
+ "_profile",
826
+ "_continuous_profile",
827
+ "_baggage",
828
+ "_sample_rand",
829
+ )
830
+
831
+ def __init__( # type: ignore[misc]
420
832
  self,
421
833
  name="", # type: str
422
- **kwargs # type: Any
834
+ parent_sampled=None, # type: Optional[bool]
835
+ baggage=None, # type: Optional[Baggage]
836
+ source=TransactionSource.CUSTOM, # type: str
837
+ **kwargs, # type: Unpack[SpanKwargs]
423
838
  ):
424
839
  # type: (...) -> None
425
- # TODO: consider removing this in a future release.
426
- # This is for backwards compatibility with releases before Transaction
427
- # existed, to allow for a smoother transition.
428
- if not name and "transaction" in kwargs:
429
- logger.warning(
430
- "Deprecated: use Transaction(name=...) to create transactions "
431
- "instead of Span(transaction=...)."
432
- )
433
- name = kwargs.pop("transaction")
434
- Span.__init__(self, **kwargs)
840
+ super().__init__(**kwargs)
841
+
435
842
  self.name = name
843
+ self.source = source
844
+ self.sample_rate = None # type: Optional[float]
845
+ self.parent_sampled = parent_sampled
846
+ self._measurements = {} # type: Dict[str, MeasurementValue]
847
+ self._contexts = {} # type: Dict[str, Any]
848
+ self._profile = None # type: Optional[Profile]
849
+ self._continuous_profile = None # type: Optional[ContinuousProfile]
850
+ self._baggage = baggage
851
+
852
+ baggage_sample_rand = (
853
+ None if self._baggage is None else self._baggage._sample_rand()
854
+ )
855
+ if baggage_sample_rand is not None:
856
+ self._sample_rand = baggage_sample_rand
857
+ else:
858
+ self._sample_rand = _generate_sample_rand(self.trace_id)
436
859
 
437
860
  def __repr__(self):
438
861
  # type: () -> str
439
862
  return (
440
- "<%s(name=%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r)>"
863
+ "<%s(name=%r, op=%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r, source=%r, origin=%r)>"
441
864
  % (
442
865
  self.__class__.__name__,
443
866
  self.name,
867
+ self.op,
444
868
  self.trace_id,
445
869
  self.span_id,
446
870
  self.parent_span_id,
447
871
  self.sampled,
872
+ self.source,
873
+ self.origin,
448
874
  )
449
875
  )
450
876
 
451
- def finish(self, hub=None):
452
- # type: (Optional[sentry_sdk.Hub]) -> Optional[str]
877
+ def _possibly_started(self):
878
+ # type: () -> bool
879
+ """Returns whether the transaction might have been started.
880
+
881
+ If this returns False, we know that the transaction was not started
882
+ with sentry_sdk.start_transaction, and therefore the transaction will
883
+ be discarded.
884
+ """
885
+
886
+ # We must explicitly check self.sampled is False since self.sampled can be None
887
+ return self._span_recorder is not None or self.sampled is False
888
+
889
+ def __enter__(self):
890
+ # type: () -> Transaction
891
+ if not self._possibly_started():
892
+ logger.debug(
893
+ "Transaction was entered without being started with sentry_sdk.start_transaction."
894
+ "The transaction will not be sent to Sentry. To fix, start the transaction by"
895
+ "passing it to sentry_sdk.start_transaction."
896
+ )
897
+
898
+ super().__enter__()
899
+
900
+ if self._profile is not None:
901
+ self._profile.__enter__()
902
+
903
+ return self
904
+
905
+ def __exit__(self, ty, value, tb):
906
+ # type: (Optional[Any], Optional[Any], Optional[Any]) -> None
907
+ if self._profile is not None:
908
+ self._profile.__exit__(ty, value, tb)
909
+
910
+ if self._continuous_profile is not None:
911
+ self._continuous_profile.stop()
912
+
913
+ super().__exit__(ty, value, tb)
914
+
915
+ @property
916
+ def containing_transaction(self):
917
+ # type: () -> Transaction
918
+ """The root element of the span tree.
919
+ In the case of a transaction it is the transaction itself.
920
+ """
921
+
922
+ # Transactions (as spans) belong to themselves (as transactions). This
923
+ # is a getter rather than a regular attribute to avoid having a circular
924
+ # reference.
925
+ return self
926
+
927
+ def _get_scope_from_finish_args(
928
+ self,
929
+ scope_arg, # type: Optional[Union[sentry_sdk.Scope, sentry_sdk.Hub]]
930
+ hub_arg, # type: Optional[Union[sentry_sdk.Scope, sentry_sdk.Hub]]
931
+ ):
932
+ # type: (...) -> Optional[sentry_sdk.Scope]
933
+ """
934
+ Logic to get the scope from the arguments passed to finish. This
935
+ function exists for backwards compatibility with the old finish.
936
+
937
+ TODO: Remove this function in the next major version.
938
+ """
939
+ scope_or_hub = scope_arg
940
+ if hub_arg is not None:
941
+ warnings.warn(
942
+ "The `hub` parameter is deprecated. Please use the `scope` parameter, instead.",
943
+ DeprecationWarning,
944
+ stacklevel=3,
945
+ )
946
+
947
+ scope_or_hub = hub_arg
948
+
949
+ if isinstance(scope_or_hub, sentry_sdk.Hub):
950
+ warnings.warn(
951
+ "Passing a Hub to finish is deprecated. Please pass a Scope, instead.",
952
+ DeprecationWarning,
953
+ stacklevel=3,
954
+ )
955
+
956
+ return scope_or_hub.scope
957
+
958
+ return scope_or_hub
959
+
960
+ def _get_log_representation(self):
961
+ # type: () -> str
962
+ return "{op}transaction <{name}>".format(
963
+ op=("<" + self.op + "> " if self.op else ""), name=self.name
964
+ )
965
+
966
+ def finish(
967
+ self,
968
+ scope=None, # type: Optional[sentry_sdk.Scope]
969
+ end_timestamp=None, # type: Optional[Union[float, datetime]]
970
+ *,
971
+ hub=None, # type: Optional[sentry_sdk.Hub]
972
+ ):
973
+ # type: (...) -> Optional[str]
974
+ """Finishes the transaction and sends it to Sentry.
975
+ All finished spans in the transaction will also be sent to Sentry.
976
+
977
+ :param scope: The Scope to use for this transaction.
978
+ If not provided, the current Scope will be used.
979
+ :param end_timestamp: Optional timestamp that should
980
+ be used as timestamp instead of the current time.
981
+ :param hub: The hub to use for this transaction.
982
+ This argument is DEPRECATED. Please use the `scope`
983
+ parameter, instead.
984
+
985
+ :return: The event ID if the transaction was sent to Sentry,
986
+ otherwise None.
987
+ """
453
988
  if self.timestamp is not None:
454
989
  # This transaction is already finished, ignore.
455
990
  return None
456
991
 
457
- if self._span_recorder is None:
458
- return None
992
+ # For backwards compatibility, we must handle the case where `scope`
993
+ # or `hub` could both either be a `Scope` or a `Hub`.
994
+ scope = self._get_scope_from_finish_args(scope, hub) # type: Optional[sentry_sdk.Scope]
459
995
 
460
- hub = hub or self.hub or sentry_sdk.Hub.current
461
- client = hub.client
996
+ scope = scope or self.scope or sentry_sdk.get_current_scope()
997
+ client = sentry_sdk.get_client()
998
+
999
+ if not client.is_active():
1000
+ # We have no active client and therefore nowhere to send this transaction.
1001
+ return None
462
1002
 
463
- if client is None:
464
- # We have no client and therefore nowhere to send this transaction.
1003
+ if self._span_recorder is None:
1004
+ # Explicit check against False needed because self.sampled might be None
1005
+ if self.sampled is False:
1006
+ logger.debug("Discarding transaction because sampled = False")
1007
+ else:
1008
+ logger.debug(
1009
+ "Discarding transaction because it was not started with sentry_sdk.start_transaction"
1010
+ )
1011
+
1012
+ # This is not entirely accurate because discards here are not
1013
+ # exclusively based on sample rate but also traces sampler, but
1014
+ # we handle this the same here.
1015
+ if client.transport and has_tracing_enabled(client.options):
1016
+ if client.monitor and client.monitor.downsample_factor > 0:
1017
+ reason = "backpressure"
1018
+ else:
1019
+ reason = "sample_rate"
1020
+
1021
+ client.transport.record_lost_event(reason, data_category="transaction")
1022
+
1023
+ # Only one span (the transaction itself) is discarded, since we did not record any spans here.
1024
+ client.transport.record_lost_event(reason, data_category="span")
465
1025
  return None
466
1026
 
467
1027
  if not self.name:
@@ -470,109 +1030,457 @@ class Transaction(Span):
470
1030
  )
471
1031
  self.name = "<unlabeled transaction>"
472
1032
 
473
- Span.finish(self, hub)
1033
+ super().finish(scope, end_timestamp)
1034
+
1035
+ status_code = self._data.get(SPANDATA.HTTP_STATUS_CODE)
1036
+ if (
1037
+ status_code is not None
1038
+ and status_code in client.options["trace_ignore_status_codes"]
1039
+ ):
1040
+ logger.debug(
1041
+ "[Tracing] Discarding {transaction_description} because the HTTP status code {status_code} is matched by trace_ignore_status_codes: {trace_ignore_status_codes}".format(
1042
+ transaction_description=self._get_log_representation(),
1043
+ status_code=self._data[SPANDATA.HTTP_STATUS_CODE],
1044
+ trace_ignore_status_codes=client.options[
1045
+ "trace_ignore_status_codes"
1046
+ ],
1047
+ )
1048
+ )
1049
+ if client.transport:
1050
+ client.transport.record_lost_event(
1051
+ "event_processor", data_category="transaction"
1052
+ )
1053
+
1054
+ num_spans = len(self._span_recorder.spans) + 1
1055
+ client.transport.record_lost_event(
1056
+ "event_processor", data_category="span", quantity=num_spans
1057
+ )
1058
+
1059
+ self.sampled = False
474
1060
 
475
1061
  if not self.sampled:
476
1062
  # At this point a `sampled = None` should have already been resolved
477
1063
  # to a concrete decision.
478
1064
  if self.sampled is None:
479
1065
  logger.warning("Discarding transaction without sampling decision.")
1066
+
480
1067
  return None
481
1068
 
482
1069
  finished_spans = [
483
- span.to_json(client)
1070
+ span.to_json()
484
1071
  for span in self._span_recorder.spans
485
- if span is not self and span.timestamp is not None
1072
+ if span.timestamp is not None
486
1073
  ]
487
1074
 
488
- return hub.capture_event(
489
- {
490
- "type": "transaction",
491
- "transaction": self.name,
492
- "contexts": {"trace": self.get_trace_context()},
493
- "tags": self._tags,
494
- "timestamp": self.timestamp,
495
- "start_timestamp": self.start_timestamp,
496
- "spans": finished_spans,
497
- }
1075
+ len_diff = len(self._span_recorder.spans) - len(finished_spans)
1076
+ dropped_spans = len_diff + self._span_recorder.dropped_spans
1077
+
1078
+ # we do this to break the circular reference of transaction -> span
1079
+ # recorder -> span -> containing transaction (which is where we started)
1080
+ # before either the spans or the transaction goes out of scope and has
1081
+ # to be garbage collected
1082
+ self._span_recorder = None
1083
+
1084
+ contexts = {}
1085
+ contexts.update(self._contexts)
1086
+ contexts.update({"trace": self.get_trace_context()})
1087
+ profile_context = self.get_profile_context()
1088
+ if profile_context is not None:
1089
+ contexts.update({"profile": profile_context})
1090
+
1091
+ event = {
1092
+ "type": "transaction",
1093
+ "transaction": self.name,
1094
+ "transaction_info": {"source": self.source},
1095
+ "contexts": contexts,
1096
+ "tags": self._tags,
1097
+ "timestamp": self.timestamp,
1098
+ "start_timestamp": self.start_timestamp,
1099
+ "spans": finished_spans,
1100
+ } # type: Event
1101
+
1102
+ if dropped_spans > 0:
1103
+ event["_dropped_spans"] = dropped_spans
1104
+
1105
+ if self._profile is not None and self._profile.valid():
1106
+ event["profile"] = self._profile
1107
+ self._profile = None
1108
+
1109
+ event["measurements"] = self._measurements
1110
+
1111
+ return scope.capture_event(event)
1112
+
1113
+ def set_measurement(self, name, value, unit=""):
1114
+ # type: (str, float, MeasurementUnit) -> None
1115
+ """
1116
+ .. deprecated:: 2.28.0
1117
+ This function is deprecated and will be removed in the next major release.
1118
+ """
1119
+
1120
+ warnings.warn(
1121
+ "`set_measurement()` is deprecated and will be removed in the next major version. Please use `set_data()` instead.",
1122
+ DeprecationWarning,
1123
+ stacklevel=2,
498
1124
  )
1125
+ self._measurements[name] = {"value": value, "unit": unit}
499
1126
 
1127
+ def set_context(self, key, value):
1128
+ # type: (str, dict[str, Any]) -> None
1129
+ """Sets a context. Transactions can have multiple contexts
1130
+ and they should follow the format described in the "Contexts Interface"
1131
+ documentation.
500
1132
 
501
- def _format_sql(cursor, sql):
502
- # type: (Any, str) -> Optional[str]
1133
+ :param key: The name of the context.
1134
+ :param value: The information about the context.
1135
+ """
1136
+ self._contexts[key] = value
503
1137
 
504
- real_sql = None
1138
+ def set_http_status(self, http_status):
1139
+ # type: (int) -> None
1140
+ """Sets the status of the Transaction according to the given HTTP status.
505
1141
 
506
- # If we're using psycopg2, it could be that we're
507
- # looking at a query that uses Composed objects. Use psycopg2's mogrify
508
- # function to format the query. We lose per-parameter trimming but gain
509
- # accuracy in formatting.
510
- try:
511
- if hasattr(cursor, "mogrify"):
512
- real_sql = cursor.mogrify(sql)
513
- if isinstance(real_sql, bytes):
514
- real_sql = real_sql.decode(cursor.connection.encoding)
515
- except Exception:
516
- real_sql = None
1142
+ :param http_status: The HTTP status code."""
1143
+ super().set_http_status(http_status)
1144
+ self.set_context("response", {"status_code": http_status})
517
1145
 
518
- return real_sql or to_string(sql)
1146
+ def to_json(self):
1147
+ # type: () -> Dict[str, Any]
1148
+ """Returns a JSON-compatible representation of the transaction."""
1149
+ rv = super().to_json()
519
1150
 
1151
+ rv["name"] = self.name
1152
+ rv["source"] = self.source
1153
+ rv["sampled"] = self.sampled
520
1154
 
521
- @contextlib.contextmanager
522
- def record_sql_queries(
523
- hub, # type: sentry_sdk.Hub
524
- cursor, # type: Any
525
- query, # type: Any
526
- params_list, # type: Any
527
- paramstyle, # type: Optional[str]
528
- executemany, # type: bool
529
- ):
530
- # type: (...) -> Generator[Span, None, None]
1155
+ return rv
531
1156
 
532
- # TODO: Bring back capturing of params by default
533
- if hub.client and hub.client.options["_experiments"].get(
534
- "record_sql_params", False
535
- ):
536
- if not params_list or params_list == [None]:
537
- params_list = None
1157
+ def get_trace_context(self):
1158
+ # type: () -> Any
1159
+ trace_context = super().get_trace_context()
538
1160
 
539
- if paramstyle == "pyformat":
540
- paramstyle = "format"
541
- else:
542
- params_list = None
543
- paramstyle = None
1161
+ if self._data:
1162
+ trace_context["data"] = self._data
544
1163
 
545
- query = _format_sql(cursor, query)
1164
+ return trace_context
546
1165
 
547
- data = {}
548
- if params_list is not None:
549
- data["db.params"] = params_list
550
- if paramstyle is not None:
551
- data["db.paramstyle"] = paramstyle
552
- if executemany:
553
- data["db.executemany"] = True
1166
+ def get_baggage(self):
1167
+ # type: () -> Baggage
1168
+ """Returns the :py:class:`~sentry_sdk.tracing_utils.Baggage`
1169
+ associated with the Transaction.
554
1170
 
555
- with capture_internal_exceptions():
556
- hub.add_breadcrumb(message=query, category="query", data=data)
1171
+ The first time a new baggage with Sentry items is made,
1172
+ it will be frozen."""
1173
+ if not self._baggage or self._baggage.mutable:
1174
+ self._baggage = Baggage.populate_from_transaction(self)
557
1175
 
558
- with hub.start_span(op="db", description=query) as span:
559
- for k, v in data.items():
560
- span.set_data(k, v)
561
- yield span
1176
+ return self._baggage
562
1177
 
1178
+ def _set_initial_sampling_decision(self, sampling_context):
1179
+ # type: (SamplingContext) -> None
1180
+ """
1181
+ Sets the transaction's sampling decision, according to the following
1182
+ precedence rules:
1183
+
1184
+ 1. If a sampling decision is passed to `start_transaction`
1185
+ (`start_transaction(name: "my transaction", sampled: True)`), that
1186
+ decision will be used, regardless of anything else
1187
+
1188
+ 2. If `traces_sampler` is defined, its decision will be used. It can
1189
+ choose to keep or ignore any parent sampling decision, or use the
1190
+ sampling context data to make its own decision or to choose a sample
1191
+ rate for the transaction.
563
1192
 
564
- def _maybe_create_breadcrumbs_from_span(hub, span):
565
- # type: (sentry_sdk.Hub, Span) -> None
566
- if span.op == "redis":
567
- hub.add_breadcrumb(
568
- message=span.description, type="redis", category="redis", data=span._tags
1193
+ 3. If `traces_sampler` is not defined, but there's a parent sampling
1194
+ decision, the parent sampling decision will be used.
1195
+
1196
+ 4. If `traces_sampler` is not defined and there's no parent sampling
1197
+ decision, `traces_sample_rate` will be used.
1198
+ """
1199
+ client = sentry_sdk.get_client()
1200
+
1201
+ transaction_description = self._get_log_representation()
1202
+
1203
+ # nothing to do if tracing is disabled
1204
+ if not has_tracing_enabled(client.options):
1205
+ self.sampled = False
1206
+ return
1207
+
1208
+ # if the user has forced a sampling decision by passing a `sampled`
1209
+ # value when starting the transaction, go with that
1210
+ if self.sampled is not None:
1211
+ self.sample_rate = float(self.sampled)
1212
+ return
1213
+
1214
+ # we would have bailed already if neither `traces_sampler` nor
1215
+ # `traces_sample_rate` were defined, so one of these should work; prefer
1216
+ # the hook if so
1217
+ sample_rate = (
1218
+ client.options["traces_sampler"](sampling_context)
1219
+ if callable(client.options.get("traces_sampler"))
1220
+ # default inheritance behavior
1221
+ else (
1222
+ sampling_context["parent_sampled"]
1223
+ if sampling_context["parent_sampled"] is not None
1224
+ else client.options["traces_sample_rate"]
1225
+ )
569
1226
  )
570
- elif span.op == "http":
571
- hub.add_breadcrumb(type="http", category="httplib", data=span._data)
572
- elif span.op == "subprocess":
573
- hub.add_breadcrumb(
574
- type="subprocess",
575
- category="subprocess",
576
- message=span.description,
577
- data=span._data,
1227
+
1228
+ # Since this is coming from the user (or from a function provided by the
1229
+ # user), who knows what we might get. (The only valid values are
1230
+ # booleans or numbers between 0 and 1.)
1231
+ if not is_valid_sample_rate(sample_rate, source="Tracing"):
1232
+ logger.warning(
1233
+ "[Tracing] Discarding {transaction_description} because of invalid sample rate.".format(
1234
+ transaction_description=transaction_description,
1235
+ )
1236
+ )
1237
+ self.sampled = False
1238
+ return
1239
+
1240
+ self.sample_rate = float(sample_rate)
1241
+
1242
+ if client.monitor:
1243
+ self.sample_rate /= 2**client.monitor.downsample_factor
1244
+
1245
+ # if the function returned 0 (or false), or if `traces_sample_rate` is
1246
+ # 0, it's a sign the transaction should be dropped
1247
+ if not self.sample_rate:
1248
+ logger.debug(
1249
+ "[Tracing] Discarding {transaction_description} because {reason}".format(
1250
+ transaction_description=transaction_description,
1251
+ reason=(
1252
+ "traces_sampler returned 0 or False"
1253
+ if callable(client.options.get("traces_sampler"))
1254
+ else "traces_sample_rate is set to 0"
1255
+ ),
1256
+ )
1257
+ )
1258
+ self.sampled = False
1259
+ return
1260
+
1261
+ # Now we roll the dice.
1262
+ self.sampled = self._sample_rand < self.sample_rate
1263
+
1264
+ if self.sampled:
1265
+ logger.debug(
1266
+ "[Tracing] Starting {transaction_description}".format(
1267
+ transaction_description=transaction_description,
1268
+ )
1269
+ )
1270
+ else:
1271
+ logger.debug(
1272
+ "[Tracing] Discarding {transaction_description} because it's not included in the random sample (sampling rate = {sample_rate})".format(
1273
+ transaction_description=transaction_description,
1274
+ sample_rate=self.sample_rate,
1275
+ )
1276
+ )
1277
+
1278
+
1279
+ class NoOpSpan(Span):
1280
+ def __repr__(self):
1281
+ # type: () -> str
1282
+ return "<%s>" % self.__class__.__name__
1283
+
1284
+ @property
1285
+ def containing_transaction(self):
1286
+ # type: () -> Optional[Transaction]
1287
+ return None
1288
+
1289
+ def start_child(self, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
1290
+ # type: (str, **Any) -> NoOpSpan
1291
+ return NoOpSpan()
1292
+
1293
+ def to_traceparent(self):
1294
+ # type: () -> str
1295
+ return ""
1296
+
1297
+ def to_baggage(self):
1298
+ # type: () -> Optional[Baggage]
1299
+ return None
1300
+
1301
+ def get_baggage(self):
1302
+ # type: () -> Optional[Baggage]
1303
+ return None
1304
+
1305
+ def iter_headers(self):
1306
+ # type: () -> Iterator[Tuple[str, str]]
1307
+ return iter(())
1308
+
1309
+ def set_tag(self, key, value):
1310
+ # type: (str, Any) -> None
1311
+ pass
1312
+
1313
+ def set_data(self, key, value):
1314
+ # type: (str, Any) -> None
1315
+ pass
1316
+
1317
+ def update_data(self, data):
1318
+ # type: (Dict[str, Any]) -> None
1319
+ pass
1320
+
1321
+ def set_status(self, value):
1322
+ # type: (str) -> None
1323
+ pass
1324
+
1325
+ def set_http_status(self, http_status):
1326
+ # type: (int) -> None
1327
+ pass
1328
+
1329
+ def is_success(self):
1330
+ # type: () -> bool
1331
+ return True
1332
+
1333
+ def to_json(self):
1334
+ # type: () -> Dict[str, Any]
1335
+ return {}
1336
+
1337
+ def get_trace_context(self):
1338
+ # type: () -> Any
1339
+ return {}
1340
+
1341
+ def get_profile_context(self):
1342
+ # type: () -> Any
1343
+ return {}
1344
+
1345
+ def finish(
1346
+ self,
1347
+ scope=None, # type: Optional[sentry_sdk.Scope]
1348
+ end_timestamp=None, # type: Optional[Union[float, datetime]]
1349
+ *,
1350
+ hub=None, # type: Optional[sentry_sdk.Hub]
1351
+ ):
1352
+ # type: (...) -> Optional[str]
1353
+ """
1354
+ The `hub` parameter is deprecated. Please use the `scope` parameter, instead.
1355
+ """
1356
+ pass
1357
+
1358
+ def set_measurement(self, name, value, unit=""):
1359
+ # type: (str, float, MeasurementUnit) -> None
1360
+ pass
1361
+
1362
+ def set_context(self, key, value):
1363
+ # type: (str, dict[str, Any]) -> None
1364
+ pass
1365
+
1366
+ def init_span_recorder(self, maxlen):
1367
+ # type: (int) -> None
1368
+ pass
1369
+
1370
+ def _set_initial_sampling_decision(self, sampling_context):
1371
+ # type: (SamplingContext) -> None
1372
+ pass
1373
+
1374
+
1375
+ if TYPE_CHECKING:
1376
+
1377
+ @overload
1378
+ def trace(
1379
+ func=None, *, op=None, name=None, attributes=None, template=SPANTEMPLATE.DEFAULT
1380
+ ):
1381
+ # type: (None, Optional[str], Optional[str], Optional[dict[str, Any]], SPANTEMPLATE) -> Callable[[Callable[P, R]], Callable[P, R]]
1382
+ # Handles: @trace() and @trace(op="custom")
1383
+ pass
1384
+
1385
+ @overload
1386
+ def trace(func):
1387
+ # type: (Callable[P, R]) -> Callable[P, R]
1388
+ # Handles: @trace
1389
+ pass
1390
+
1391
+
1392
+ def trace(
1393
+ func=None, *, op=None, name=None, attributes=None, template=SPANTEMPLATE.DEFAULT
1394
+ ):
1395
+ # type: (Optional[Callable[P, R]], Optional[str], Optional[str], Optional[dict[str, Any]], SPANTEMPLATE) -> Union[Callable[P, R], Callable[[Callable[P, R]], Callable[P, R]]]
1396
+ """
1397
+ Decorator to start a child span around a function call.
1398
+
1399
+ This decorator automatically creates a new span when the decorated function
1400
+ is called, and finishes the span when the function returns or raises an exception.
1401
+
1402
+ :param func: The function to trace. When used as a decorator without parentheses,
1403
+ this is the function being decorated. When used with parameters (e.g.,
1404
+ ``@trace(op="custom")``, this should be None.
1405
+ :type func: Callable or None
1406
+
1407
+ :param op: The operation name for the span. This is a high-level description
1408
+ of what the span represents (e.g., "http.client", "db.query").
1409
+ You can use predefined constants from :py:class:`sentry_sdk.consts.OP`
1410
+ or provide your own string. If not provided, a default operation will
1411
+ be assigned based on the template.
1412
+ :type op: str or None
1413
+
1414
+ :param name: The human-readable name/description for the span. If not provided,
1415
+ defaults to the function name. This provides more specific details about
1416
+ what the span represents (e.g., "GET /api/users", "process_user_data").
1417
+ :type name: str or None
1418
+
1419
+ :param attributes: A dictionary of key-value pairs to add as attributes to the span.
1420
+ Attribute values must be strings, integers, floats, or booleans. These
1421
+ attributes provide additional context about the span's execution.
1422
+ :type attributes: dict[str, Any] or None
1423
+
1424
+ :param template: The type of span to create. This determines what kind of
1425
+ span instrumentation and data collection will be applied. Use predefined
1426
+ constants from :py:class:`sentry_sdk.consts.SPANTEMPLATE`.
1427
+ The default is `SPANTEMPLATE.DEFAULT` which is the right choice for most
1428
+ use cases.
1429
+ :type template: :py:class:`sentry_sdk.consts.SPANTEMPLATE`
1430
+
1431
+ :returns: When used as ``@trace``, returns the decorated function. When used as
1432
+ ``@trace(...)`` with parameters, returns a decorator function.
1433
+ :rtype: Callable or decorator function
1434
+
1435
+ Example::
1436
+
1437
+ import sentry_sdk
1438
+ from sentry_sdk.consts import OP, SPANTEMPLATE
1439
+
1440
+ # Simple usage with default values
1441
+ @sentry_sdk.trace
1442
+ def process_data():
1443
+ # Function implementation
1444
+ pass
1445
+
1446
+ # With custom parameters
1447
+ @sentry_sdk.trace(
1448
+ op=OP.DB_QUERY,
1449
+ name="Get user data",
1450
+ attributes={"postgres": True}
578
1451
  )
1452
+ def make_db_query(sql):
1453
+ # Function implementation
1454
+ pass
1455
+
1456
+ # With a custom template
1457
+ @sentry_sdk.trace(template=SPANTEMPLATE.AI_TOOL)
1458
+ def calculate_interest_rate(amount, rate, years):
1459
+ # Function implementation
1460
+ pass
1461
+ """
1462
+ from sentry_sdk.tracing_utils import create_span_decorator
1463
+
1464
+ decorator = create_span_decorator(
1465
+ op=op,
1466
+ name=name,
1467
+ attributes=attributes,
1468
+ template=template,
1469
+ )
1470
+
1471
+ if func:
1472
+ return decorator(func)
1473
+ else:
1474
+ return decorator
1475
+
1476
+
1477
+ # Circular imports
1478
+
1479
+ from sentry_sdk.tracing_utils import (
1480
+ Baggage,
1481
+ EnvironHeaders,
1482
+ extract_sentrytrace_data,
1483
+ _generate_sample_rand,
1484
+ has_tracing_enabled,
1485
+ maybe_create_breadcrumbs_from_span,
1486
+ )