[英]How can I see in debug logs which IP address is used for connection by Python's request?
Let us say I am sending a GET request to an URL which's DNS record contains multiple IP addresses (DNS Round-Robin).假设我正在向一个 URL 发送 GET 请求,该 URL 的 DNS 记录包含多个 IP 地址(DNS 循环)。 For example, to the
https://www.twitter.com
.例如,到
https://www.twitter.com
。 If we do dig
of it, we see:如果我们
dig
它,我们会看到:
;; ANSWER SECTION:
twitter.com. 60 IN A 104.244.42.193
twitter.com. 60 IN A 104.244.42.129
I have tried to use DEBUG logging as described here: https://stackoverflow.com/a/16630836/1479414 however it does not show which IP address it uses.我尝试使用此处描述的调试日志记录: https : //stackoverflow.com/a/16630836/1479414但是它没有显示它使用的 IP 地址。
Furthermore, I looked also at this answer: https://stackoverflow.com/a/22513161/1479414 about how to see the destination IP address, but it is not what I actually want to see -- this one shows me the finally used IP address.此外,我还查看了这个答案: https : //stackoverflow.com/a/22513161/1479414关于如何查看目标 IP 地址,但这不是我真正想要看到的——这个给我展示了最后使用的IP地址。
I want rather to see which IP addresses are tried during all attempts, while the library performs DNS failover.我更想查看在所有尝试中尝试了哪些 IP 地址,而库执行 DNS 故障转移。 Something like:
就像是:
Trying to connect to 104.244.42.193... failed, trying to connect using another IP address
Is it possible to see somehow?有可能以某种方式看到吗?
The urllib3
library is responsible for this, in the urllib3.util.connection.create_connection()
function . urllib3
库在urllib3.util.connection.create_connection()
函数中对此负责。 There's a loop there that checks each result from socket.getaddrinfo()
:有一个循环检查
socket.getaddrinfo()
每个结果:
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
# ....
try:
sock = socket.socket(af, socktype, proto)
# ...
sock.connect(sa)
return sock
except socket.error as e:
# ...
Unfortunately, there is no logging used in this section.不幸的是,本节中没有使用日志记录。 If you must have logging, you'd have to copy the function source, add in the logging you need, then monkeypatch the
urllib3
code to use your version instead.如果必须有日志记录,则必须复制函数源,添加所需的日志记录,然后对
urllib3
代码进行urllib3
以使用您的版本。
The only location that uses that function uses it as an attribute on the imported module , so at least monkeypatching is as simple as assigning it back to original function location:唯一使用该函数的位置将其用作导入模块上的属性,因此至少monkeypatching 就像将其分配回原始函数位置一样简单:
import urllib3.util.connection
def create_connection_with_logging(
address,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None,
socket_options=None,
):
# ....
urllib3.util.connection.create_connection = create_connection_with_logging
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.