Skip to content

Commit 155a5aa

Browse files
committed
Limit to only handling in our own spans
1 parent b39cb13 commit 155a5aa

File tree

2 files changed

+28
-51
lines changed

2 files changed

+28
-51
lines changed

temporalio/contrib/opentelemetry.py

Lines changed: 22 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -171,11 +171,30 @@ def _start_as_current_span(
171171
attributes: opentelemetry.util.types.Attributes,
172172
input: Optional[_InputWithHeaders] = None,
173173
kind: opentelemetry.trace.SpanKind,
174+
context: Optional[Context] = None,
174175
) -> Iterator[None]:
175-
with self.tracer.start_as_current_span(name, attributes=attributes, kind=kind):
176+
with self.tracer.start_as_current_span(name, attributes=attributes, kind=kind, context=context, set_status_on_exception=False) as span:
176177
if input:
177178
input.headers = self._context_to_headers(input.headers)
178-
yield None
179+
try:
180+
yield None
181+
except ApplicationError as exc:
182+
if exc.category != ApplicationErrorCategory.BENIGN:
183+
span.set_status(
184+
Status(
185+
status_code=StatusCode.ERROR,
186+
description=f"{type(exc).__name__}: {exc}",
187+
)
188+
)
189+
raise
190+
except Exception as exc:
191+
span.set_status(
192+
Status(
193+
status_code=StatusCode.ERROR,
194+
description=f"{type(exc).__name__}: {exc}",
195+
)
196+
)
197+
raise
179198

180199
def _completed_workflow_span(
181200
self, params: _CompletedWorkflowSpanParams
@@ -286,7 +305,7 @@ async def execute_activity(
286305
self, input: temporalio.worker.ExecuteActivityInput
287306
) -> Any:
288307
info = temporalio.activity.info()
289-
with self.root.tracer.start_as_current_span(
308+
with self.root._start_as_current_span(
290309
f"RunActivity:{info.activity_type}",
291310
context=self.root._context_from_headers(input.headers),
292311
attributes={
@@ -665,50 +684,6 @@ def start_local_activity(
665684
return super().start_local_activity(input)
666685

667686

668-
class TemporalTracer(opentelemetry.trace.Tracer):
669-
def __init__(self, tracer: opentelemetry.trace.Tracer):
670-
self._tracer = tracer
671-
super().__init__()
672-
673-
def start_span(self, name: str, context: Optional[Context] = None, kind: SpanKind = SpanKind.INTERNAL,
674-
attributes: types.Attributes = None, links: _Links = None, start_time: Optional[int] = None,
675-
record_exception: bool = True, set_status_on_exception: bool = True) -> Span:
676-
return self._tracer.start_span(name, context, kind, attributes, links, start_time, record_exception, set_status_on_exception)
677-
678-
@staticmethod
679-
def handle_exception(exc: Exception, span: Span, record_exception: bool, set_status_on_exception: bool) -> None:
680-
if record_exception:
681-
span.record_exception(exc)
682-
683-
# Set status in case exception was raised
684-
if set_status_on_exception:
685-
span.set_status(
686-
Status(
687-
status_code=StatusCode.ERROR,
688-
description=f"{type(exc).__name__}: {exc}",
689-
)
690-
)
691-
692-
@contextmanager
693-
def start_as_current_span(self, name: str, context: Optional[Context] = None, kind: SpanKind = SpanKind.INTERNAL,
694-
attributes: types.Attributes = None, links: _Links = None,
695-
start_time: Optional[int] = None, record_exception: bool = True,
696-
set_status_on_exception: bool = True, end_on_exit: bool = True) -> Iterator[Span]:
697-
698-
with self._tracer.start_as_current_span(name, context, kind, attributes, links, start_time, False, False, end_on_exit) as span:
699-
try:
700-
yield span
701-
702-
# TODO: Catch base exception and handle cancellation errors
703-
except ApplicationError as exc:
704-
if exc.category != ApplicationErrorCategory.BENIGN:
705-
self.handle_exception(exc, span, record_exception, set_status_on_exception)
706-
raise
707-
except Exception as exc:
708-
self.handle_exception(exc, span, record_exception, set_status_on_exception)
709-
raise
710-
711-
712687
class workflow:
713688
"""Contains static methods that are safe to call from within a workflow.
714689

tests/contrib/test_opentelemetry.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from temporalio import activity, workflow
1717
from temporalio.client import Client
1818
from temporalio.common import RetryPolicy
19-
from temporalio.contrib.opentelemetry import TracingInterceptor, TemporalTracer
19+
from temporalio.contrib.opentelemetry import TracingInterceptor
2020
from temporalio.contrib.opentelemetry import workflow as otel_workflow
2121
from temporalio.exceptions import ApplicationError, ApplicationErrorCategory
2222
from temporalio.testing import WorkflowEnvironment
@@ -394,7 +394,6 @@ def benign_activity() -> str:
394394
global attempted
395395
if attempted:
396396
return "done"
397-
print("Raising")
398397
attempted = True
399398
raise ApplicationError(category=ApplicationErrorCategory.BENIGN, message="Benign Error")
400399

@@ -404,12 +403,13 @@ class BenignWorkflow:
404403
async def run(self) -> str:
405404
return await workflow.execute_activity(benign_activity, schedule_to_close_timeout=timedelta(seconds=1))
406405

407-
async def test_opentelemetry_exception_tracing(client: Client):
406+
async def test_opentelemetry_benign_exception(client: Client):
408407
# Create a tracer that has an in-memory exporter
409408
exporter = InMemorySpanExporter()
410409
provider = TracerProvider()
411410
provider.add_span_processor(SimpleSpanProcessor(exporter))
412-
tracer = TemporalTracer(get_tracer(__name__, tracer_provider=provider))
411+
tracer = get_tracer(__name__, tracer_provider=provider)
412+
413413
# Create new client with tracer interceptor
414414
client_config = client.config()
415415
client_config["interceptors"] = [TracingInterceptor(tracer)]
@@ -429,6 +429,8 @@ async def test_opentelemetry_exception_tracing(client: Client):
429429
retry_policy=RetryPolicy(maximum_attempts=2, initial_interval=timedelta(milliseconds=10)),
430430
)
431431
spans = exporter.get_finished_spans()
432+
for span in spans:
433+
print(f"{span.name}: {span.status.status_code}")
432434
assert all(span.status.status_code == StatusCode.UNSET for span in spans)
433435

434436
# TODO(cretz): Additional tests to write

0 commit comments

Comments
 (0)