如何在 Azure 应用程序洞察中启用 HTTP 请求日志记录

问题描述 投票:0回答:1

我想在 Python 函数应用程序中调试 API 调用,但无法在 Azure 监视器中显示 HTTP 请求的日志。

在代码中,我添加了以下设置:

http_client.HTTPConnection.debuglevel = 1
    
logger = logging.getLogger("requests.packages.urllib3")
    
sh = AzureLogHandler(connection_string='InstrumentationKey=<instrumentation key>')
logger.addHandler(sh)
logger.propagate = True
logger.setLevel(logging.DEBUG)

我希望它给出以下输出:

send: b'GET <some_url> HTTP/1.1\r\nHost: <some_host>\r\nUser-Agent: python-requests/2.31.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\napikey: <some_key>\r\n\r\n'
reply: 'HTTP/1.1 200 \r\n'
header: API-Version: 1.4.1
header: strict-transport-security: max-age=157680000 ; includeSubDomains
header: Content-Encoding: gzip
header: Content-Type: application/json
header: Content-Length: 285
header: Date: Sat, 12 Aug 2023 12:32:38 GMT
header: Keep-Alive: timeout=60
header: Connection: keep-alive
header: Server: unknown

我的函数监视器中没有出现任何日志,我怀疑这与日志处理程序未注册

http_client.HTTPConnection.debuglevel = 1
有关。

如何在 Azure 中启用 HTTP 请求的日志记录?

python-3.x azure-functions httprequest python-logging
1个回答
0
投票

我尝试使用下面的函数代码来请求 API 并将其日志跟踪发送到 Application Insights,它成功运行,如下所示:-

init.py:-

import azure.functions as func
import http.client
import logging

def main(req: func.HttpRequest) -> func.HttpResponse:
    
    http.client.HTTPConnection.debuglevel = 1
    logger = logging.getLogger("requests.packages.urllib3")
    logger.setLevel(logging.DEBUG)    
    sh1 = AzureLogHandler(connection_string='InstrumentationKey=b61d789ad;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/')
    logger.addHandler(sh1)
    logger.propagate = True    
    conn = http.client.HTTPSConnection("reqres.in")
    conn.request("GET", "/api/users/2")
    response = conn.getresponse()    
    logger.debug("Request Headers:\n%s", conn._buffer)
    logger.debug("Response:\n%s %s\n%s", response.status, response.reason, response.read())
    conn.close()

    return func.HttpResponse("HTTP request completed Rithwik")

class AzureLogHandler(logging.Handler):
    def __init__(self, connection_string):
        super(AzureLogHandler, self).__init__()
        self.connection_string = connection_string

    def emit(self, record):        
        pass

Output:-

Local:-

enter image description here

我在Azure Portal中部署了该功能。当我测试它时,日志已成功发送到 Azure 应用程序洞察,请参阅下文:-

Portal Output:-

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.