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/hub.py CHANGED
@@ -1,38 +1,47 @@
1
- import copy
2
- import random
3
- import sys
4
-
5
- from datetime import datetime
1
+ import warnings
6
2
  from contextlib import contextmanager
7
3
 
4
+ from sentry_sdk import (
5
+ get_client,
6
+ get_global_scope,
7
+ get_isolation_scope,
8
+ get_current_scope,
9
+ )
8
10
  from sentry_sdk._compat import with_metaclass
9
- from sentry_sdk.scope import Scope
11
+ from sentry_sdk.consts import INSTRUMENTER
12
+ from sentry_sdk.scope import _ScopeManager
10
13
  from sentry_sdk.client import Client
11
- from sentry_sdk.tracing import Span, Transaction
12
- from sentry_sdk.sessions import Session
14
+ from sentry_sdk.tracing import (
15
+ NoOpSpan,
16
+ Span,
17
+ Transaction,
18
+ )
19
+
13
20
  from sentry_sdk.utils import (
14
- exc_info_from_error,
15
- event_from_exception,
16
21
  logger,
17
22
  ContextVar,
18
23
  )
19
24
 
20
- from sentry_sdk._types import MYPY
25
+ from typing import TYPE_CHECKING
21
26
 
22
- if MYPY:
23
- from typing import Union
27
+ if TYPE_CHECKING:
24
28
  from typing import Any
25
- from typing import Optional
26
- from typing import Tuple
27
- from typing import Dict
28
- from typing import List
29
29
  from typing import Callable
30
+ from typing import ContextManager
31
+ from typing import Dict
30
32
  from typing import Generator
33
+ from typing import List
34
+ from typing import Optional
35
+ from typing import overload
36
+ from typing import Tuple
31
37
  from typing import Type
32
38
  from typing import TypeVar
33
- from typing import overload
34
- from typing import ContextManager
39
+ from typing import Union
35
40
 
41
+ from typing_extensions import Unpack
42
+
43
+ from sentry_sdk.scope import Scope
44
+ from sentry_sdk.client import BaseClient
36
45
  from sentry_sdk.integrations import Integration
37
46
  from sentry_sdk._types import (
38
47
  Event,
@@ -40,8 +49,10 @@ if MYPY:
40
49
  Breadcrumb,
41
50
  BreadcrumbHint,
42
51
  ExcInfo,
52
+ LogLevelStr,
53
+ SamplingContext,
43
54
  )
44
- from sentry_sdk.consts import ClientConstructor
55
+ from sentry_sdk.tracing import TransactionKwargs
45
56
 
46
57
  T = TypeVar("T")
47
58
 
@@ -52,82 +63,33 @@ else:
52
63
  return x
53
64
 
54
65
 
55
- _local = ContextVar("sentry_current_hub")
56
-
57
-
58
- def _update_scope(base, scope_change, scope_kwargs):
59
- # type: (Scope, Optional[Any], Dict[str, Any]) -> Scope
60
- if scope_change and scope_kwargs:
61
- raise TypeError("cannot provide scope and kwargs")
62
- if scope_change is not None:
63
- final_scope = copy.copy(base)
64
- if callable(scope_change):
65
- scope_change(final_scope)
66
- else:
67
- final_scope.update_from_scope(scope_change)
68
- elif scope_kwargs:
69
- final_scope = copy.copy(base)
70
- final_scope.update_from_kwargs(**scope_kwargs)
71
- else:
72
- final_scope = base
73
- return final_scope
74
-
75
-
76
- def _should_send_default_pii():
77
- # type: () -> bool
78
- client = Hub.current.client
79
- if not client:
80
- return False
81
- return client.options["send_default_pii"]
82
-
83
-
84
- class _InitGuard(object):
85
- def __init__(self, client):
86
- # type: (Client) -> None
87
- self._client = client
88
-
89
- def __enter__(self):
90
- # type: () -> _InitGuard
91
- return self
92
-
93
- def __exit__(self, exc_type, exc_value, tb):
94
- # type: (Any, Any, Any) -> None
95
- c = self._client
96
- if c is not None:
97
- c.close()
98
-
99
-
100
- def _init(*args, **kwargs):
101
- # type: (*Optional[str], **Any) -> ContextManager[Any]
102
- """Initializes the SDK and optionally integrations.
103
-
104
- This takes the same arguments as the client constructor.
66
+ class SentryHubDeprecationWarning(DeprecationWarning):
67
+ """
68
+ A custom deprecation warning to inform users that the Hub is deprecated.
105
69
  """
106
- client = Client(*args, **kwargs) # type: ignore
107
- Hub.current.bind_client(client)
108
- rv = _InitGuard(client)
109
- return rv
110
-
111
70
 
112
- from sentry_sdk._types import MYPY
71
+ _MESSAGE = (
72
+ "`sentry_sdk.Hub` is deprecated and will be removed in a future major release. "
73
+ "Please consult our 1.x to 2.x migration guide for details on how to migrate "
74
+ "`Hub` usage to the new API: "
75
+ "https://docs.sentry.io/platforms/python/migration/1.x-to-2.x"
76
+ )
113
77
 
114
- if MYPY:
115
- # Make mypy, PyCharm and other static analyzers think `init` is a type to
116
- # have nicer autocompletion for params.
117
- #
118
- # Use `ClientConstructor` to define the argument types of `init` and
119
- # `ContextManager[Any]` to tell static analyzers about the return type.
78
+ def __init__(self, *_):
79
+ # type: (*object) -> None
80
+ super().__init__(self._MESSAGE)
120
81
 
121
- class init(ClientConstructor, ContextManager[Any]): # noqa: N801
122
- pass
123
82
 
83
+ @contextmanager
84
+ def _suppress_hub_deprecation_warning():
85
+ # type: () -> Generator[None, None, None]
86
+ """Utility function to suppress deprecation warnings for the Hub."""
87
+ with warnings.catch_warnings():
88
+ warnings.filterwarnings("ignore", category=SentryHubDeprecationWarning)
89
+ yield
124
90
 
125
- else:
126
- # Alias `init` for actual usage. Go through the lambda indirection to throw
127
- # PyCharm off of the weakly typed signature (it would otherwise discover
128
- # both the weakly typed signature of `_init` and our faked `init` type).
129
91
 
130
- init = (lambda: _init)()
92
+ _local = ContextVar("sentry_current_hub")
131
93
 
132
94
 
133
95
  class HubMeta(type):
@@ -135,9 +97,12 @@ class HubMeta(type):
135
97
  def current(cls):
136
98
  # type: () -> Hub
137
99
  """Returns the current instance of the hub."""
100
+ warnings.warn(SentryHubDeprecationWarning(), stacklevel=2)
138
101
  rv = _local.get(None)
139
102
  if rv is None:
140
- rv = Hub(GLOBAL_HUB)
103
+ with _suppress_hub_deprecation_warning():
104
+ # This will raise a deprecation warning; suppress it since we already warned above.
105
+ rv = Hub(GLOBAL_HUB)
141
106
  _local.set(rv)
142
107
  return rv
143
108
 
@@ -145,59 +110,16 @@ class HubMeta(type):
145
110
  def main(cls):
146
111
  # type: () -> Hub
147
112
  """Returns the main instance of the hub."""
113
+ warnings.warn(SentryHubDeprecationWarning(), stacklevel=2)
148
114
  return GLOBAL_HUB
149
115
 
150
116
 
151
- class _ScopeManager(object):
152
- def __init__(self, hub):
153
- # type: (Hub) -> None
154
- self._hub = hub
155
- self._original_len = len(hub._stack)
156
- self._layer = hub._stack[-1]
157
-
158
- def __enter__(self):
159
- # type: () -> Scope
160
- scope = self._layer[1]
161
- assert scope is not None
162
- return scope
163
-
164
- def __exit__(self, exc_type, exc_value, tb):
165
- # type: (Any, Any, Any) -> None
166
- current_len = len(self._hub._stack)
167
- if current_len < self._original_len:
168
- logger.error(
169
- "Scope popped too soon. Popped %s scopes too many.",
170
- self._original_len - current_len,
171
- )
172
- return
173
- elif current_len > self._original_len:
174
- logger.warning(
175
- "Leaked %s scopes: %s",
176
- current_len - self._original_len,
177
- self._hub._stack[self._original_len :],
178
- )
179
-
180
- layer = self._hub._stack[self._original_len - 1]
181
- del self._hub._stack[self._original_len - 1 :]
182
-
183
- if layer[1] != self._layer[1]:
184
- logger.error(
185
- "Wrong scope found. Meant to pop %s, but popped %s.",
186
- layer[1],
187
- self._layer[1],
188
- )
189
- elif layer[0] != self._layer[0]:
190
- warning = (
191
- "init() called inside of pushed scope. This might be entirely "
192
- "legitimate but usually occurs when initializing the SDK inside "
193
- "a request handler or task/job function. Try to initialize the "
194
- "SDK as early as possible instead."
195
- )
196
- logger.warning(warning)
197
-
198
-
199
117
  class Hub(with_metaclass(HubMeta)): # type: ignore
200
- """The hub wraps the concurrency management of the SDK. Each thread has
118
+ """
119
+ .. deprecated:: 2.0.0
120
+ The Hub is deprecated. Its functionality will be merged into :py:class:`sentry_sdk.scope.Scope`.
121
+
122
+ The hub wraps the concurrency management of the SDK. Each thread has
201
123
  its own hub but the hub might transfer with the flow of execution if
202
124
  context vars are available.
203
125
 
@@ -205,10 +127,11 @@ class Hub(with_metaclass(HubMeta)): # type: ignore
205
127
  """
206
128
 
207
129
  _stack = None # type: List[Tuple[Optional[Client], Scope]]
130
+ _scope = None # type: Optional[Scope]
208
131
 
209
132
  # Mypy doesn't pick up on the metaclass.
210
133
 
211
- if MYPY:
134
+ if TYPE_CHECKING:
212
135
  current = None # type: Hub
213
136
  main = None # type: Hub
214
137
 
@@ -218,24 +141,51 @@ class Hub(with_metaclass(HubMeta)): # type: ignore
218
141
  scope=None, # type: Optional[Any]
219
142
  ):
220
143
  # type: (...) -> None
144
+ warnings.warn(SentryHubDeprecationWarning(), stacklevel=2)
145
+
146
+ current_scope = None
147
+
221
148
  if isinstance(client_or_hub, Hub):
222
- hub = client_or_hub
223
- client, other_scope = hub._stack[-1]
149
+ client = get_client()
224
150
  if scope is None:
225
- scope = copy.copy(other_scope)
151
+ # hub cloning is going on, we use a fork of the current/isolation scope for context manager
152
+ scope = get_isolation_scope().fork()
153
+ current_scope = get_current_scope().fork()
226
154
  else:
227
- client = client_or_hub
228
- if scope is None:
229
- scope = Scope()
155
+ client = client_or_hub # type: ignore
156
+ get_global_scope().set_client(client)
157
+
158
+ if scope is None: # so there is no Hub cloning going on
159
+ # just the current isolation scope is used for context manager
160
+ scope = get_isolation_scope()
161
+ current_scope = get_current_scope()
230
162
 
231
- self._stack = [(client, scope)]
163
+ if current_scope is None:
164
+ # just the current current scope is used for context manager
165
+ current_scope = get_current_scope()
166
+
167
+ self._stack = [(client, scope)] # type: ignore
232
168
  self._last_event_id = None # type: Optional[str]
233
169
  self._old_hubs = [] # type: List[Hub]
234
170
 
171
+ self._old_current_scopes = [] # type: List[Scope]
172
+ self._old_isolation_scopes = [] # type: List[Scope]
173
+ self._current_scope = current_scope # type: Scope
174
+ self._scope = scope # type: Scope
175
+
235
176
  def __enter__(self):
236
177
  # type: () -> Hub
237
178
  self._old_hubs.append(Hub.current)
238
179
  _local.set(self)
180
+
181
+ current_scope = get_current_scope()
182
+ self._old_current_scopes.append(current_scope)
183
+ scope._current_scope.set(self._current_scope)
184
+
185
+ isolation_scope = get_isolation_scope()
186
+ self._old_isolation_scopes.append(isolation_scope)
187
+ scope._isolation_scope.set(self._scope)
188
+
239
189
  return self
240
190
 
241
191
  def __exit__(
@@ -248,242 +198,249 @@ class Hub(with_metaclass(HubMeta)): # type: ignore
248
198
  old = self._old_hubs.pop()
249
199
  _local.set(old)
250
200
 
201
+ old_current_scope = self._old_current_scopes.pop()
202
+ scope._current_scope.set(old_current_scope)
203
+
204
+ old_isolation_scope = self._old_isolation_scopes.pop()
205
+ scope._isolation_scope.set(old_isolation_scope)
206
+
251
207
  def run(
252
- self, callback # type: Callable[[], T]
208
+ self,
209
+ callback, # type: Callable[[], T]
253
210
  ):
254
211
  # type: (...) -> T
255
- """Runs a callback in the context of the hub. Alternatively the
212
+ """
213
+ .. deprecated:: 2.0.0
214
+ This function is deprecated and will be removed in a future release.
215
+
216
+ Runs a callback in the context of the hub. Alternatively the
256
217
  with statement can be used on the hub directly.
257
218
  """
258
219
  with self:
259
220
  return callback()
260
221
 
261
222
  def get_integration(
262
- self, name_or_class # type: Union[str, Type[Integration]]
223
+ self,
224
+ name_or_class, # type: Union[str, Type[Integration]]
263
225
  ):
264
226
  # type: (...) -> Any
265
- """Returns the integration for this hub by name or class. If there
227
+ """
228
+ .. deprecated:: 2.0.0
229
+ This function is deprecated and will be removed in a future release.
230
+ Please use :py:meth:`sentry_sdk.client._Client.get_integration` instead.
231
+
232
+ Returns the integration for this hub by name or class. If there
266
233
  is no client bound or the client does not have that integration
267
234
  then `None` is returned.
268
235
 
269
236
  If the return value is not `None` the hub is guaranteed to have a
270
237
  client attached.
271
238
  """
272
- if isinstance(name_or_class, str):
273
- integration_name = name_or_class
274
- elif name_or_class.identifier is not None:
275
- integration_name = name_or_class.identifier
276
- else:
277
- raise ValueError("Integration has no name")
278
-
279
- client = self.client
280
- if client is not None:
281
- rv = client.integrations.get(integration_name)
282
- if rv is not None:
283
- return rv
239
+ return get_client().get_integration(name_or_class)
284
240
 
285
241
  @property
286
242
  def client(self):
287
- # type: () -> Optional[Client]
288
- """Returns the current client on the hub."""
289
- return self._stack[-1][0]
243
+ # type: () -> Optional[BaseClient]
244
+ """
245
+ .. deprecated:: 2.0.0
246
+ This property is deprecated and will be removed in a future release.
247
+ Please use :py:func:`sentry_sdk.api.get_client` instead.
248
+
249
+ Returns the current client on the hub.
250
+ """
251
+ client = get_client()
252
+
253
+ if not client.is_active():
254
+ return None
255
+
256
+ return client
290
257
 
291
258
  @property
292
259
  def scope(self):
293
260
  # type: () -> Scope
294
- """Returns the current scope on the hub."""
295
- return self._stack[-1][1]
261
+ """
262
+ .. deprecated:: 2.0.0
263
+ This property is deprecated and will be removed in a future release.
264
+ Returns the current scope on the hub.
265
+ """
266
+ return get_isolation_scope()
296
267
 
297
268
  def last_event_id(self):
298
269
  # type: () -> Optional[str]
299
- """Returns the last event ID."""
270
+ """
271
+ Returns the last event ID.
272
+
273
+ .. deprecated:: 1.40.5
274
+ This function is deprecated and will be removed in a future release. The functions `capture_event`, `capture_message`, and `capture_exception` return the event ID directly.
275
+ """
276
+ logger.warning(
277
+ "Deprecated: last_event_id is deprecated. This will be removed in the future. The functions `capture_event`, `capture_message`, and `capture_exception` return the event ID directly."
278
+ )
300
279
  return self._last_event_id
301
280
 
302
281
  def bind_client(
303
- self, new # type: Optional[Client]
282
+ self,
283
+ new, # type: Optional[BaseClient]
304
284
  ):
305
285
  # type: (...) -> None
306
- """Binds a new client to the hub."""
307
- top = self._stack[-1]
308
- self._stack[-1] = (new, top[1])
286
+ """
287
+ .. deprecated:: 2.0.0
288
+ This function is deprecated and will be removed in a future release.
289
+ Please use :py:meth:`sentry_sdk.Scope.set_client` instead.
309
290
 
310
- def capture_event(
311
- self,
312
- event, # type: Event
313
- hint=None, # type: Optional[Hint]
314
- scope=None, # type: Optional[Any]
315
- **scope_args # type: Dict[str, Any]
316
- ):
317
- # type: (...) -> Optional[str]
318
- """Captures an event. Alias of :py:meth:`sentry_sdk.Client.capture_event`."""
319
- client, top_scope = self._stack[-1]
320
- scope = _update_scope(top_scope, scope, scope_args)
321
- if client is not None:
322
- rv = client.capture_event(event, hint, scope)
323
- if rv is not None:
324
- self._last_event_id = rv
325
- return rv
326
- return None
291
+ Binds a new client to the hub.
292
+ """
293
+ get_global_scope().set_client(new)
327
294
 
328
- def capture_message(
329
- self,
330
- message, # type: str
331
- level=None, # type: Optional[str]
332
- scope=None, # type: Optional[Any]
333
- **scope_args # type: Dict[str, Any]
334
- ):
335
- # type: (...) -> Optional[str]
336
- """Captures a message. The message is just a string. If no level
337
- is provided the default level is `info`.
295
+ def capture_event(self, event, hint=None, scope=None, **scope_kwargs):
296
+ # type: (Event, Optional[Hint], Optional[Scope], Any) -> Optional[str]
297
+ """
298
+ .. deprecated:: 2.0.0
299
+ This function is deprecated and will be removed in a future release.
300
+ Please use :py:meth:`sentry_sdk.Scope.capture_event` instead.
301
+
302
+ Captures an event.
303
+
304
+ Alias of :py:meth:`sentry_sdk.Scope.capture_event`.
305
+
306
+ :param event: A ready-made event that can be directly sent to Sentry.
307
+
308
+ :param hint: Contains metadata about the event that can be read from `before_send`, such as the original exception object or a HTTP request object.
309
+
310
+ :param scope: An optional :py:class:`sentry_sdk.Scope` to apply to events.
311
+ The `scope` and `scope_kwargs` parameters are mutually exclusive.
338
312
 
339
- :returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.Client.capture_event`).
313
+ :param scope_kwargs: Optional data to apply to event.
314
+ For supported `**scope_kwargs` see :py:meth:`sentry_sdk.Scope.update_from_kwargs`.
315
+ The `scope` and `scope_kwargs` parameters are mutually exclusive.
340
316
  """
341
- if self.client is None:
342
- return None
343
- if level is None:
344
- level = "info"
345
- return self.capture_event(
346
- {"message": message, "level": level}, scope=scope, **scope_args
317
+ last_event_id = get_current_scope().capture_event(
318
+ event, hint, scope=scope, **scope_kwargs
347
319
  )
348
320
 
349
- def capture_exception(
350
- self,
351
- error=None, # type: Optional[Union[BaseException, ExcInfo]]
352
- scope=None, # type: Optional[Any]
353
- **scope_args # type: Dict[str, Any]
354
- ):
355
- # type: (...) -> Optional[str]
356
- """Captures an exception.
321
+ is_transaction = event.get("type") == "transaction"
322
+ if last_event_id is not None and not is_transaction:
323
+ self._last_event_id = last_event_id
357
324
 
358
- :param error: An exception to catch. If `None`, `sys.exc_info()` will be used.
325
+ return last_event_id
359
326
 
360
- :returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.Client.capture_event`).
327
+ def capture_message(self, message, level=None, scope=None, **scope_kwargs):
328
+ # type: (str, Optional[LogLevelStr], Optional[Scope], Any) -> Optional[str]
361
329
  """
362
- client = self.client
363
- if client is None:
364
- return None
365
- if error is not None:
366
- exc_info = exc_info_from_error(error)
367
- else:
368
- exc_info = sys.exc_info()
330
+ .. deprecated:: 2.0.0
331
+ This function is deprecated and will be removed in a future release.
332
+ Please use :py:meth:`sentry_sdk.Scope.capture_message` instead.
369
333
 
370
- event, hint = event_from_exception(exc_info, client_options=client.options)
371
- try:
372
- return self.capture_event(event, hint=hint, scope=scope, **scope_args)
373
- except Exception:
374
- self._capture_internal_exception(sys.exc_info())
334
+ Captures a message.
375
335
 
376
- return None
336
+ Alias of :py:meth:`sentry_sdk.Scope.capture_message`.
377
337
 
378
- def _capture_internal_exception(
379
- self, exc_info # type: Any
380
- ):
381
- # type: (...) -> Any
382
- """
383
- Capture an exception that is likely caused by a bug in the SDK
384
- itself.
338
+ :param message: The string to send as the message to Sentry.
339
+
340
+ :param level: If no level is provided, the default level is `info`.
341
+
342
+ :param scope: An optional :py:class:`sentry_sdk.Scope` to apply to events.
343
+ The `scope` and `scope_kwargs` parameters are mutually exclusive.
344
+
345
+ :param scope_kwargs: Optional data to apply to event.
346
+ For supported `**scope_kwargs` see :py:meth:`sentry_sdk.Scope.update_from_kwargs`.
347
+ The `scope` and `scope_kwargs` parameters are mutually exclusive.
385
348
 
386
- These exceptions do not end up in Sentry and are just logged instead.
349
+ :returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.client._Client.capture_event`).
387
350
  """
388
- logger.error("Internal error in sentry_sdk", exc_info=exc_info)
351
+ last_event_id = get_current_scope().capture_message(
352
+ message, level=level, scope=scope, **scope_kwargs
353
+ )
389
354
 
390
- def add_breadcrumb(
391
- self,
392
- crumb=None, # type: Optional[Breadcrumb]
393
- hint=None, # type: Optional[BreadcrumbHint]
394
- **kwargs # type: Any
395
- ):
396
- # type: (...) -> None
355
+ if last_event_id is not None:
356
+ self._last_event_id = last_event_id
357
+
358
+ return last_event_id
359
+
360
+ def capture_exception(self, error=None, scope=None, **scope_kwargs):
361
+ # type: (Optional[Union[BaseException, ExcInfo]], Optional[Scope], Any) -> Optional[str]
397
362
  """
398
- Adds a breadcrumb.
363
+ .. deprecated:: 2.0.0
364
+ This function is deprecated and will be removed in a future release.
365
+ Please use :py:meth:`sentry_sdk.Scope.capture_exception` instead.
399
366
 
400
- :param crumb: Dictionary with the data as the sentry v7/v8 protocol expects.
367
+ Captures an exception.
401
368
 
402
- :param hint: An optional value that can be used by `before_breadcrumb`
403
- to customize the breadcrumbs that are emitted.
369
+ Alias of :py:meth:`sentry_sdk.Scope.capture_exception`.
370
+
371
+ :param error: An exception to capture. If `None`, `sys.exc_info()` will be used.
372
+
373
+ :param scope: An optional :py:class:`sentry_sdk.Scope` to apply to events.
374
+ The `scope` and `scope_kwargs` parameters are mutually exclusive.
375
+
376
+ :param scope_kwargs: Optional data to apply to event.
377
+ For supported `**scope_kwargs` see :py:meth:`sentry_sdk.Scope.update_from_kwargs`.
378
+ The `scope` and `scope_kwargs` parameters are mutually exclusive.
379
+
380
+ :returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.client._Client.capture_event`).
404
381
  """
405
- client, scope = self._stack[-1]
406
- if client is None:
407
- logger.info("Dropped breadcrumb because no client bound")
408
- return
382
+ last_event_id = get_current_scope().capture_exception(
383
+ error, scope=scope, **scope_kwargs
384
+ )
409
385
 
410
- crumb = dict(crumb or ()) # type: Breadcrumb
411
- crumb.update(kwargs)
412
- if not crumb:
413
- return
386
+ if last_event_id is not None:
387
+ self._last_event_id = last_event_id
414
388
 
415
- hint = dict(hint or ()) # type: Hint
389
+ return last_event_id
416
390
 
417
- if crumb.get("timestamp") is None:
418
- crumb["timestamp"] = datetime.utcnow()
419
- if crumb.get("type") is None:
420
- crumb["type"] = "default"
391
+ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
392
+ # type: (Optional[Breadcrumb], Optional[BreadcrumbHint], Any) -> None
393
+ """
394
+ .. deprecated:: 2.0.0
395
+ This function is deprecated and will be removed in a future release.
396
+ Please use :py:meth:`sentry_sdk.Scope.add_breadcrumb` instead.
421
397
 
422
- if client.options["before_breadcrumb"] is not None:
423
- new_crumb = client.options["before_breadcrumb"](crumb, hint)
424
- else:
425
- new_crumb = crumb
398
+ Adds a breadcrumb.
426
399
 
427
- if new_crumb is not None:
428
- scope._breadcrumbs.append(new_crumb)
429
- else:
430
- logger.info("before breadcrumb dropped breadcrumb (%s)", crumb)
400
+ :param crumb: Dictionary with the data as the sentry v7/v8 protocol expects.
431
401
 
432
- max_breadcrumbs = client.options["max_breadcrumbs"] # type: int
433
- while len(scope._breadcrumbs) > max_breadcrumbs:
434
- scope._breadcrumbs.popleft()
402
+ :param hint: An optional value that can be used by `before_breadcrumb`
403
+ to customize the breadcrumbs that are emitted.
404
+ """
405
+ get_isolation_scope().add_breadcrumb(crumb, hint, **kwargs)
435
406
 
436
- def start_span(
437
- self,
438
- span=None, # type: Optional[Span]
439
- **kwargs # type: Any
440
- ):
441
- # type: (...) -> Span
407
+ def start_span(self, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
408
+ # type: (str, Any) -> Span
442
409
  """
443
- Create and start timing a new span whose parent is the currently active
444
- span or transaction, if any. The return value is a span instance,
410
+ .. deprecated:: 2.0.0
411
+ This function is deprecated and will be removed in a future release.
412
+ Please use :py:meth:`sentry_sdk.Scope.start_span` instead.
413
+
414
+ Start a span whose parent is the currently active span or transaction, if any.
415
+
416
+ The return value is a :py:class:`sentry_sdk.tracing.Span` instance,
445
417
  typically used as a context manager to start and stop timing in a `with`
446
418
  block.
447
419
 
448
420
  Only spans contained in a transaction are sent to Sentry. Most
449
421
  integrations start a transaction at the appropriate time, for example
450
- for every incoming HTTP request. Use `start_transaction` to start a new
451
- transaction when one is not already in progress.
452
- """
453
- # TODO: consider removing this in a future release.
454
- # This is for backwards compatibility with releases before
455
- # start_transaction existed, to allow for a smoother transition.
456
- if isinstance(span, Transaction) or "transaction" in kwargs:
457
- deprecation_msg = (
458
- "Deprecated: use start_transaction to start transactions and "
459
- "Transaction.start_child to start spans."
460
- )
461
- if isinstance(span, Transaction):
462
- logger.warning(deprecation_msg)
463
- return self.start_transaction(span)
464
- if "transaction" in kwargs:
465
- logger.warning(deprecation_msg)
466
- name = kwargs.pop("transaction")
467
- return self.start_transaction(name=name, **kwargs)
468
-
469
- if span is not None:
470
- return span
471
-
472
- kwargs.setdefault("hub", self)
473
-
474
- span = self.scope.span
475
- if span is not None:
476
- return span.start_child(**kwargs)
422
+ for every incoming HTTP request. Use
423
+ :py:meth:`sentry_sdk.start_transaction` to start a new transaction when
424
+ one is not already in progress.
477
425
 
478
- return Span(**kwargs)
426
+ For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
427
+ """
428
+ scope = get_current_scope()
429
+ return scope.start_span(instrumenter=instrumenter, **kwargs)
479
430
 
480
431
  def start_transaction(
481
432
  self,
482
- transaction=None, # type: Optional[Transaction]
483
- **kwargs # type: Any
433
+ transaction=None,
434
+ instrumenter=INSTRUMENTER.SENTRY,
435
+ custom_sampling_context=None,
436
+ **kwargs,
484
437
  ):
485
- # type: (...) -> Transaction
438
+ # type: (Optional[Transaction], str, Optional[SamplingContext], Unpack[TransactionKwargs]) -> Union[Transaction, NoOpSpan]
486
439
  """
440
+ .. deprecated:: 2.0.0
441
+ This function is deprecated and will be removed in a future release.
442
+ Please use :py:meth:`sentry_sdk.Scope.start_transaction` instead.
443
+
487
444
  Start and return a transaction.
488
445
 
489
446
  Start an existing transaction if given, otherwise create and start a new
@@ -504,44 +461,59 @@ class Hub(with_metaclass(HubMeta)): # type: ignore
504
461
 
505
462
  When the transaction is finished, it will be sent to Sentry with all its
506
463
  finished child spans.
464
+
465
+ For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
507
466
  """
508
- if transaction is None:
509
- kwargs.setdefault("hub", self)
510
- transaction = Transaction(**kwargs)
467
+ scope = get_current_scope()
511
468
 
512
- client, scope = self._stack[-1]
469
+ # For backwards compatibility, we allow passing the scope as the hub.
470
+ # We need a major release to make this nice. (if someone searches the code: deprecated)
471
+ # Type checking disabled for this line because deprecated keys are not allowed in the type signature.
472
+ kwargs["hub"] = scope # type: ignore
513
473
 
514
- if transaction.sampled is None:
515
- sample_rate = client and client.options["traces_sample_rate"] or 0
516
- transaction.sampled = random.random() < sample_rate
474
+ return scope.start_transaction(
475
+ transaction, instrumenter, custom_sampling_context, **kwargs
476
+ )
517
477
 
518
- if transaction.sampled:
519
- max_spans = (
520
- client and client.options["_experiments"].get("max_spans") or 1000
521
- )
522
- transaction.init_span_recorder(maxlen=max_spans)
478
+ def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
479
+ # type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
480
+ """
481
+ .. deprecated:: 2.0.0
482
+ This function is deprecated and will be removed in a future release.
483
+ Please use :py:meth:`sentry_sdk.Scope.continue_trace` instead.
523
484
 
524
- return transaction
485
+ Sets the propagation context from environment or headers and returns a transaction.
486
+ """
487
+ return get_isolation_scope().continue_trace(
488
+ environ_or_headers=environ_or_headers, op=op, name=name, source=source
489
+ )
525
490
 
526
491
  @overload
527
- def push_scope( # noqa: F811
528
- self, callback=None # type: Optional[None]
492
+ def push_scope(
493
+ self,
494
+ callback=None, # type: Optional[None]
529
495
  ):
530
496
  # type: (...) -> ContextManager[Scope]
531
497
  pass
532
498
 
533
499
  @overload
534
500
  def push_scope( # noqa: F811
535
- self, callback # type: Callable[[Scope], None]
501
+ self,
502
+ callback, # type: Callable[[Scope], None]
536
503
  ):
537
504
  # type: (...) -> None
538
505
  pass
539
506
 
540
507
  def push_scope( # noqa
541
- self, callback=None # type: Optional[Callable[[Scope], None]]
508
+ self,
509
+ callback=None, # type: Optional[Callable[[Scope], None]]
510
+ continue_trace=True, # type: bool
542
511
  ):
543
512
  # type: (...) -> Optional[ContextManager[Scope]]
544
513
  """
514
+ .. deprecated:: 2.0.0
515
+ This function is deprecated and will be removed in a future release.
516
+
545
517
  Pushes a new layer on the scope stack.
546
518
 
547
519
  :param callback: If provided, this method pushes a scope, calls
@@ -555,15 +527,14 @@ class Hub(with_metaclass(HubMeta)): # type: ignore
555
527
  callback(scope)
556
528
  return None
557
529
 
558
- client, scope = self._stack[-1]
559
- new_layer = (client, copy.copy(scope))
560
- self._stack.append(new_layer)
561
-
562
530
  return _ScopeManager(self)
563
531
 
564
532
  def pop_scope_unsafe(self):
565
533
  # type: () -> Tuple[Optional[Client], Scope]
566
534
  """
535
+ .. deprecated:: 2.0.0
536
+ This function is deprecated and will be removed in a future release.
537
+
567
538
  Pops a scope layer from the stack.
568
539
 
569
540
  Try to use the context manager :py:meth:`push_scope` instead.
@@ -573,90 +544,108 @@ class Hub(with_metaclass(HubMeta)): # type: ignore
573
544
  return rv
574
545
 
575
546
  @overload
576
- def configure_scope( # noqa: F811
577
- self, callback=None # type: Optional[None]
547
+ def configure_scope(
548
+ self,
549
+ callback=None, # type: Optional[None]
578
550
  ):
579
551
  # type: (...) -> ContextManager[Scope]
580
552
  pass
581
553
 
582
554
  @overload
583
555
  def configure_scope( # noqa: F811
584
- self, callback # type: Callable[[Scope], None]
556
+ self,
557
+ callback, # type: Callable[[Scope], None]
585
558
  ):
586
559
  # type: (...) -> None
587
560
  pass
588
561
 
589
562
  def configure_scope( # noqa
590
- self, callback=None # type: Optional[Callable[[Scope], None]]
591
- ): # noqa
563
+ self,
564
+ callback=None, # type: Optional[Callable[[Scope], None]]
565
+ continue_trace=True, # type: bool
566
+ ):
592
567
  # type: (...) -> Optional[ContextManager[Scope]]
593
-
594
568
  """
569
+ .. deprecated:: 2.0.0
570
+ This function is deprecated and will be removed in a future release.
571
+
595
572
  Reconfigures the scope.
596
573
 
597
574
  :param callback: If provided, call the callback with the current scope.
598
575
 
599
576
  :returns: If no callback is provided, returns a context manager that returns the scope.
600
577
  """
578
+ scope = get_isolation_scope()
579
+
580
+ if continue_trace:
581
+ scope.generate_propagation_context()
601
582
 
602
- client, scope = self._stack[-1]
603
583
  if callback is not None:
604
- if client is not None:
605
- callback(scope)
584
+ # TODO: used to return None when client is None. Check if this changes behavior.
585
+ callback(scope)
606
586
 
607
587
  return None
608
588
 
609
589
  @contextmanager
610
590
  def inner():
611
591
  # type: () -> Generator[Scope, None, None]
612
- if client is not None:
613
- yield scope
614
- else:
615
- yield Scope()
592
+ yield scope
616
593
 
617
594
  return inner()
618
595
 
619
- def start_session(self):
596
+ def start_session(
597
+ self,
598
+ session_mode="application", # type: str
599
+ ):
620
600
  # type: (...) -> None
621
- """Starts a new session."""
622
- self.end_session()
623
- client, scope = self._stack[-1]
624
- scope._session = Session(
625
- release=client.options["release"] if client else None,
626
- environment=client.options["environment"] if client else None,
627
- user=scope._user,
601
+ """
602
+ .. deprecated:: 2.0.0
603
+ This function is deprecated and will be removed in a future release.
604
+ Please use :py:meth:`sentry_sdk.Scope.start_session` instead.
605
+
606
+ Starts a new session.
607
+ """
608
+ get_isolation_scope().start_session(
609
+ session_mode=session_mode,
628
610
  )
629
611
 
630
612
  def end_session(self):
631
613
  # type: (...) -> None
632
- """Ends the current session if there is one."""
633
- client, scope = self._stack[-1]
634
- session = scope._session
635
- if session is not None:
636
- session.close()
637
- if client is not None:
638
- client.capture_session(session)
639
- self.scope._session = None
614
+ """
615
+ .. deprecated:: 2.0.0
616
+ This function is deprecated and will be removed in a future release.
617
+ Please use :py:meth:`sentry_sdk.Scope.end_session` instead.
618
+
619
+ Ends the current session if there is one.
620
+ """
621
+ get_isolation_scope().end_session()
640
622
 
641
623
  def stop_auto_session_tracking(self):
642
624
  # type: (...) -> None
643
- """Stops automatic session tracking.
625
+ """
626
+ .. deprecated:: 2.0.0
627
+ This function is deprecated and will be removed in a future release.
628
+ Please use :py:meth:`sentry_sdk.Scope.stop_auto_session_tracking` instead.
629
+
630
+ Stops automatic session tracking.
644
631
 
645
632
  This temporarily session tracking for the current scope when called.
646
633
  To resume session tracking call `resume_auto_session_tracking`.
647
634
  """
648
- self.end_session()
649
- client, scope = self._stack[-1]
650
- scope._force_auto_session_tracking = False
635
+ get_isolation_scope().stop_auto_session_tracking()
651
636
 
652
637
  def resume_auto_session_tracking(self):
653
638
  # type: (...) -> None
654
- """Resumes automatic session tracking for the current scope if
639
+ """
640
+ .. deprecated:: 2.0.0
641
+ This function is deprecated and will be removed in a future release.
642
+ Please use :py:meth:`sentry_sdk.Scope.resume_auto_session_tracking` instead.
643
+
644
+ Resumes automatic session tracking for the current scope if
655
645
  disabled earlier. This requires that generally automatic session
656
646
  tracking is enabled.
657
647
  """
658
- client, scope = self._stack[-1]
659
- scope._force_auto_session_tracking = None
648
+ get_isolation_scope().resume_auto_session_tracking()
660
649
 
661
650
  def flush(
662
651
  self,
@@ -665,27 +654,94 @@ class Hub(with_metaclass(HubMeta)): # type: ignore
665
654
  ):
666
655
  # type: (...) -> None
667
656
  """
668
- Alias for :py:meth:`sentry_sdk.Client.flush`
657
+ .. deprecated:: 2.0.0
658
+ This function is deprecated and will be removed in a future release.
659
+ Please use :py:meth:`sentry_sdk.client._Client.flush` instead.
660
+
661
+ Alias for :py:meth:`sentry_sdk.client._Client.flush`
662
+ """
663
+ return get_client().flush(timeout=timeout, callback=callback)
664
+
665
+ def get_traceparent(self):
666
+ # type: () -> Optional[str]
667
+ """
668
+ .. deprecated:: 2.0.0
669
+ This function is deprecated and will be removed in a future release.
670
+ Please use :py:meth:`sentry_sdk.Scope.get_traceparent` instead.
671
+
672
+ Returns the traceparent either from the active span or from the scope.
673
+ """
674
+ current_scope = get_current_scope()
675
+ traceparent = current_scope.get_traceparent()
676
+
677
+ if traceparent is None:
678
+ isolation_scope = get_isolation_scope()
679
+ traceparent = isolation_scope.get_traceparent()
680
+
681
+ return traceparent
682
+
683
+ def get_baggage(self):
684
+ # type: () -> Optional[str]
685
+ """
686
+ .. deprecated:: 2.0.0
687
+ This function is deprecated and will be removed in a future release.
688
+ Please use :py:meth:`sentry_sdk.Scope.get_baggage` instead.
689
+
690
+ Returns Baggage either from the active span or from the scope.
691
+ """
692
+ current_scope = get_current_scope()
693
+ baggage = current_scope.get_baggage()
694
+
695
+ if baggage is None:
696
+ isolation_scope = get_isolation_scope()
697
+ baggage = isolation_scope.get_baggage()
698
+
699
+ if baggage is not None:
700
+ return baggage.serialize()
701
+
702
+ return None
703
+
704
+ def iter_trace_propagation_headers(self, span=None):
705
+ # type: (Optional[Span]) -> Generator[Tuple[str, str], None, None]
669
706
  """
670
- client, scope = self._stack[-1]
671
- if client is not None:
672
- return client.flush(timeout=timeout, callback=callback)
707
+ .. deprecated:: 2.0.0
708
+ This function is deprecated and will be removed in a future release.
709
+ Please use :py:meth:`sentry_sdk.Scope.iter_trace_propagation_headers` instead.
673
710
 
674
- def iter_trace_propagation_headers(self):
675
- # type: () -> Generator[Tuple[str, str], None, None]
676
- # TODO: Document
677
- client, scope = self._stack[-1]
678
- span = scope.span
711
+ Return HTTP headers which allow propagation of trace data. Data taken
712
+ from the span representing the request, if available, or the current
713
+ span on the scope if not.
714
+ """
715
+ return get_current_scope().iter_trace_propagation_headers(
716
+ span=span,
717
+ )
679
718
 
680
- if span is None:
681
- return
719
+ def trace_propagation_meta(self, span=None):
720
+ # type: (Optional[Span]) -> str
721
+ """
722
+ .. deprecated:: 2.0.0
723
+ This function is deprecated and will be removed in a future release.
724
+ Please use :py:meth:`sentry_sdk.Scope.trace_propagation_meta` instead.
682
725
 
683
- propagate_traces = client and client.options["propagate_traces"]
684
- if not propagate_traces:
685
- return
726
+ Return meta tags which should be injected into HTML templates
727
+ to allow propagation of trace information.
728
+ """
729
+ if span is not None:
730
+ logger.warning(
731
+ "The parameter `span` in trace_propagation_meta() is deprecated and will be removed in the future."
732
+ )
686
733
 
687
- yield "sentry-trace", span.to_traceparent()
734
+ return get_current_scope().trace_propagation_meta(
735
+ span=span,
736
+ )
688
737
 
689
738
 
690
- GLOBAL_HUB = Hub()
739
+ with _suppress_hub_deprecation_warning():
740
+ # Suppress deprecation warning for the Hub here, since we still always
741
+ # import this module.
742
+ GLOBAL_HUB = Hub()
691
743
  _local.set(GLOBAL_HUB)
744
+
745
+
746
+ # Circular imports
747
+ from sentry_sdk import scope