Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 5244790

Browse files
committedApr 20, 2021
Add support for HTTPX instrumentation
This builds off of the initial idea in [this issue][1] of using the transport API in `httpx`. This allows for using [custom transports][2]. One issue with this current implementation is that there are few more [changes coming][3] in 0.18.0 that this will probably want to use. So maybe it will make sense to finalize this on that version before releasing it. Want to get some eyes on this sooner. Resolves #263 [1]: encode/httpx#1264 (comment) [2]: https://www.python-httpx.org/advanced/#custom-transports [3]: encode/httpx#1522
1 parent 3083690 commit 5244790

File tree

13 files changed

+1361
-0
lines changed

13 files changed

+1361
-0
lines changed
 

‎docs-requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,4 @@ redis>=2.6
3434
sqlalchemy>=1.0
3535
tornado>=6.0
3636
ddtrace>=0.34.0
37+
httpx~=0.17.0

‎docs/instrumentation/httpx/httpx.rst

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
.. include:: ../../../instrumentation/opentelemetry-instrumentation-httpx/README.rst
2+
:end-before: References
3+
4+
API
5+
---
6+
7+
.. automodule:: opentelemetry.instrumentation.httpx
8+
:members:
9+
:undoc-members:
10+
:show-inheritance:

‎docs/nitpick-exceptions.ini

+4
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ class_references=
1818
Setter
1919
Getter
2020
; - AwsXRayFormat.extract
21+
httpcore.SyncHTTPTransport
22+
httpcore.AsyncHTTPTransport
23+
httpcore.SyncByteStream
24+
httpcore.AsyncByteStream
2125

2226
anys=
2327
; API
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
Apache License
2+
Version 2.0, January 2004
3+
http://www.apache.org/licenses/
4+
5+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6+
7+
1. Definitions.
8+
9+
"License" shall mean the terms and conditions for use, reproduction,
10+
and distribution as defined by Sections 1 through 9 of this document.
11+
12+
"Licensor" shall mean the copyright owner or entity authorized by
13+
the copyright owner that is granting the License.
14+
15+
"Legal Entity" shall mean the union of the acting entity and all
16+
other entities that control, are controlled by, or are under common
17+
control with that entity. For the purposes of this definition,
18+
"control" means (i) the power, direct or indirect, to cause the
19+
direction or management of such entity, whether by contract or
20+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
21+
outstanding shares, or (iii) beneficial ownership of such entity.
22+
23+
"You" (or "Your") shall mean an individual or Legal Entity
24+
exercising permissions granted by this License.
25+
26+
"Source" form shall mean the preferred form for making modifications,
27+
including but not limited to software source code, documentation
28+
source, and configuration files.
29+
30+
"Object" form shall mean any form resulting from mechanical
31+
transformation or translation of a Source form, including but
32+
not limited to compiled object code, generated documentation,
33+
and conversions to other media types.
34+
35+
"Work" shall mean the work of authorship, whether in Source or
36+
Object form, made available under the License, as indicated by a
37+
copyright notice that is included in or attached to the work
38+
(an example is provided in the Appendix below).
39+
40+
"Derivative Works" shall mean any work, whether in Source or Object
41+
form, that is based on (or derived from) the Work and for which the
42+
editorial revisions, annotations, elaborations, or other modifications
43+
represent, as a whole, an original work of authorship. For the purposes
44+
of this License, Derivative Works shall not include works that remain
45+
separable from, or merely link (or bind by name) to the interfaces of,
46+
the Work and Derivative Works thereof.
47+
48+
"Contribution" shall mean any work of authorship, including
49+
the original version of the Work and any modifications or additions
50+
to that Work or Derivative Works thereof, that is intentionally
51+
submitted to Licensor for inclusion in the Work by the copyright owner
52+
or by an individual or Legal Entity authorized to submit on behalf of
53+
the copyright owner. For the purposes of this definition, "submitted"
54+
means any form of electronic, verbal, or written communication sent
55+
to the Licensor or its representatives, including but not limited to
56+
communication on electronic mailing lists, source code control systems,
57+
and issue tracking systems that are managed by, or on behalf of, the
58+
Licensor for the purpose of discussing and improving the Work, but
59+
excluding communication that is conspicuously marked or otherwise
60+
designated in writing by the copyright owner as "Not a Contribution."
61+
62+
"Contributor" shall mean Licensor and any individual or Legal Entity
63+
on behalf of whom a Contribution has been received by Licensor and
64+
subsequently incorporated within the Work.
65+
66+
2. Grant of Copyright License. Subject to the terms and conditions of
67+
this License, each Contributor hereby grants to You a perpetual,
68+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69+
copyright license to reproduce, prepare Derivative Works of,
70+
publicly display, publicly perform, sublicense, and distribute the
71+
Work and such Derivative Works in Source or Object form.
72+
73+
3. Grant of Patent License. Subject to the terms and conditions of
74+
this License, each Contributor hereby grants to You a perpetual,
75+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76+
(except as stated in this section) patent license to make, have made,
77+
use, offer to sell, sell, import, and otherwise transfer the Work,
78+
where such license applies only to those patent claims licensable
79+
by such Contributor that are necessarily infringed by their
80+
Contribution(s) alone or by combination of their Contribution(s)
81+
with the Work to which such Contribution(s) was submitted. If You
82+
institute patent litigation against any entity (including a
83+
cross-claim or counterclaim in a lawsuit) alleging that the Work
84+
or a Contribution incorporated within the Work constitutes direct
85+
or contributory patent infringement, then any patent licenses
86+
granted to You under this License for that Work shall terminate
87+
as of the date such litigation is filed.
88+
89+
4. Redistribution. You may reproduce and distribute copies of the
90+
Work or Derivative Works thereof in any medium, with or without
91+
modifications, and in Source or Object form, provided that You
92+
meet the following conditions:
93+
94+
(a) You must give any other recipients of the Work or
95+
Derivative Works a copy of this License; and
96+
97+
(b) You must cause any modified files to carry prominent notices
98+
stating that You changed the files; and
99+
100+
(c) You must retain, in the Source form of any Derivative Works
101+
that You distribute, all copyright, patent, trademark, and
102+
attribution notices from the Source form of the Work,
103+
excluding those notices that do not pertain to any part of
104+
the Derivative Works; and
105+
106+
(d) If the Work includes a "NOTICE" text file as part of its
107+
distribution, then any Derivative Works that You distribute must
108+
include a readable copy of the attribution notices contained
109+
within such NOTICE file, excluding those notices that do not
110+
pertain to any part of the Derivative Works, in at least one
111+
of the following places: within a NOTICE text file distributed
112+
as part of the Derivative Works; within the Source form or
113+
documentation, if provided along with the Derivative Works; or,
114+
within a display generated by the Derivative Works, if and
115+
wherever such third-party notices normally appear. The contents
116+
of the NOTICE file are for informational purposes only and
117+
do not modify the License. You may add Your own attribution
118+
notices within Derivative Works that You distribute, alongside
119+
or as an addendum to the NOTICE text from the Work, provided
120+
that such additional attribution notices cannot be construed
121+
as modifying the License.
122+
123+
You may add Your own copyright statement to Your modifications and
124+
may provide additional or different license terms and conditions
125+
for use, reproduction, or distribution of Your modifications, or
126+
for any such Derivative Works as a whole, provided Your use,
127+
reproduction, and distribution of the Work otherwise complies with
128+
the conditions stated in this License.
129+
130+
5. Submission of Contributions. Unless You explicitly state otherwise,
131+
any Contribution intentionally submitted for inclusion in the Work
132+
by You to the Licensor shall be under the terms and conditions of
133+
this License, without any additional terms or conditions.
134+
Notwithstanding the above, nothing herein shall supersede or modify
135+
the terms of any separate license agreement you may have executed
136+
with Licensor regarding such Contributions.
137+
138+
6. Trademarks. This License does not grant permission to use the trade
139+
names, trademarks, service marks, or product names of the Licensor,
140+
except as required for reasonable and customary use in describing the
141+
origin of the Work and reproducing the content of the NOTICE file.
142+
143+
7. Disclaimer of Warranty. Unless required by applicable law or
144+
agreed to in writing, Licensor provides the Work (and each
145+
Contributor provides its Contributions) on an "AS IS" BASIS,
146+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147+
implied, including, without limitation, any warranties or conditions
148+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149+
PARTICULAR PURPOSE. You are solely responsible for determining the
150+
appropriateness of using or redistributing the Work and assume any
151+
risks associated with Your exercise of permissions under this License.
152+
153+
8. Limitation of Liability. In no event and under no legal theory,
154+
whether in tort (including negligence), contract, or otherwise,
155+
unless required by applicable law (such as deliberate and grossly
156+
negligent acts) or agreed to in writing, shall any Contributor be
157+
liable to You for damages, including any direct, indirect, special,
158+
incidental, or consequential damages of any character arising as a
159+
result of this License or out of the use or inability to use the
160+
Work (including but not limited to damages for loss of goodwill,
161+
work stoppage, computer failure or malfunction, or any and all
162+
other commercial damages or losses), even if such Contributor
163+
has been advised of the possibility of such damages.
164+
165+
9. Accepting Warranty or Additional Liability. While redistributing
166+
the Work or Derivative Works thereof, You may choose to offer,
167+
and charge a fee for, acceptance of support, warranty, indemnity,
168+
or other liability obligations and/or rights consistent with this
169+
License. However, in accepting such obligations, You may act only
170+
on Your own behalf and on Your sole responsibility, not on behalf
171+
of any other Contributor, and only if You agree to indemnify,
172+
defend, and hold each Contributor harmless for any liability
173+
incurred by, or claims asserted against, such Contributor by reason
174+
of your accepting any such warranty or additional liability.
175+
176+
END OF TERMS AND CONDITIONS
177+
178+
APPENDIX: How to apply the Apache License to your work.
179+
180+
To apply the Apache License to your work, attach the following
181+
boilerplate notice, with the fields enclosed by brackets "[]"
182+
replaced with your own identifying information. (Don't include
183+
the brackets!) The text should be enclosed in the appropriate
184+
comment syntax for the file format. We also recommend that a
185+
file or class name and description of purpose be included on the
186+
same "printed page" as the copyright notice for easier
187+
identification within third-party archives.
188+
189+
Copyright [yyyy] [name of copyright owner]
190+
191+
Licensed under the Apache License, Version 2.0 (the "License");
192+
you may not use this file except in compliance with the License.
193+
You may obtain a copy of the License at
194+
195+
http://www.apache.org/licenses/LICENSE-2.0
196+
197+
Unless required by applicable law or agreed to in writing, software
198+
distributed under the License is distributed on an "AS IS" BASIS,
199+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200+
See the License for the specific language governing permissions and
201+
limitations under the License.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
graft src
2+
graft tests
3+
global-exclude *.pyc
4+
global-exclude *.pyo
5+
global-exclude __pycache__/*
6+
include CHANGELOG.md
7+
include MANIFEST.in
8+
include README.rst
9+
include LICENSE
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
OpenTelemetry HTTPX Instrumentation
2+
===================================
3+
4+
|pypi|
5+
6+
.. |pypi| image:: https://badge.fury.io/py/opentelemetry-instrumentation-httpx.svg
7+
:target: https://pypi.org/project/opentelemetry-instrumentation-httpx/
8+
9+
This library allows tracing HTTP requests made by the
10+
`httpx <https://www.python-httpx.org/>`_ library.
11+
12+
Installation
13+
------------
14+
15+
::
16+
17+
pip install opentelemetry-instrumentation-httpx
18+
19+
20+
Usage
21+
-----
22+
23+
Instrumenting all clients
24+
*************************
25+
26+
When using the instrumentor, all newly created clients will automatically trace
27+
requests.
28+
29+
.. code-block:: python
30+
31+
import httpx
32+
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
33+
34+
url = "https://httpbin.org/get"
35+
HTTPXClientInstrumentor().instrument()
36+
37+
with httpx.Client() as client:
38+
response = client.get(url)
39+
40+
async with httpx.AsyncClient() as client:
41+
response = await client.get(url)
42+
43+
Uninstrument
44+
^^^^^^^^^^^^
45+
46+
If you need to uninstrument clients, there are two options available.
47+
48+
.. code-block:: python
49+
50+
import httpx
51+
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
52+
53+
HTTPXClientInstrumentor().instrument()
54+
client = httpx.Client()
55+
56+
# Uninstrument a specific client
57+
HTTPXClientInstrumentor.uninstrument_client(client)
58+
59+
# Uninstrument all new clients
60+
HTTPXClientInstrumentor().uninstrument()
61+
62+
63+
Instrumenting single clients
64+
****************************
65+
66+
If you only want to instrument requests for specific client instances, you can
67+
create the transport instance manually and pass it in when creating the client.
68+
69+
70+
.. code-block:: python
71+
72+
import httpx
73+
from opentelemetry.instrumentation.httpx import (
74+
AsyncOpenTelemetryTransport,
75+
SyncOpenTelemetryTransport,
76+
)
77+
78+
url = "https://httpbin.org/get"
79+
transport = httpx.HTTPTransport()
80+
telemetry_transport = SyncOpenTelemetryTransport(transport)
81+
82+
with httpx.Client(transport=telemetry_transport) as client:
83+
response = client.get(url)
84+
85+
transport = httpx.AsyncHTTPTransport()
86+
telemetry_transport = AsyncOpenTelemetryTransport(transport)
87+
88+
async with httpx.AsyncClient(transport=telemetry_transport) as client:
89+
response = await client.get(url)
90+
91+
92+
References
93+
----------
94+
95+
* `OpenTelemetry HTTPX Instrumentation <https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/httpx/httpx.html>`_
96+
* `OpenTelemetry Project <https://opentelemetry.io/>`_
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
#
15+
[metadata]
16+
name = opentelemetry-instrumentation-httpx
17+
description = OpenTelemetry HTTPX Instrumentation
18+
long_description = file: README.rst
19+
long_description_content_type = text/x-rst
20+
author = OpenTelemetry Authors
21+
author_email = cncf-opentelemetry-contributors@lists.cncf.io
22+
url = https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-httpx
23+
platforms = any
24+
license = Apache-2.0
25+
classifiers =
26+
Development Status :: 4 - Beta
27+
Intended Audience :: Developers
28+
License :: OSI Approved :: Apache Software License
29+
Programming Language :: Python
30+
Programming Language :: Python :: 3
31+
Programming Language :: Python :: 3.6
32+
Programming Language :: Python :: 3.7
33+
Programming Language :: Python :: 3.8
34+
35+
[options]
36+
python_requires = >=3.6
37+
package_dir=
38+
=src
39+
packages=find_namespace:
40+
install_requires =
41+
opentelemetry-api == 1.0.1.dev0
42+
opentelemetry-instrumentation == 0.20.dev0
43+
httpx >= 0.17.0, < 0.18.0
44+
wrapt >= 1.0.0, < 2.0.0
45+
46+
[options.extras_require]
47+
test =
48+
opentelemetry-sdk == 1.0.1dev0
49+
opentelemetry-test == 0.20.dev0
50+
respx ~= 0.16.0
51+
52+
[options.packages.find]
53+
where = src
54+
55+
[options.entry_points]
56+
opentelemetry_instrumentor =
57+
httpx = opentelemetry.instrumentation.httpx:HTTPXClientInstrumentor
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
import os
15+
16+
import setuptools
17+
18+
BASE_DIR = os.path.dirname(__file__)
19+
VERSION_FILENAME = os.path.join(
20+
BASE_DIR, "src", "opentelemetry", "instrumentation", "httpx", "version.py",
21+
)
22+
PACKAGE_INFO = {}
23+
with open(VERSION_FILENAME) as f:
24+
exec(f.read(), PACKAGE_INFO)
25+
26+
setuptools.setup(version=PACKAGE_INFO["__version__"])
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,325 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import typing
16+
17+
import httpcore
18+
import httpx
19+
import wrapt
20+
21+
from opentelemetry import context
22+
from opentelemetry.instrumentation.httpx.version import __version__
23+
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
24+
from opentelemetry.instrumentation.utils import (
25+
http_status_to_status_code,
26+
unwrap,
27+
)
28+
from opentelemetry.propagate import inject
29+
from opentelemetry.trace import SpanKind, Tracer, TracerProvider, get_tracer
30+
from opentelemetry.trace.span import Span
31+
from opentelemetry.trace.status import Status
32+
33+
ResponseInfo = typing.Tuple[
34+
int, typing.List[typing.Tuple[bytes, bytes]], typing.Iterable[bytes], dict,
35+
]
36+
NameCallback = typing.Callable[[str, str], str]
37+
SpanCallback = typing.Callable[[Span, ResponseInfo], None]
38+
URL = typing.Tuple[bytes, bytes, typing.Optional[int], bytes]
39+
Headers = typing.List[typing.Tuple[bytes, bytes]]
40+
41+
42+
def _get_tracer(
43+
*, tracer_provider: typing.Optional[TracerProvider] = None
44+
) -> Tracer:
45+
return get_tracer(
46+
__name__,
47+
instrumenting_library_version=__version__,
48+
tracer_provider=tracer_provider,
49+
)
50+
51+
52+
def _get_span_name(
53+
method: str,
54+
url: str,
55+
*,
56+
name_callback: typing.Optional[NameCallback] = None
57+
) -> str:
58+
span_name = ""
59+
if name_callback is not None:
60+
span_name = name_callback(method, url)
61+
if not span_name or not isinstance(span_name, str):
62+
span_name = "HTTP {}".format(method).strip()
63+
return span_name
64+
65+
66+
def _apply_status_code(span: Span, status_code: int) -> None:
67+
if not span.is_recording():
68+
return
69+
70+
span.set_attribute("http.status_code", status_code)
71+
span.set_status(Status(http_status_to_status_code(status_code)))
72+
73+
74+
def _prepare_attributes(method: bytes, url: URL) -> typing.Dict[str, str]:
75+
_method = method.decode().upper()
76+
_url = str(httpx.URL(url))
77+
span_attributes = {
78+
"http.method": _method,
79+
"http.url": _url,
80+
}
81+
return span_attributes
82+
83+
84+
def _prepare_headers(headers: typing.Optional[Headers]) -> httpx.Headers:
85+
return httpx.Headers(headers)
86+
87+
88+
class SyncOpenTelemetryTransport(httpcore.SyncHTTPTransport):
89+
"""Sync transport class that will trace all requests made with a client.
90+
91+
Args:
92+
transport: SyncHTTPTransport instance to wrap
93+
tracer_provider: Tracer provider to use
94+
span_callback: A callback provided with the response info to modify
95+
the span
96+
name_callback: A callback provided with the method and url to process
97+
the span name
98+
"""
99+
100+
def __init__(
101+
self,
102+
transport: httpcore.SyncHTTPTransport,
103+
tracer_provider: typing.Optional[TracerProvider] = None,
104+
span_callback: typing.Optional[SpanCallback] = None,
105+
name_callback: typing.Optional[NameCallback] = None,
106+
):
107+
self._transport = transport
108+
self._tracer_provider = tracer_provider
109+
self._span_callback = span_callback
110+
self._name_callback = name_callback
111+
112+
def request(
113+
self,
114+
method: bytes,
115+
url: URL,
116+
headers: typing.Optional[Headers] = None,
117+
stream: typing.Optional[httpcore.SyncByteStream] = None,
118+
ext: typing.Optional[dict] = None,
119+
) -> typing.Tuple[int, "Headers", httpcore.SyncByteStream, dict]:
120+
"""Add request info to span."""
121+
if context.get_value("suppress_instrumentation"):
122+
return self._transport.request(
123+
method, url, headers=headers, stream=stream, ext=ext
124+
)
125+
126+
span_attributes = _prepare_attributes(method, url)
127+
_headers = _prepare_headers(headers)
128+
span_name = _get_span_name(
129+
span_attributes["http.method"],
130+
span_attributes["http.url"],
131+
name_callback=self._name_callback,
132+
)
133+
134+
with _get_tracer(
135+
tracer_provider=self._tracer_provider
136+
).start_as_current_span(
137+
span_name, kind=SpanKind.CLIENT, attributes=span_attributes
138+
) as span:
139+
inject(_headers)
140+
141+
status_code, headers, stream, extensions = self._transport.request(
142+
method, url, headers=_headers.raw, stream=stream, ext=ext
143+
)
144+
145+
_apply_status_code(span, status_code)
146+
147+
if self._span_callback is not None:
148+
self._span_callback(
149+
span, (status_code, headers, stream, extensions)
150+
)
151+
152+
return status_code, headers, stream, extensions
153+
154+
155+
class AsyncOpenTelemetryTransport(httpcore.AsyncHTTPTransport):
156+
"""Async transport class that will trace all requests made with a client.
157+
158+
Args:
159+
transport: AsyncHTTPTransport instance to wrap
160+
tracer_provider: Tracer provider to use
161+
span_callback: A callback provided with the response info to modify
162+
the span
163+
name_callback: A callback provided with the method and url to process
164+
the span name
165+
"""
166+
167+
def __init__(
168+
self,
169+
transport: httpcore.AsyncHTTPTransport,
170+
tracer_provider: typing.Optional[TracerProvider] = None,
171+
span_callback: typing.Optional[SpanCallback] = None,
172+
name_callback: typing.Optional[NameCallback] = None,
173+
):
174+
self._transport = transport
175+
self._tracer_provider = tracer_provider
176+
self._span_callback = span_callback
177+
self._name_callback = name_callback
178+
179+
async def arequest(
180+
self,
181+
method: bytes,
182+
url: URL,
183+
headers: typing.Optional[Headers] = None,
184+
stream: typing.Optional[httpcore.AsyncByteStream] = None,
185+
ext: typing.Optional[dict] = None,
186+
) -> typing.Tuple[int, "Headers", httpcore.AsyncByteStream, dict]:
187+
"""Add request info to span."""
188+
if context.get_value("suppress_instrumentation"):
189+
return await self._transport.arequest(
190+
method, url, headers=headers, stream=stream, ext=ext
191+
)
192+
193+
span_attributes = _prepare_attributes(method, url)
194+
_headers = _prepare_headers(headers)
195+
span_name = _get_span_name(
196+
span_attributes["http.method"],
197+
span_attributes["http.url"],
198+
name_callback=self._name_callback,
199+
)
200+
201+
with _get_tracer(
202+
tracer_provider=self._tracer_provider
203+
).start_as_current_span(
204+
span_name, kind=SpanKind.CLIENT, attributes=span_attributes
205+
) as span:
206+
inject(_headers)
207+
208+
(
209+
status_code,
210+
headers,
211+
stream,
212+
extensions,
213+
) = await self._transport.arequest(
214+
method, url, headers=_headers.raw, stream=stream, ext=ext
215+
)
216+
217+
_apply_status_code(span, status_code)
218+
219+
if self._span_callback is not None:
220+
self._span_callback(
221+
span, (status_code, headers, stream, extensions)
222+
)
223+
224+
return status_code, headers, stream, extensions
225+
226+
227+
def _instrument(
228+
tracer_provider: TracerProvider = None,
229+
span_callback: typing.Optional[SpanCallback] = None,
230+
name_callback: typing.Optional[NameCallback] = None,
231+
) -> None:
232+
"""Enables tracing of all Client and AsyncClient instances
233+
234+
When a Client or AsyncClient gets created, a telemetry transport is passed
235+
in to the instance.
236+
"""
237+
# pylint:disable=unused-argument
238+
def instrumented_sync_init(wrapped, instance, args, kwargs):
239+
if context.get_value("suppress_instrumentation"):
240+
return wrapped(*args, **kwargs)
241+
242+
transport = kwargs.get("transport") or httpx.HTTPTransport()
243+
telemetry_transport = SyncOpenTelemetryTransport(
244+
transport,
245+
tracer_provider=tracer_provider,
246+
span_callback=span_callback,
247+
name_callback=name_callback,
248+
)
249+
250+
kwargs["transport"] = telemetry_transport
251+
return wrapped(*args, **kwargs)
252+
253+
def instrumented_async_init(wrapped, instance, args, kwargs):
254+
if context.get_value("suppress_instrumentation"):
255+
return wrapped(*args, **kwargs)
256+
257+
transport = kwargs.get("transport") or httpx.AsyncHTTPTransport()
258+
telemetry_transport = AsyncOpenTelemetryTransport(
259+
transport,
260+
tracer_provider=tracer_provider,
261+
span_callback=span_callback,
262+
name_callback=name_callback,
263+
)
264+
265+
kwargs["transport"] = telemetry_transport
266+
return wrapped(*args, **kwargs)
267+
268+
wrapt.wrap_function_wrapper(
269+
httpx.Client, "__init__", instrumented_sync_init
270+
)
271+
272+
wrapt.wrap_function_wrapper(
273+
httpx.AsyncClient, "__init__", instrumented_async_init
274+
)
275+
276+
277+
def _uninstrument() -> None:
278+
"""Disables instrumenting for all newly created Client and AsyncClient instances"""
279+
unwrap(httpx.Client, "__init__")
280+
unwrap(httpx.AsyncClient, "__init__")
281+
282+
283+
def _uninstrument_client(
284+
client: typing.Union[httpx.Client, httpx.AsyncClient]
285+
) -> None:
286+
"""Disables instrumentation for the given Client or AsyncClient"""
287+
# pylint: disable=protected-access
288+
telemetry_transport: typing.Union[
289+
SyncOpenTelemetryTransport, AsyncOpenTelemetryTransport
290+
] = client._transport
291+
client._transport = telemetry_transport._transport
292+
293+
294+
class HTTPXClientInstrumentor(BaseInstrumentor):
295+
"""An instrumentor for httpx Client and AsyncClient
296+
297+
See `BaseInstrumentor`
298+
"""
299+
300+
def _instrument(self, **kwargs):
301+
"""Instruments httpx Client and AsyncClient
302+
303+
Args:
304+
**kwargs: Optional arguments
305+
``tracer_provider``: a TracerProvider, defaults to global
306+
``span_callback``: A callback provided with the response info
307+
to modify the span
308+
``name_callback``: A callback provided with the method and url
309+
to process the span name
310+
"""
311+
_instrument(
312+
tracer_provider=kwargs.get("tracer_provider"),
313+
span_callback=kwargs.get("span_callback"),
314+
name_callback=kwargs.get("name_callback"),
315+
)
316+
317+
def _uninstrument(self, **kwargs):
318+
_uninstrument()
319+
320+
@staticmethod
321+
def uninstrument_client(
322+
client: typing.Union[httpx.Client, httpx.AsyncClient]
323+
):
324+
"""Disables instrumentation for the given client instance"""
325+
_uninstrument_client(client)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
__version__ = "0.20.dev0"

‎instrumentation/opentelemetry-instrumentation-httpx/tests/__init__.py

Whitespace-only changes.

‎instrumentation/opentelemetry-instrumentation-httpx/tests/test_httpx_integration.py

+609
Large diffs are not rendered by default.

‎tox.ini

+8
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,10 @@ envlist =
140140
py3{6,7,8}-test-instrumentation-tornado
141141
pypy3-test-instrumentation-tornado
142142

143+
; opentelemetry-instrumentation-httpx
144+
py{6,7,8}-test-instrumentation-httpx
145+
pypy3-test-instrumentation-httpx
146+
143147
; opentelemetry-util-http
144148
py3{6,7,8}-test-util-http
145149
pypy3-test-util-http
@@ -204,6 +208,7 @@ changedir =
204208
test-instrumentation-starlette: instrumentation/opentelemetry-instrumentation-starlette/tests
205209
test-instrumentation-tornado: instrumentation/opentelemetry-instrumentation-tornado/tests
206210
test-instrumentation-wsgi: instrumentation/opentelemetry-instrumentation-wsgi/tests
211+
test-instrumentation-httpx: instrumentation/opentelemetry-instrumentation-httpx/tests
207212
test-util-http: util/opentelemetry-util-http/tests
208213
test-sdkextension-aws: sdk-extension/opentelemetry-sdk-extension-aws/tests
209214
test-propagator-ot-trace: propagator/opentelemetry-propagator-ot-trace/tests
@@ -287,6 +292,8 @@ commands_pre =
287292

288293
elasticsearch{2,5,6,7}: pip install {toxinidir}/opentelemetry-python-core/opentelemetry-instrumentation {toxinidir}/instrumentation/opentelemetry-instrumentation-elasticsearch[test]
289294

295+
httpx: pip install {toxinidir}/opentelemetry-python-core/opentelemetry-instrumentation {toxinidir}/instrumentation/opentelemetry-instrumentation-httpx[test]
296+
290297
aws: pip install requests {toxinidir}/sdk-extension/opentelemetry-sdk-extension-aws
291298

292299
http: pip install {toxinidir}/util/opentelemetry-util-http
@@ -370,6 +377,7 @@ commands_pre =
370377
python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-asyncpg[test]
371378
python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-tornado[test]
372379
python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-mysql[test]
380+
python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-httpx[test]
373381
python -m pip install -e {toxinidir}/exporter/opentelemetry-exporter-datadog[test]
374382
python -m pip install -e {toxinidir}/sdk-extension/opentelemetry-sdk-extension-aws[test]
375383
python -m pip install -e {toxinidir}/propagator/opentelemetry-propagator-ot-trace[test]

0 commit comments

Comments
 (0)
Please sign in to comment.