-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathurllib3.py
64 lines (50 loc) · 1.76 KB
/
urllib3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import wrapt
from scout_apm.compat import text_type
from scout_apm.core.tracked_request import TrackedRequest
try:
from urllib3 import HTTPConnectionPool
except ImportError: # pragma: no cover
HTTPConnectionPool = None
logger = logging.getLogger(__name__)
have_patched_pool_urlopen = False
def ensure_installed():
global have_patched_pool_urlopen
logger.debug("Instrumenting urllib3.")
if HTTPConnectionPool is None:
logger.debug(
"Couldn't import urllib3.HTTPConnectionPool - probably not installed."
)
return False
elif not have_patched_pool_urlopen:
try:
HTTPConnectionPool.urlopen = wrapped_urlopen(HTTPConnectionPool.urlopen)
except Exception as exc:
logger.warning(
"Failed to instrument for Urllib3 HTTPConnectionPool.urlopen: %r",
exc,
exc_info=exc,
)
else:
have_patched_pool_urlopen = True
@wrapt.decorator
def wrapped_urlopen(wrapped, instance, args, kwargs):
def _extract_method_url(method, url, *args, **kwargs):
return method, url
try:
method, url = _extract_method_url(*args, **kwargs)
except TypeError:
method = "Unknown"
url = "Unknown"
else:
try:
url = text_type(instance._absolute_url(url))
except Exception:
logger.exception("Could not get URL for HTTPConnectionPool")
url = "Unknown"
tracked_request = TrackedRequest.instance()
with tracked_request.span(operation="HTTP/{}".format(method)) as span:
span.tag("url", url)
return wrapped(*args, **kwargs)