api.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. import inspect
  2. import warnings
  3. from contextlib import contextmanager
  4. from sentry_sdk import tracing_utils, Client
  5. from sentry_sdk._init_implementation import init
  6. from sentry_sdk.consts import INSTRUMENTER
  7. from sentry_sdk.scope import Scope, _ScopeManager, new_scope, isolation_scope
  8. from sentry_sdk.traces import StreamedSpan
  9. from sentry_sdk.tracing import NoOpSpan, Transaction, trace
  10. from sentry_sdk.crons import monitor
  11. from typing import TYPE_CHECKING
  12. if TYPE_CHECKING:
  13. from collections.abc import Mapping
  14. from typing import Any
  15. from typing import Dict
  16. from typing import Generator
  17. from typing import Optional
  18. from typing import overload
  19. from typing import Callable
  20. from typing import TypeVar
  21. from typing import ContextManager
  22. from typing import Union
  23. from typing_extensions import Unpack
  24. from sentry_sdk.client import BaseClient
  25. from sentry_sdk._types import (
  26. Event,
  27. Hint,
  28. Breadcrumb,
  29. BreadcrumbHint,
  30. ExcInfo,
  31. MeasurementUnit,
  32. LogLevelStr,
  33. SamplingContext,
  34. )
  35. from sentry_sdk.traces import StreamedSpan
  36. from sentry_sdk.tracing import Span, TransactionKwargs
  37. T = TypeVar("T")
  38. F = TypeVar("F", bound=Callable[..., Any])
  39. else:
  40. def overload(x: "T") -> "T":
  41. return x
  42. # When changing this, update __all__ in __init__.py too
  43. __all__ = [
  44. "init",
  45. "add_attachment",
  46. "add_breadcrumb",
  47. "capture_event",
  48. "capture_exception",
  49. "capture_message",
  50. "configure_scope",
  51. "continue_trace",
  52. "flush",
  53. "flush_async",
  54. "get_baggage",
  55. "get_client",
  56. "get_global_scope",
  57. "get_isolation_scope",
  58. "get_current_scope",
  59. "get_current_span",
  60. "get_traceparent",
  61. "is_initialized",
  62. "isolation_scope",
  63. "last_event_id",
  64. "new_scope",
  65. "push_scope",
  66. "remove_attribute",
  67. "set_attribute",
  68. "set_context",
  69. "set_extra",
  70. "set_level",
  71. "set_measurement",
  72. "set_tag",
  73. "set_tags",
  74. "set_user",
  75. "start_span",
  76. "start_transaction",
  77. "trace",
  78. "monitor",
  79. "start_session",
  80. "end_session",
  81. "set_transaction_name",
  82. "update_current_span",
  83. ]
  84. def scopemethod(f: "F") -> "F":
  85. f.__doc__ = "%s\n\n%s" % (
  86. "Alias for :py:meth:`sentry_sdk.Scope.%s`" % f.__name__,
  87. inspect.getdoc(getattr(Scope, f.__name__)),
  88. )
  89. return f
  90. def clientmethod(f: "F") -> "F":
  91. f.__doc__ = "%s\n\n%s" % (
  92. "Alias for :py:meth:`sentry_sdk.Client.%s`" % f.__name__,
  93. inspect.getdoc(getattr(Client, f.__name__)),
  94. )
  95. return f
  96. @scopemethod
  97. def get_client() -> "BaseClient":
  98. return Scope.get_client()
  99. def is_initialized() -> bool:
  100. """
  101. .. versionadded:: 2.0.0
  102. Returns whether Sentry has been initialized or not.
  103. If a client is available and the client is active
  104. (meaning it is configured to send data) then
  105. Sentry is initialized.
  106. """
  107. return get_client().is_active()
  108. @scopemethod
  109. def get_global_scope() -> "Scope":
  110. return Scope.get_global_scope()
  111. @scopemethod
  112. def get_isolation_scope() -> "Scope":
  113. return Scope.get_isolation_scope()
  114. @scopemethod
  115. def get_current_scope() -> "Scope":
  116. return Scope.get_current_scope()
  117. @scopemethod
  118. def last_event_id() -> "Optional[str]":
  119. """
  120. See :py:meth:`sentry_sdk.Scope.last_event_id` documentation regarding
  121. this method's limitations.
  122. """
  123. return Scope.last_event_id()
  124. @scopemethod
  125. def capture_event(
  126. event: "Event",
  127. hint: "Optional[Hint]" = None,
  128. scope: "Optional[Any]" = None,
  129. **scope_kwargs: "Any",
  130. ) -> "Optional[str]":
  131. return get_current_scope().capture_event(event, hint, scope=scope, **scope_kwargs)
  132. @scopemethod
  133. def capture_message(
  134. message: str,
  135. level: "Optional[LogLevelStr]" = None,
  136. scope: "Optional[Any]" = None,
  137. **scope_kwargs: "Any",
  138. ) -> "Optional[str]":
  139. return get_current_scope().capture_message(
  140. message, level, scope=scope, **scope_kwargs
  141. )
  142. @scopemethod
  143. def capture_exception(
  144. error: "Optional[Union[BaseException, ExcInfo]]" = None,
  145. scope: "Optional[Any]" = None,
  146. **scope_kwargs: "Any",
  147. ) -> "Optional[str]":
  148. return get_current_scope().capture_exception(error, scope=scope, **scope_kwargs)
  149. @scopemethod
  150. def add_attachment(
  151. bytes: "Union[None, bytes, Callable[[], bytes]]" = None,
  152. filename: "Optional[str]" = None,
  153. path: "Optional[str]" = None,
  154. content_type: "Optional[str]" = None,
  155. add_to_transactions: bool = False,
  156. ) -> None:
  157. return get_isolation_scope().add_attachment(
  158. bytes, filename, path, content_type, add_to_transactions
  159. )
  160. @scopemethod
  161. def add_breadcrumb(
  162. crumb: "Optional[Breadcrumb]" = None,
  163. hint: "Optional[BreadcrumbHint]" = None,
  164. **kwargs: "Any",
  165. ) -> None:
  166. return get_isolation_scope().add_breadcrumb(crumb, hint, **kwargs)
  167. @overload
  168. def configure_scope() -> "ContextManager[Scope]":
  169. pass
  170. @overload
  171. def configure_scope( # noqa: F811
  172. callback: "Callable[[Scope], None]",
  173. ) -> None:
  174. pass
  175. def configure_scope( # noqa: F811
  176. callback: "Optional[Callable[[Scope], None]]" = None,
  177. ) -> "Optional[ContextManager[Scope]]":
  178. """
  179. Reconfigures the scope.
  180. :param callback: If provided, call the callback with the current scope.
  181. :returns: If no callback is provided, returns a context manager that returns the scope.
  182. """
  183. warnings.warn(
  184. "sentry_sdk.configure_scope is deprecated and will be removed in the next major version. "
  185. "Please consult our migration guide to learn how to migrate to the new API: "
  186. "https://docs.sentry.io/platforms/python/migration/1.x-to-2.x#scope-configuring",
  187. DeprecationWarning,
  188. stacklevel=2,
  189. )
  190. scope = get_isolation_scope()
  191. scope.generate_propagation_context()
  192. if callback is not None:
  193. # TODO: used to return None when client is None. Check if this changes behavior.
  194. callback(scope)
  195. return None
  196. @contextmanager
  197. def inner() -> "Generator[Scope, None, None]":
  198. yield scope
  199. return inner()
  200. @overload
  201. def push_scope() -> "ContextManager[Scope]":
  202. pass
  203. @overload
  204. def push_scope( # noqa: F811
  205. callback: "Callable[[Scope], None]",
  206. ) -> None:
  207. pass
  208. def push_scope( # noqa: F811
  209. callback: "Optional[Callable[[Scope], None]]" = None,
  210. ) -> "Optional[ContextManager[Scope]]":
  211. """
  212. Pushes a new layer on the scope stack.
  213. :param callback: If provided, this method pushes a scope, calls
  214. `callback`, and pops the scope again.
  215. :returns: If no `callback` is provided, a context manager that should
  216. be used to pop the scope again.
  217. """
  218. warnings.warn(
  219. "sentry_sdk.push_scope is deprecated and will be removed in the next major version. "
  220. "Please consult our migration guide to learn how to migrate to the new API: "
  221. "https://docs.sentry.io/platforms/python/migration/1.x-to-2.x#scope-pushing",
  222. DeprecationWarning,
  223. stacklevel=2,
  224. )
  225. if callback is not None:
  226. with warnings.catch_warnings():
  227. warnings.simplefilter("ignore", DeprecationWarning)
  228. with push_scope() as scope:
  229. callback(scope)
  230. return None
  231. return _ScopeManager()
  232. @scopemethod
  233. def set_attribute(attribute: str, value: "Any") -> None:
  234. """
  235. Set an attribute.
  236. Any attributes-based telemetry (logs, metrics) captured in this scope will
  237. include this attribute.
  238. """
  239. return get_isolation_scope().set_attribute(attribute, value)
  240. @scopemethod
  241. def remove_attribute(attribute: str) -> None:
  242. """
  243. Remove an attribute.
  244. If the attribute doesn't exist, this function will not have any effect and
  245. it will also not raise an exception.
  246. """
  247. return get_isolation_scope().remove_attribute(attribute)
  248. @scopemethod
  249. def set_tag(key: str, value: "Any") -> None:
  250. return get_isolation_scope().set_tag(key, value)
  251. @scopemethod
  252. def set_tags(tags: "Mapping[str, object]") -> None:
  253. return get_isolation_scope().set_tags(tags)
  254. @scopemethod
  255. def set_context(key: str, value: "Dict[str, Any]") -> None:
  256. return get_isolation_scope().set_context(key, value)
  257. @scopemethod
  258. def set_extra(key: str, value: "Any") -> None:
  259. return get_isolation_scope().set_extra(key, value)
  260. @scopemethod
  261. def set_user(value: "Optional[Dict[str, Any]]") -> None:
  262. return get_isolation_scope().set_user(value)
  263. @scopemethod
  264. def set_level(value: "LogLevelStr") -> None:
  265. return get_isolation_scope().set_level(value)
  266. @clientmethod
  267. def flush(
  268. timeout: "Optional[float]" = None,
  269. callback: "Optional[Callable[[int, float], None]]" = None,
  270. ) -> None:
  271. return get_client().flush(timeout=timeout, callback=callback)
  272. @clientmethod
  273. async def flush_async(
  274. timeout: "Optional[float]" = None,
  275. callback: "Optional[Callable[[int, float], None]]" = None,
  276. ) -> None:
  277. return await get_client().flush_async(timeout=timeout, callback=callback)
  278. @scopemethod
  279. def start_span(
  280. **kwargs: "Any",
  281. ) -> "Span":
  282. return get_current_scope().start_span(**kwargs)
  283. @scopemethod
  284. def start_transaction(
  285. transaction: "Optional[Transaction]" = None,
  286. instrumenter: str = INSTRUMENTER.SENTRY,
  287. custom_sampling_context: "Optional[SamplingContext]" = None,
  288. **kwargs: "Unpack[TransactionKwargs]",
  289. ) -> "Union[Transaction, NoOpSpan]":
  290. """
  291. Start and return a transaction on the current scope.
  292. Start an existing transaction if given, otherwise create and start a new
  293. transaction with kwargs.
  294. This is the entry point to manual tracing instrumentation.
  295. A tree structure can be built by adding child spans to the transaction,
  296. and child spans to other spans. To start a new child span within the
  297. transaction or any span, call the respective `.start_child()` method.
  298. Every child span must be finished before the transaction is finished,
  299. otherwise the unfinished spans are discarded.
  300. When used as context managers, spans and transactions are automatically
  301. finished at the end of the `with` block. If not using context managers,
  302. call the `.finish()` method.
  303. When the transaction is finished, it will be sent to Sentry with all its
  304. finished child spans.
  305. :param transaction: The transaction to start. If omitted, we create and
  306. start a new transaction.
  307. :param instrumenter: This parameter is meant for internal use only. It
  308. will be removed in the next major version.
  309. :param custom_sampling_context: The transaction's custom sampling context.
  310. :param kwargs: Optional keyword arguments to be passed to the Transaction
  311. constructor. See :py:class:`sentry_sdk.tracing.Transaction` for
  312. available arguments.
  313. """
  314. return get_current_scope().start_transaction(
  315. transaction, instrumenter, custom_sampling_context, **kwargs
  316. )
  317. def set_measurement(name: str, value: float, unit: "MeasurementUnit" = "") -> None:
  318. """
  319. .. deprecated:: 2.28.0
  320. This function is deprecated and will be removed in the next major release.
  321. """
  322. transaction = get_current_scope().transaction
  323. if transaction is not None:
  324. transaction.set_measurement(name, value, unit)
  325. def get_current_span(
  326. scope: "Optional[Scope]" = None,
  327. ) -> "Optional[Union[Span, StreamedSpan]]":
  328. """
  329. Returns the currently active span if there is one running, otherwise `None`
  330. """
  331. return tracing_utils.get_current_span(scope)
  332. def get_traceparent() -> "Optional[str]":
  333. """
  334. Returns the traceparent either from the active span or from the scope.
  335. """
  336. return get_current_scope().get_traceparent()
  337. def get_baggage() -> "Optional[str]":
  338. """
  339. Returns Baggage either from the active span or from the scope.
  340. """
  341. baggage = get_current_scope().get_baggage()
  342. if baggage is not None:
  343. return baggage.serialize()
  344. return None
  345. def continue_trace(
  346. environ_or_headers: "Dict[str, Any]",
  347. op: "Optional[str]" = None,
  348. name: "Optional[str]" = None,
  349. source: "Optional[str]" = None,
  350. origin: str = "manual",
  351. ) -> "Transaction":
  352. """
  353. Sets the propagation context from environment or headers and returns a transaction.
  354. """
  355. return get_isolation_scope().continue_trace(
  356. environ_or_headers, op, name, source, origin
  357. )
  358. @scopemethod
  359. def start_session(
  360. session_mode: str = "application",
  361. ) -> None:
  362. return get_isolation_scope().start_session(session_mode=session_mode)
  363. @scopemethod
  364. def end_session() -> None:
  365. return get_isolation_scope().end_session()
  366. @scopemethod
  367. def set_transaction_name(name: str, source: "Optional[str]" = None) -> None:
  368. return get_current_scope().set_transaction_name(name, source)
  369. def update_current_span(
  370. op: "Optional[str]" = None,
  371. name: "Optional[str]" = None,
  372. attributes: "Optional[dict[str, Union[str, int, float, bool]]]" = None,
  373. data: "Optional[dict[str, Any]]" = None,
  374. ) -> None:
  375. """
  376. Update the current active span with the provided parameters.
  377. This function allows you to modify properties of the currently active span.
  378. If no span is currently active, this function will do nothing.
  379. :param op: The operation name for the span. This is a high-level description
  380. of what the span represents (e.g., "http.client", "db.query").
  381. You can use predefined constants from :py:class:`sentry_sdk.consts.OP`
  382. or provide your own string. If not provided, the span's operation will
  383. remain unchanged.
  384. :type op: str or None
  385. :param name: The human-readable name/description for the span. This provides
  386. more specific details about what the span represents (e.g., "GET /api/users",
  387. "SELECT * FROM users"). If not provided, the span's name will remain unchanged.
  388. :type name: str or None
  389. :param data: A dictionary of key-value pairs to add as data to the span. This
  390. data will be merged with any existing span data. If not provided,
  391. no data will be added.
  392. .. deprecated:: 2.35.0
  393. Use ``attributes`` instead. The ``data`` parameter will be removed
  394. in a future version.
  395. :type data: dict[str, Union[str, int, float, bool]] or None
  396. :param attributes: A dictionary of key-value pairs to add as attributes to the span.
  397. Attribute values must be strings, integers, floats, or booleans. These
  398. attributes will be merged with any existing span data. If not provided,
  399. no attributes will be added.
  400. :type attributes: dict[str, Union[str, int, float, bool]] or None
  401. :returns: None
  402. .. versionadded:: 2.35.0
  403. Example::
  404. import sentry_sdk
  405. from sentry_sdk.consts import OP
  406. sentry_sdk.update_current_span(
  407. op=OP.FUNCTION,
  408. name="process_user_data",
  409. attributes={"user_id": 123, "batch_size": 50}
  410. )
  411. """
  412. current_span = get_current_span()
  413. if current_span is None:
  414. return
  415. if isinstance(current_span, StreamedSpan):
  416. warnings.warn(
  417. "The `update_current_span` API isn't available in streaming mode. "
  418. "Retrieve the current span with get_current_span() and use its API "
  419. "directly.",
  420. DeprecationWarning,
  421. stacklevel=2,
  422. )
  423. return
  424. if op is not None:
  425. current_span.op = op
  426. if name is not None:
  427. # internally it is still description
  428. current_span.description = name
  429. if data is not None and attributes is not None:
  430. raise ValueError(
  431. "Cannot provide both `data` and `attributes`. Please use only `attributes`."
  432. )
  433. if data is not None:
  434. warnings.warn(
  435. "The `data` parameter is deprecated. Please use `attributes` instead.",
  436. DeprecationWarning,
  437. stacklevel=2,
  438. )
  439. attributes = data
  440. if attributes is not None:
  441. current_span.update_data(attributes)