@@ -114,11 +114,10 @@ def start_as_current_span(
114
114
kind : SpanKind = _SpanKind .INTERNAL ,
115
115
attributes : Optional [Attributes ] = None ,
116
116
links : Optional [Sequence [Link ]] = None ,
117
+ end_on_exit : bool = True ,
117
118
) -> Iterator [Span ]:
118
119
"""Context manager that starts a span and sets it as the current span in the context.
119
120
120
- Exiting the context manager will call the span's end method.
121
-
122
121
.. code:: python
123
122
124
123
with tracer.start_as_current_span("span_name") as span:
@@ -133,13 +132,34 @@ def start_as_current_span(
133
132
:paramtype attributes: Optional[Attributes]
134
133
:keyword links: Links to add to the span.
135
134
:paramtype links: Optional[Sequence[Link]]
135
+ :keyword end_on_exit: Whether to end the span when exiting the context manager. Defaults to True.
136
+ :paramtype end_on_exit: bool
136
137
:return: The span that was started
137
- :rtype: ~opentelemetry.trace.Span
138
+ :rtype: Iterator[ ~opentelemetry.trace.Span]
138
139
"""
139
140
span = self .start_span (name , kind = kind , attributes = attributes , links = links )
140
- with trace .use_span (span , record_exception = False , end_on_exit = True ) as span : # type: ignore[attr-defined] # pylint: disable=not-context-manager
141
+ with trace .use_span ( # pylint: disable=not-context-manager
142
+ span , record_exception = False , end_on_exit = end_on_exit
143
+ ) as span :
141
144
yield span
142
145
146
+ @classmethod
147
+ @contextmanager
148
+ def use_span (cls , span : Span , * , end_on_exit : bool = True ) -> Iterator [Span ]:
149
+ """Context manager that takes a non-active span and activates it in the current context.
150
+
151
+ :param span: The span to set as the current span
152
+ :type span: ~opentelemetry.trace.Span
153
+ :keyword end_on_exit: Whether to end the span when exiting the context manager. Defaults to True.
154
+ :paramtype end_on_exit: bool
155
+ :return: The span that was activated.
156
+ :rtype: Iterator[~opentelemetry.trace.Span]
157
+ """
158
+ with trace .use_span ( # pylint: disable=not-context-manager
159
+ span , record_exception = False , end_on_exit = end_on_exit
160
+ ) as active_span :
161
+ yield active_span
162
+
143
163
def _parse_links (self , links : Optional [Sequence [Link ]]) -> Optional [Sequence [OpenTelemetryLink ]]:
144
164
if not links :
145
165
return None
@@ -189,7 +209,7 @@ def call_with_current_context(*args, **kwargs):
189
209
190
210
@classmethod
191
211
def get_trace_context (cls ) -> Dict [str , str ]:
192
- """Returns the Trace Context header values associated with the span.
212
+ """Returns the Trace Context header values associated with the current span.
193
213
194
214
These are generally the W3C Trace Context headers (i.e. "traceparent" and "tracestate").
195
215
0 commit comments