如何通过Python SDK获取基于EventHub的日志型自定义指标数据?
使用Python SDK获取Azure日志型指标命名空间的自定义指标平均值
1. 安装依赖包
先安装所需的Azure SDK工具包:
pip install azure-monitor-query azure-identity
2. 核心查询代码
替换占位符为你的实际参数,即可直接运行获取结果:
from azure.monitor.query import MetricsQueryClient from azure.identity import DefaultAzureCredential from datetime import timedelta # 替换为你的实际资源信息 RESOURCE_ID = "/subscriptions/你的订阅ID/resourceGroups/你的资源组/providers/Microsoft.EventHub/namespaces/你的EventHub命名空间" METRIC_NAME = "你的自定义指标名称" # 初始化客户端(自动处理身份认证) credential = DefaultAzureCredential() metrics_client = MetricsQueryClient(credential) # 查询最近15分钟的指标平均值 query_result = metrics_client.query_resource( resource_id=RESOURCE_ID, metric_names=[METRIC_NAME], timespan=timedelta(minutes=15), # 也可使用ISO字符串格式:"PT15M" aggregations=["average"], # EventHub日志型指标的固定命名空间值 namespace="Microsoft.EventHub/namespaces" ) # 解析并输出结果 for metric in query_result.metrics: print(f"指标名称: {metric.name.localized_value}") for series in metric.timeseries: for data_point in series.data: print(f"[{data_point.timestamp}] 平均值: {data_point.average}")
关键注意事项
- 认证逻辑:
DefaultAzureCredential自动适配多种场景:本地开发时先执行az login通过Azure CLI认证;Azure托管服务(如VM、函数应用)直接使用托管身份,无需手动配置密钥。 - 命名空间必填:日志型指标必须指定
namespace参数,EventHub对应的固定值为Microsoft.EventHub/namespaces。 - 时间范围格式:除了
timedelta,也支持ISO 8601格式字符串,比如最近15分钟可写为"PT15M"。
内容的提问来源于stack exchange,提问作者jakeMantle
相关产品推荐
相关产品推荐

