开发Python版Azure Functions时屏蔽CosmosDB信息日志
屏蔽Azure Functions本地开发中CosmosDB的Info/Verbose日志
我在VS Code本地开发Azure Functions,使用azure.cosmos模块查询远程CosmosDB。每次查询都会在终端输出大量Info/Verbose级别的CosmosDB日志(如下示例),导致难以查看自定义的logging.info()输出。希望设置日志级别,仅保留CosmosDB的Warning/Error日志,或仅显示自定义日志。
需要屏蔽的日志示例:
[2022-08-31T08:50:00.643Z] Request URL: 'https://xxx-norwayeast.documents.azure.com:443/dbs' Request method: 'POST' Request headers: 'Cache-Control': 'no-cache' 'x-ms-version': 'REDACTED' 'x-ms-documentdb-query-iscontinuationexpected': 'REDACTED' 'x-ms-consistency-level': 'REDACTED' 'x-ms-date': 'REDACTED' 'authorization': 'REDACTED' 'Content-Type': 'application/json' 'Accept': 'application/json' 'Content-Length': '12' 'User-Agent': 'azsdk-python-cosmos/4.2.0 Python/3.9.12 (Windows-10-10.0.25188-SP0)' A body is sent with the request
当前配置
host.json
{ "version": "2.0", "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true, "excludedTypes": "Request" } } }, "extensionBundle": { "id": "Microsoft.Azure.Functions.ExtensionBundle", "version": "[2.*, 3.0.0)" }, "extensions": { "durableTask": { "hubName": "%TaskHub%" } } }
function.json
{ "scriptFile": "__init__.py", "bindings": [ { "name": "context", "type": "orchestrationTrigger", "direction": "in" } ] }
解决方案
方法1:通过host.json配置日志过滤
修改host.json的logging节点,添加logLevel配置,指定azure.cosmos模块的日志级别为Warning或更高:
{ "version": "2.0", "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true, "excludedTypes": "Request" } }, "logLevel": { "azure.cosmos": "Warning" } }, "extensionBundle": { "id": "Microsoft.Azure.Functions.ExtensionBundle", "version": "[2.*, 3.0.0)" }, "extensions": { "durableTask": { "hubName": "%TaskHub%" } } }
配置后,终端只会输出azure.cosmos模块的Warning和Error级别日志,自定义的logging.info()输出不受影响。
方法2:在Python代码中直接调整日志级别
如果host.json配置不生效,可在函数代码开头直接修改azure.cosmos模块的日志器级别:
import logging # 获取azure.cosmos模块的日志器 cosmos_logger = logging.getLogger("azure.cosmos") # 设置日志级别为WARNING,仅输出Warning及以上级别日志 cosmos_logger.setLevel(logging.WARNING) # 自定义日志配置(可选,确保自定义日志正常输出) custom_logger = logging.getLogger(__name__) custom_logger.setLevel(logging.INFO)
这种方式直接控制Python日志模块的输出,更精准,适合本地开发调试场景。
内容的提问来源于stack exchange,提问作者Maxime
相关产品推荐
相关产品推荐

