From 7addc1e40348f28e87deda1ae97fc7f4b01806b3 Mon Sep 17 00:00:00 2001 From: Leighton Chen Date: Mon, 21 Sep 2020 08:38:58 -0700 Subject: [PATCH] instrumentation/wsgi: Use is_recording flag in wsgi instrumentation (#1122) --- .../instrumentation/wsgi/__init__.py | 6 ++++-- .../tests/test_wsgi_middleware.py | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py index 289016fe5..56c8b755c 100644 --- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py @@ -136,7 +136,8 @@ def add_response_attributes( ): # pylint: disable=unused-argument """Adds HTTP response attributes to span using the arguments passed to a PEP3333-conforming start_response callable.""" - + if not span.is_recording(): + return status_code, status_text = start_response_status.split(" ", 1) span.set_attribute("http.status_text", status_text) @@ -215,7 +216,8 @@ class OpenTelemetryMiddleware: iterable, span, self.tracer, token ) except Exception as ex: - span.set_status(Status(StatusCanonicalCode.INTERNAL, str(ex))) + if span.is_recording(): + span.set_status(Status(StatusCanonicalCode.INTERNAL, str(ex))) span.end() context.detach(token) raise diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py index b06d915b5..baab50d96 100644 --- a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py +++ b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py @@ -125,6 +125,23 @@ class TestWsgiApplication(WsgiTestBase): response = app(self.environ, self.start_response) self.validate_response(response) + def test_wsgi_not_recording(self): + mock_tracer = mock.Mock() + mock_span = mock.Mock() + mock_span.is_recording.return_value = False + mock_tracer.start_span.return_value = mock_span + mock_tracer.use_span.return_value.__enter__ = mock_span + mock_tracer.use_span.return_value.__exit__ = mock_span + with mock.patch("opentelemetry.trace.get_tracer") as tracer: + tracer.return_value = mock_tracer + app = otel_wsgi.OpenTelemetryMiddleware(simple_wsgi) + # pylint: disable=W0612 + response = app(self.environ, self.start_response) # noqa: F841 + self.assertFalse(mock_span.is_recording()) + self.assertTrue(mock_span.is_recording.called) + self.assertFalse(mock_span.set_attribute.called) + self.assertFalse(mock_span.set_status.called) + def test_wsgi_iterable(self): original_response = Response() iter_wsgi = create_iter_wsgi(original_response)