bug_x

导航

 
import logging
import http.client

httpclient_logger = logging.getLogger("http.client")

def httpclient_logging_patch(level=logging.DEBUG):
    """Enable HTTPConnection debug logging to the logging framework"""

    def httpclient_log(*args):
        httpclient_logger.log(level, " ".join(args))

    # mask the print() built-in in the http.client module to use
    # logging instead
    http.client.print = httpclient_log
    # enable debugging
    http.client.HTTPConnection.debuglevel = 1


==========================================================================
>>> httpclient_logging_patch()
>>> r = requests.get('http://httpbin.org/get?foo=bar&baz=python')
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): httpbin.org:80
DEBUG:http.client:send: b'GET /get?foo=bar&baz=python HTTP/1.1\r\nHost: httpbin.org\r\nUser-Agent: python-requests/2.22.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n'
DEBUG:http.client:reply: 'HTTP/1.1 200 OK\r\n'
DEBUG:http.client:header: Date: Tue, 04 Feb 2020 13:36:53 GMT
DEBUG:http.client:header: Content-Type: application/json
DEBUG:http.client:header: Content-Length: 366
DEBUG:http.client:header: Connection: keep-alive
DEBUG:http.client:header: Server: gunicorn/19.9.0
DEBUG:http.client:header: Access-Control-Allow-Origin: *
DEBUG:http.client:header: Access-Control-Allow-Credentials: true
DEBUG:urllib3.connectionpool:http://httpbin.org:80 "GET /get?foo=bar&baz=python HTTP/1.1" 200 366

默认的request ,logging 会记录红色的请求:
比如:
2023-05-19 18:10:59,425 - DEBUG: Starting new HTTP connection (1): http://localhost:5000
2023-05-19 18:10:59,622 - DEBUG: http://localhost:5000 "POST /api/sale/s HTTP/1.1" 200 None


1. 在2023-05-19 18:10:59,425,程序启动了一个到http://localhost:5000的新HTTP连接
2. 在2023-05-19 18:10:59,622,也就是197ms后,通过此连接发送了一个POST /api/sale/s HTTP/1.1请求
3. 服务器返回的状态码是200,表示请求成功
4. 返回的响应内容长度为None,表明此日志没有显示响应内容长度信息



https://stackoverflow.com/questions/16337511/log-all-requests-from-the-python-requests-module

  

posted on 2023-05-20 16:23  bug_x  阅读(61)  评论(0编辑  收藏  举报