问题描述
使用Python SDK来获取Azure上的各种资源的Metrics的名称以及Metrics Data的示例
问题解答
通过 azure-monitor-query ,可以创建一个 metrics client,调用 client.list_metric_definitions 来获取Metrics 定义,然后通过 client.query_resource 获取Metrics data。
关键函数为:
#第一步:定义 client client = MetricsQueryClient(credential=credential, endpoint='https://management.chinacloudapi.cn', audience='https://management.chinacloudapi.cn') #第二步:获取metrics name response = client.list_metric_definitions(metric_uri) #第三步:获取 metrcis data response = client.query_resource( resource_uri=url, metric_names=[name], timespan=timedelta(hours=2), granularity=timedelta(minutes=5), aggregations=[MetricAggregationType.AVERAGE], )
需要注意:
- endpoint 和 audience 需要根据代码的使用Azure环境不同而改变,以上为中国区Azure的Endpoint。与Global Azure 终结点对比文档见:https://docs.microsoft.com/en-us/azure/china/resources-developer-guide#check-endpoints-in-azuredevelop
- metrics_url 可以在Azure 门户中的“属性”页面获取,当然也可以通过Python对于资源的SDK进行获取。示例代码见附录一.
全部示例代码:
# import required package from ast import Try from warnings import catch_warnings from datetime import timedelta from azure.monitor.query import MetricsQueryClient, MetricAggregationType from azure.identity import AzureCliCredential ## pip install azure-identity # prepare credential credential = AzureCliCredential() #init metric query client, endpoint need to target China Azure client = MetricsQueryClient(credential=credential, endpoint='https://management.chinacloudapi.cn', audience='https://management.chinacloudapi.cn') def printMetricsDataByName(url, name): ##metrics_uri =metric_uri; ### os.environ.get('METRICS_RESOURCE_URI') response = client.query_resource( resource_uri=url, metric_names=[name], timespan=timedelta(hours=2), granularity=timedelta(minutes=5), aggregations=[MetricAggregationType.AVERAGE], ) for metric in response.metrics: print(metric.name + ' -- ' + metric.display_description) for time_series_element in metric.timeseries: for metric_value in time_series_element.data: print('\tThe {} at {} is {}'.format( name, metric_value.timestamp, metric_value.average )) print("### ..Special Reource URL.. ....") # specific resource uri metric_uri = '/subscriptions/<your-subscriptions-id>/resourceGroups/<your-resource-group>/providers/Microsoft.Cache/Redis/<your-resource-name>' # do query... response = client.list_metric_definitions(metric_uri) for item in response: print(item.name + " ...... Metrics Data ......") try: printMetricsDataByName(metric_uri,item.name) except Exception as e: print(e)
测试效果图:
附录一:例如在代码中获取Redis资源的Resource ID
from azure.mgmt.redis import RedisManagementClient ## pip install azure-mgmt-redis from azure.identity import AzureCliCredential ## pip install azure-identity # prepare credential credential = AzureCliCredential() redisClient = RedisManagementClient(credential, '<YOUR SUB>', base_url='https://management.chinacloudapi.cn', credential_scopes=[https://management.chinacloudapi.cn/.default]) for item in redisClient.redis.list_by_subscription(): print(item.id)
以上代码执行结果:
附录二:credential = AzureCliCredential() 为访问Azure资源时提供认证授权的方法,如果出现权限不够,或者是无法访问的情况,会出现类似如下的提示,需要根据消息提示来解决权限问题。
Code: AuthorizationFailed Message: The client 'xxxxxxxxxxxxxxxxxxx@xxxxx.partner.onmschina.cn' with object id 'xxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx' does not have authorization to perform action 'Microsoft.Insights/metricDefinitions/read' over scope '/subscriptions/xxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx/resourceGroups/xxxx-resource-group/providers/Microsoft.Cache/Redis/redis-xxxxxx/providers/Microsoft.Insights' or the scope is invalid. If access was recently granted, please refresh your credentials.
参考资料
Azure Monitor Query client library Python samples: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-query/samples
Azure China developer guide: https://docs.microsoft.com/en-us/azure/china/resources-developer-guide#check-endpoints-in-azuredevelop