__init__.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. # Copyright The OpenTelemetry Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. The OpenTelemetry tracing API describes the classes used to generate
  16. distributed traces.
  17. The :class:`.Tracer` class controls access to the execution context, and
  18. manages span creation. Each operation in a trace is represented by a
  19. :class:`.Span`, which records the start, end time, and metadata associated with
  20. the operation.
  21. This module provides abstract (i.e. unimplemented) classes required for
  22. tracing, and a concrete no-op :class:`.NonRecordingSpan` that allows applications
  23. to use the API package alone without a supporting implementation.
  24. To get a tracer, you need to provide the package name from which you are
  25. calling the tracer APIs to OpenTelemetry by calling `TracerProvider.get_tracer`
  26. with the calling module name and the version of your package.
  27. The tracer supports creating spans that are "attached" or "detached" from the
  28. context. New spans are "attached" to the context in that they are
  29. created as children of the currently active span, and the newly-created span
  30. can optionally become the new active span::
  31. from opentelemetry import trace
  32. tracer = trace.get_tracer(__name__)
  33. # Create a new root span, set it as the current span in context
  34. with tracer.start_as_current_span("parent"):
  35. # Attach a new child and update the current span
  36. with tracer.start_as_current_span("child"):
  37. do_work():
  38. # Close child span, set parent as current
  39. # Close parent span, set default span as current
  40. When creating a span that's "detached" from the context the active span doesn't
  41. change, and the caller is responsible for managing the span's lifetime::
  42. # Explicit parent span assignment is done via the Context
  43. from opentelemetry.trace import set_span_in_context
  44. context = set_span_in_context(parent)
  45. child = tracer.start_span("child", context=context)
  46. try:
  47. do_work(span=child)
  48. finally:
  49. child.end()
  50. Applications should generally use a single global TracerProvider, and use
  51. either implicit or explicit context propagation consistently throughout.
  52. .. versionadded:: 0.1.0
  53. .. versionchanged:: 0.3.0
  54. `TracerProvider` was introduced and the global ``tracer`` getter was
  55. replaced by ``tracer_provider``.
  56. .. versionchanged:: 0.5.0
  57. ``tracer_provider`` was replaced by `get_tracer_provider`,
  58. ``set_preferred_tracer_provider_implementation`` was replaced by
  59. `set_tracer_provider`.
  60. """
  61. import os
  62. import typing
  63. from abc import ABC, abstractmethod
  64. from enum import Enum
  65. from logging import getLogger
  66. from typing import Iterator, Optional, Sequence, cast
  67. from deprecated import deprecated
  68. from opentelemetry import context as context_api
  69. from opentelemetry.attributes import BoundedAttributes
  70. from opentelemetry.context.context import Context
  71. from opentelemetry.environment_variables import OTEL_PYTHON_TRACER_PROVIDER
  72. from opentelemetry.trace.propagation import (
  73. _SPAN_KEY,
  74. get_current_span,
  75. set_span_in_context,
  76. )
  77. from opentelemetry.trace.span import (
  78. DEFAULT_TRACE_OPTIONS,
  79. DEFAULT_TRACE_STATE,
  80. INVALID_SPAN,
  81. INVALID_SPAN_CONTEXT,
  82. INVALID_SPAN_ID,
  83. INVALID_TRACE_ID,
  84. NonRecordingSpan,
  85. Span,
  86. SpanContext,
  87. TraceFlags,
  88. TraceState,
  89. format_span_id,
  90. format_trace_id,
  91. )
  92. from opentelemetry.trace.status import Status, StatusCode
  93. from opentelemetry.util import types
  94. from opentelemetry.util._decorator import _agnosticcontextmanager
  95. from opentelemetry.util._once import Once
  96. from opentelemetry.util._providers import _load_provider
  97. logger = getLogger(__name__)
  98. class _LinkBase(ABC):
  99. def __init__(self, context: "SpanContext") -> None:
  100. self._context = context
  101. @property
  102. def context(self) -> "SpanContext":
  103. return self._context
  104. @property
  105. @abstractmethod
  106. def attributes(self) -> types.Attributes:
  107. pass
  108. class Link(_LinkBase):
  109. """A link to a `Span`. The attributes of a Link are immutable.
  110. Args:
  111. context: `SpanContext` of the `Span` to link to.
  112. attributes: Link's attributes.
  113. """
  114. def __init__(
  115. self,
  116. context: "SpanContext",
  117. attributes: types.Attributes = None,
  118. ) -> None:
  119. super().__init__(context)
  120. self._attributes = attributes
  121. @property
  122. def attributes(self) -> types.Attributes:
  123. return self._attributes
  124. @property
  125. def dropped_attributes(self) -> int:
  126. if isinstance(self._attributes, BoundedAttributes):
  127. return self._attributes.dropped
  128. return 0
  129. _Links = Optional[Sequence[Link]]
  130. class SpanKind(Enum):
  131. """Specifies additional details on how this span relates to its parent span.
  132. Note that this enumeration is experimental and likely to change. See
  133. https://github.com/open-telemetry/opentelemetry-specification/pull/226.
  134. """
  135. #: Default value. Indicates that the span is used internally in the
  136. # application.
  137. INTERNAL = 0
  138. #: Indicates that the span describes an operation that handles a remote
  139. # request.
  140. SERVER = 1
  141. #: Indicates that the span describes a request to some remote service.
  142. CLIENT = 2
  143. #: Indicates that the span describes a producer sending a message to a
  144. #: broker. Unlike client and server, there is usually no direct critical
  145. #: path latency relationship between producer and consumer spans.
  146. PRODUCER = 3
  147. #: Indicates that the span describes a consumer receiving a message from a
  148. #: broker. Unlike client and server, there is usually no direct critical
  149. #: path latency relationship between producer and consumer spans.
  150. CONSUMER = 4
  151. class TracerProvider(ABC):
  152. @abstractmethod
  153. def get_tracer(
  154. self,
  155. instrumenting_module_name: str,
  156. instrumenting_library_version: typing.Optional[str] = None,
  157. schema_url: typing.Optional[str] = None,
  158. attributes: typing.Optional[types.Attributes] = None,
  159. ) -> "Tracer":
  160. """Returns a `Tracer` for use by the given instrumentation library.
  161. For any two calls it is undefined whether the same or different
  162. `Tracer` instances are returned, even for different library names.
  163. This function may return different `Tracer` types (e.g. a no-op tracer
  164. vs. a functional tracer).
  165. Args:
  166. instrumenting_module_name: The uniquely identifiable name for instrumentation
  167. scope, such as instrumentation library, package, module or class name.
  168. ``__name__`` may not be used as this can result in
  169. different tracer names if the tracers are in different files.
  170. It is better to use a fixed string that can be imported where
  171. needed and used consistently as the name of the tracer.
  172. This should *not* be the name of the module that is
  173. instrumented but the name of the module doing the instrumentation.
  174. E.g., instead of ``"requests"``, use
  175. ``"opentelemetry.instrumentation.requests"``.
  176. instrumenting_library_version: Optional. The version string of the
  177. instrumenting library. Usually this should be the same as
  178. ``importlib.metadata.version(instrumenting_library_name)``.
  179. schema_url: Optional. Specifies the Schema URL of the emitted telemetry.
  180. attributes: Optional. Specifies the attributes of the emitted telemetry.
  181. """
  182. class NoOpTracerProvider(TracerProvider):
  183. """The default TracerProvider, used when no implementation is available.
  184. All operations are no-op.
  185. """
  186. def get_tracer(
  187. self,
  188. instrumenting_module_name: str,
  189. instrumenting_library_version: typing.Optional[str] = None,
  190. schema_url: typing.Optional[str] = None,
  191. attributes: typing.Optional[types.Attributes] = None,
  192. ) -> "Tracer":
  193. # pylint:disable=no-self-use,unused-argument
  194. return NoOpTracer()
  195. @deprecated(version="1.9.0", reason="You should use NoOpTracerProvider") # type: ignore
  196. class _DefaultTracerProvider(NoOpTracerProvider):
  197. """The default TracerProvider, used when no implementation is available.
  198. All operations are no-op.
  199. """
  200. class ProxyTracerProvider(TracerProvider):
  201. def get_tracer(
  202. self,
  203. instrumenting_module_name: str,
  204. instrumenting_library_version: typing.Optional[str] = None,
  205. schema_url: typing.Optional[str] = None,
  206. attributes: typing.Optional[types.Attributes] = None,
  207. ) -> "Tracer":
  208. if _TRACER_PROVIDER:
  209. return _TRACER_PROVIDER.get_tracer(
  210. instrumenting_module_name,
  211. instrumenting_library_version,
  212. schema_url,
  213. attributes,
  214. )
  215. return ProxyTracer(
  216. instrumenting_module_name,
  217. instrumenting_library_version,
  218. schema_url,
  219. attributes,
  220. )
  221. class Tracer(ABC):
  222. """Handles span creation and in-process context propagation.
  223. This class provides methods for manipulating the context, creating spans,
  224. and controlling spans' lifecycles.
  225. """
  226. @abstractmethod
  227. def start_span(
  228. self,
  229. name: str,
  230. context: Optional[Context] = None,
  231. kind: SpanKind = SpanKind.INTERNAL,
  232. attributes: types.Attributes = None,
  233. links: _Links = None,
  234. start_time: Optional[int] = None,
  235. record_exception: bool = True,
  236. set_status_on_exception: bool = True,
  237. ) -> "Span":
  238. """Starts a span.
  239. Create a new span. Start the span without setting it as the current
  240. span in the context. To start the span and use the context in a single
  241. method, see :meth:`start_as_current_span`.
  242. By default the current span in the context will be used as parent, but an
  243. explicit context can also be specified, by passing in a `Context` containing
  244. a current `Span`. If there is no current span in the global `Context` or in
  245. the specified context, the created span will be a root span.
  246. The span can be used as a context manager. On exiting the context manager,
  247. the span's end() method will be called.
  248. Example::
  249. # trace.get_current_span() will be used as the implicit parent.
  250. # If none is found, the created span will be a root instance.
  251. with tracer.start_span("one") as child:
  252. child.add_event("child's event")
  253. Args:
  254. name: The name of the span to be created.
  255. context: An optional Context containing the span's parent. Defaults to the
  256. global context.
  257. kind: The span's kind (relationship to parent). Note that is
  258. meaningful even if there is no parent.
  259. attributes: The span's attributes.
  260. links: Links span to other spans
  261. start_time: Sets the start time of a span
  262. record_exception: Whether to record any exceptions raised within the
  263. context as error event on the span.
  264. set_status_on_exception: Only relevant if the returned span is used
  265. in a with/context manager. Defines whether the span status will
  266. be automatically set to ERROR when an uncaught exception is
  267. raised in the span with block. The span status won't be set by
  268. this mechanism if it was previously set manually.
  269. Returns:
  270. The newly-created span.
  271. """
  272. @_agnosticcontextmanager
  273. @abstractmethod
  274. def start_as_current_span(
  275. self,
  276. name: str,
  277. context: Optional[Context] = None,
  278. kind: SpanKind = SpanKind.INTERNAL,
  279. attributes: types.Attributes = None,
  280. links: _Links = None,
  281. start_time: Optional[int] = None,
  282. record_exception: bool = True,
  283. set_status_on_exception: bool = True,
  284. end_on_exit: bool = True,
  285. ) -> Iterator["Span"]:
  286. """Context manager for creating a new span and set it
  287. as the current span in this tracer's context.
  288. Exiting the context manager will call the span's end method,
  289. as well as return the current span to its previous value by
  290. returning to the previous context.
  291. Example::
  292. with tracer.start_as_current_span("one") as parent:
  293. parent.add_event("parent's event")
  294. with tracer.start_as_current_span("two") as child:
  295. child.add_event("child's event")
  296. trace.get_current_span() # returns child
  297. trace.get_current_span() # returns parent
  298. trace.get_current_span() # returns previously active span
  299. This is a convenience method for creating spans attached to the
  300. tracer's context. Applications that need more control over the span
  301. lifetime should use :meth:`start_span` instead. For example::
  302. with tracer.start_as_current_span(name) as span:
  303. do_work()
  304. is equivalent to::
  305. span = tracer.start_span(name)
  306. with opentelemetry.trace.use_span(span, end_on_exit=True):
  307. do_work()
  308. This can also be used as a decorator::
  309. @tracer.start_as_current_span("name")
  310. def function():
  311. ...
  312. function()
  313. Args:
  314. name: The name of the span to be created.
  315. context: An optional Context containing the span's parent. Defaults to the
  316. global context.
  317. kind: The span's kind (relationship to parent). Note that is
  318. meaningful even if there is no parent.
  319. attributes: The span's attributes.
  320. links: Links span to other spans
  321. start_time: Sets the start time of a span
  322. record_exception: Whether to record any exceptions raised within the
  323. context as error event on the span.
  324. set_status_on_exception: Only relevant if the returned span is used
  325. in a with/context manager. Defines whether the span status will
  326. be automatically set to ERROR when an uncaught exception is
  327. raised in the span with block. The span status won't be set by
  328. this mechanism if it was previously set manually.
  329. end_on_exit: Whether to end the span automatically when leaving the
  330. context manager.
  331. Yields:
  332. The newly-created span.
  333. """
  334. class ProxyTracer(Tracer):
  335. # pylint: disable=W0222,signature-differs
  336. def __init__(
  337. self,
  338. instrumenting_module_name: str,
  339. instrumenting_library_version: typing.Optional[str] = None,
  340. schema_url: typing.Optional[str] = None,
  341. attributes: typing.Optional[types.Attributes] = None,
  342. ):
  343. self._instrumenting_module_name = instrumenting_module_name
  344. self._instrumenting_library_version = instrumenting_library_version
  345. self._schema_url = schema_url
  346. self._attributes = attributes
  347. self._real_tracer: Optional[Tracer] = None
  348. self._noop_tracer = NoOpTracer()
  349. @property
  350. def _tracer(self) -> Tracer:
  351. if self._real_tracer:
  352. return self._real_tracer
  353. if _TRACER_PROVIDER:
  354. self._real_tracer = _TRACER_PROVIDER.get_tracer(
  355. self._instrumenting_module_name,
  356. self._instrumenting_library_version,
  357. self._schema_url,
  358. self._attributes,
  359. )
  360. return self._real_tracer
  361. return self._noop_tracer
  362. def start_span(self, *args, **kwargs) -> Span: # type: ignore
  363. return self._tracer.start_span(*args, **kwargs) # type: ignore
  364. @_agnosticcontextmanager # type: ignore
  365. def start_as_current_span(self, *args, **kwargs) -> Iterator[Span]:
  366. with self._tracer.start_as_current_span(*args, **kwargs) as span: # type: ignore
  367. yield span
  368. class NoOpTracer(Tracer):
  369. """The default Tracer, used when no Tracer implementation is available.
  370. All operations are no-op.
  371. """
  372. def start_span(
  373. self,
  374. name: str,
  375. context: Optional[Context] = None,
  376. kind: SpanKind = SpanKind.INTERNAL,
  377. attributes: types.Attributes = None,
  378. links: _Links = None,
  379. start_time: Optional[int] = None,
  380. record_exception: bool = True,
  381. set_status_on_exception: bool = True,
  382. ) -> "Span":
  383. return INVALID_SPAN
  384. @_agnosticcontextmanager
  385. def start_as_current_span(
  386. self,
  387. name: str,
  388. context: Optional[Context] = None,
  389. kind: SpanKind = SpanKind.INTERNAL,
  390. attributes: types.Attributes = None,
  391. links: _Links = None,
  392. start_time: Optional[int] = None,
  393. record_exception: bool = True,
  394. set_status_on_exception: bool = True,
  395. end_on_exit: bool = True,
  396. ) -> Iterator["Span"]:
  397. yield INVALID_SPAN
  398. @deprecated(version="1.9.0", reason="You should use NoOpTracer") # type: ignore
  399. class _DefaultTracer(NoOpTracer):
  400. """The default Tracer, used when no Tracer implementation is available.
  401. All operations are no-op.
  402. """
  403. _TRACER_PROVIDER_SET_ONCE = Once()
  404. _TRACER_PROVIDER: Optional[TracerProvider] = None
  405. _PROXY_TRACER_PROVIDER = ProxyTracerProvider()
  406. def get_tracer(
  407. instrumenting_module_name: str,
  408. instrumenting_library_version: typing.Optional[str] = None,
  409. tracer_provider: Optional[TracerProvider] = None,
  410. schema_url: typing.Optional[str] = None,
  411. attributes: typing.Optional[types.Attributes] = None,
  412. ) -> "Tracer":
  413. """Returns a `Tracer` for use by the given instrumentation library.
  414. This function is a convenience wrapper for
  415. opentelemetry.trace.TracerProvider.get_tracer.
  416. If tracer_provider is omitted the current configured one is used.
  417. """
  418. if tracer_provider is None:
  419. tracer_provider = get_tracer_provider()
  420. return tracer_provider.get_tracer(
  421. instrumenting_module_name,
  422. instrumenting_library_version,
  423. schema_url,
  424. attributes,
  425. )
  426. def _set_tracer_provider(tracer_provider: TracerProvider, log: bool) -> None:
  427. def set_tp() -> None:
  428. global _TRACER_PROVIDER # pylint: disable=global-statement
  429. _TRACER_PROVIDER = tracer_provider
  430. did_set = _TRACER_PROVIDER_SET_ONCE.do_once(set_tp)
  431. if log and not did_set:
  432. logger.warning("Overriding of current TracerProvider is not allowed")
  433. def set_tracer_provider(tracer_provider: TracerProvider) -> None:
  434. """Sets the current global :class:`~.TracerProvider` object.
  435. This can only be done once, a warning will be logged if any further attempt
  436. is made.
  437. """
  438. _set_tracer_provider(tracer_provider, log=True)
  439. def get_tracer_provider() -> TracerProvider:
  440. """Gets the current global :class:`~.TracerProvider` object."""
  441. if _TRACER_PROVIDER is None:
  442. # if a global tracer provider has not been set either via code or env
  443. # vars, return a proxy tracer provider
  444. if OTEL_PYTHON_TRACER_PROVIDER not in os.environ:
  445. return _PROXY_TRACER_PROVIDER
  446. tracer_provider: TracerProvider = _load_provider(
  447. OTEL_PYTHON_TRACER_PROVIDER, "tracer_provider"
  448. )
  449. _set_tracer_provider(tracer_provider, log=False)
  450. # _TRACER_PROVIDER will have been set by one thread
  451. return cast("TracerProvider", _TRACER_PROVIDER)
  452. @_agnosticcontextmanager
  453. def use_span(
  454. span: Span,
  455. end_on_exit: bool = False,
  456. record_exception: bool = True,
  457. set_status_on_exception: bool = True,
  458. ) -> Iterator[Span]:
  459. """Takes a non-active span and activates it in the current context.
  460. Args:
  461. span: The span that should be activated in the current context.
  462. end_on_exit: Whether to end the span automatically when leaving the
  463. context manager scope.
  464. record_exception: Whether to record any exceptions raised within the
  465. context as error event on the span.
  466. set_status_on_exception: Only relevant if the returned span is used
  467. in a with/context manager. Defines whether the span status will
  468. be automatically set to ERROR when an uncaught exception is
  469. raised in the span with block. The span status won't be set by
  470. this mechanism if it was previously set manually.
  471. """
  472. try:
  473. token = context_api.attach(context_api.set_value(_SPAN_KEY, span))
  474. try:
  475. yield span
  476. finally:
  477. context_api.detach(token)
  478. # Record only exceptions that inherit Exception class but not BaseException, because
  479. # classes that directly inherit BaseException are not technically errors, e.g. GeneratorExit.
  480. # See https://github.com/open-telemetry/opentelemetry-python/issues/4484
  481. except Exception as exc: # pylint: disable=broad-exception-caught
  482. if isinstance(span, Span) and span.is_recording():
  483. # Record the exception as an event
  484. if record_exception:
  485. span.record_exception(exc)
  486. # Set status in case exception was raised
  487. if set_status_on_exception:
  488. span.set_status(
  489. Status(
  490. status_code=StatusCode.ERROR,
  491. description=f"{type(exc).__name__}: {exc}",
  492. )
  493. )
  494. # This causes parent spans to set their status to ERROR and to record
  495. # an exception as an event if a child span raises an exception even if
  496. # such child span was started with both record_exception and
  497. # set_status_on_exception attributes set to False.
  498. raise
  499. finally:
  500. if end_on_exit:
  501. span.end()
  502. __all__ = [
  503. "DEFAULT_TRACE_OPTIONS",
  504. "DEFAULT_TRACE_STATE",
  505. "INVALID_SPAN",
  506. "INVALID_SPAN_CONTEXT",
  507. "INVALID_SPAN_ID",
  508. "INVALID_TRACE_ID",
  509. "NonRecordingSpan",
  510. "Link",
  511. "Span",
  512. "SpanContext",
  513. "SpanKind",
  514. "TraceFlags",
  515. "TraceState",
  516. "TracerProvider",
  517. "Tracer",
  518. "format_span_id",
  519. "format_trace_id",
  520. "get_current_span",
  521. "get_tracer",
  522. "get_tracer_provider",
  523. "set_tracer_provider",
  524. "set_span_in_context",
  525. "use_span",
  526. "Status",
  527. "StatusCode",
  528. ]