从Python类中的静态方法全局打开httplib日志记录?

2024-06-02 07:40:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类,它为请求使用的httplib库打开详细日志记录。我想在运行任何请求代码并打开日志记录之前调用它。但是,在我调用它之后,日志记录并没有打开。如果我将代码从静态方法中取出,并将其放在主python文件中的函数中并运行它,那么它就可以工作了。但是,我希望它打包成一个类和一个静态方法

import logging
import http.client

class HttpClientUtilities:

    @staticmethod
    def enable_logging(level=logging.DEBUG):

        global http

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

        """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

我这样称呼它:

from HttpClientUtilities import HttpClientUtilities

HttpClientUtilities.enable_logging()

#then here i run some methods from other classes which use the requests library

在enable_logging方法中,我使用了全局http,因此它应该引用全局http对象


1条回答
网友
1楼 · 发布于 2024-06-02 07:40:46

我在这里找到了一个更简单的解决方案:urllib3 debug request header

通过覆盖默认调试级别:

# You'll need to do this before urllib3 creates any http connection objects
import http.client
http.client.HTTPConnection.debuglevel = 5

相关问题 更多 >