如何在调试日志中查看 Python 的请求使用哪个 IP 地址进行连接?

How can I see in debug logs which IP address is used for connection by Python's request?

假设我正在向 URL 发送 GET 请求,其 DNS 记录包含多个 IP 地址(DNS 循环)。例如,给https://www.twitter.com。如果我们对它进行 dig,我们会看到:

;; ANSWER SECTION:
twitter.com.        60  IN  A   104.244.42.193
twitter.com.        60  IN  A   104.244.42.129

我已尝试按照此处所述使用 DEBUG 日志记录: 但是它没有显示它使用的 IP 地址。

此外,我还看了这个答案:关于如何查看目标IP地址,但这不是我真正想看到的——这个显示了我最终使用的IP地址。

我更想看看在所有尝试中尝试了哪些 IP 地址,而库执行 DNS 故障转移。类似于:

Trying to connect to 104.244.42.193... failed, trying to connect using another IP address

有没有办法看到?

urllib3 库负责这个,在 urllib3.util.connection.create_connection() function. There's a loop there that checks each result from 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:
        # ...

遗憾的是,本部分没有使用日志记录。如果你必须有日志记录,你必须复制函数源,添加你需要的日志记录,然后 monkeypatch urllib3 代码以使用你的版本。

使用该函数的唯一位置使用它 as an attribute on the imported module,所以至少 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