instrumentation/wsgi: Use is_recording flag in wsgi instrumentation (#1122)

This commit is contained in:
Leighton Chen
2020-09-21 08:38:58 -07:00
committed by GitHub
parent 04316cad0b
commit 7addc1e403
2 changed files with 21 additions and 2 deletions

View File

@ -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

View File

@ -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)