• 【Azure 环境】【Azure Developer】使用Python代码获取Azure 中的资源的Metrics定义及数据


    问题描述

    使用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)
    复制代码

    测试效果图:

    附录一:例如在代码中获取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

     

  • 相关阅读:
    Leetcode算法训练日记 | day32
    Go语言进阶,interface接口,socket套接字
    触发器,寄存器,三态输出电路
    Tensor、Numpy、PIL格式转换以及图像显示
    电脑键盘功能基础知识,快速入门,抓住这份详细教程
    调用google批量翻译接口
    OneNote 教程,如何在 OneNote 中创建更多空间?
    齐家坪水电站施工组织设计(lunwen+任务书+外文翻译+cad图纸)
    Vue绑定样式
    两个shell实用函数:icd和mgrep
  • 原文地址:https://www.cnblogs.com/lulight/p/16269526.html