如何在Azure Application Insights中启用Python函数应用的HTTP请求日志
问题:Azure函数应用中无法捕获Python HTTP请求日志到Azure Monitor
我需要调试Python函数应用中的API调用,但无法让HTTP请求日志显示在Azure Monitor中。已在代码中添加如下配置:
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请求日志?
解决方案
核心问题说明
HTTPConnection.debuglevel = 1是让urllib3直接将调试信息输出到sys.stderr,而非通过Python的logging模块发射日志事件,因此你的AzureLogHandler无法捕获这些内容。必须通过配置urllib3的日志器,让它将日志注入到Python日志系统,才能被Azure Monitor接收。
具体实现步骤
改用OpenTelemetry集成(官方推荐)
旧版AzureLogHandler已被弃用,官方推荐使用OpenTelemetry SDK,兼容性更强、功能更完善。- 安装依赖:
pip install azure-monitor-opentelemetry - 代码配置示例:
import logging from azure.monitor.opentelemetry import configure_azure_monitor import urllib3 import requests # 初始化Azure Monitor(替换为你的连接字符串) configure_azure_monitor(connection_string="InstrumentationKey=<你的密钥>") # 开启urllib3的DEBUG级日志 urllib3_logger = logging.getLogger("urllib3") urllib3_logger.setLevel(logging.DEBUG) urllib3_logger.propagate = True # 同步开启requests库的日志(如果使用requests调用API) requests_logger = logging.getLogger("requests") requests_logger.setLevel(logging.DEBUG) requests_logger.propagate = True
- 安装依赖:
配置函数应用的日志级别
- 在Azure门户进入你的函数应用,依次打开「监控」→「日志」→「日志设置」,将日志级别设置为DEBUG。
- 修改函数应用根目录下的
host.json,添加日志级别配置:{ "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true, "excludedTypes": "Request" } }, "logLevel": { "urllib3": "Debug", "requests": "Debug" } } }
本地验证(可选)
部署前可先在本地测试,确保日志能正常输出到控制台:# 添加控制台日志处理器 console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) urllib3_logger.addHandler(console_handler)运行代码后,若控制台能输出期望的HTTP请求/响应日志,说明配置有效,再部署到Azure即可。
内容的提问来源于stack exchange,提问作者Jeroen Vermunt
相关产品推荐
相关产品推荐

