diff --git a/ext/opentelemetry-ext-wsgi/src/opentelemetry/ext/wsgi/__init__.py b/ext/opentelemetry-ext-wsgi/src/opentelemetry/ext/wsgi/__init__.py index 61f061948d3..5e619eb7c6a 100644 --- a/ext/opentelemetry-ext-wsgi/src/opentelemetry/ext/wsgi/__init__.py +++ b/ext/opentelemetry-ext-wsgi/src/opentelemetry/ext/wsgi/__init__.py @@ -48,10 +48,12 @@ def _add_request_attributes(span, environ): if not host: host = environ["SERVER_NAME"] port = environ["SERVER_PORT"] + scheme = environ["wsgi.url_scheme"] if ( - port != "80" - and environ["wsgi.url_scheme"] == "http" - or port != "443" + scheme == "http" + and port != "80" + or scheme == "https" + and port != "443" ): host += ":" + port diff --git a/ext/opentelemetry-ext-wsgi/tests/test_wsgi_middleware.py b/ext/opentelemetry-ext-wsgi/tests/test_wsgi_middleware.py index cd1778c492e..a88782d6428 100644 --- a/ext/opentelemetry-ext-wsgi/tests/test_wsgi_middleware.py +++ b/ext/opentelemetry-ext-wsgi/tests/test_wsgi_middleware.py @@ -203,9 +203,7 @@ def validate_url(self, expected_url): self.assertIn("http.url", attrs) self.assertEqual(attrs["http.url"], expected_url) self.assertIn("http.host", attrs) - self.assertEqual( - attrs["http.host"], urlparse(attrs["http.url"]).netloc - ) + self.assertEqual(attrs["http.host"], urlparse(expected_url).netloc) def test_request_attributes_with_partial_raw_uri(self): self.environ["RAW_URI"] = "/#top" @@ -231,6 +229,18 @@ def test_https_uri_port(self): self.environ["SERVER_PORT"] = "80" self.validate_url("https://127.0.0.1:80/") + def test_http_uri_port(self): + del self.environ["HTTP_HOST"] + self.environ["SERVER_PORT"] = "80" + self.environ["wsgi.url_scheme"] = "http" + self.validate_url("http://127.0.0.1/") + + self.environ["SERVER_PORT"] = "8080" + self.validate_url("http://127.0.0.1:8080/") + + self.environ["SERVER_PORT"] = "443" + self.validate_url("http://127.0.0.1:443/") + def test_request_attributes_with_nonstandard_port_and_no_host(self): del self.environ["HTTP_HOST"] self.environ["SERVER_PORT"] = "8080"