【Azure 環境】【Azure Developer】使用Python程式碼獲取Azure 中的資源的Metrics定義及資料

路邊兩盞燈發表於2022-05-14

問題描述

使用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],
        )

需要注意:

全部示例程式碼:

# 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)

測試效果圖:

【Azure 環境】【Azure Developer】使用Python程式碼獲取Azure 中的資源的Metrics定義及資料

附錄一:例如在程式碼中獲取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)

以上程式碼執行結果:
【Azure 環境】【Azure Developer】使用Python程式碼獲取Azure 中的資源的Metrics定義及資料

 

附錄二: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

 

相關文章