api.py 15 KB

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