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

简介: 【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

 

相关文章
|
6月前
|
数据采集 Web App开发 数据可视化
Python零基础爬取东方财富网股票行情数据指南
东方财富网数据稳定、反爬宽松,适合爬虫入门。本文详解使用Python抓取股票行情数据,涵盖请求发送、HTML解析、动态加载处理、代理IP切换及数据可视化,助你快速掌握金融数据爬取技能。
3576 1
|
6月前
|
Java 数据挖掘 数据处理
(Pandas)Python做数据处理必选框架之一!(一):介绍Pandas中的两个数据结构;刨析Series:如何访问数据;数据去重、取众数、总和、标准差、方差、平均值等;判断缺失值、获取索引...
Pandas 是一个开源的数据分析和数据处理库,它是基于 Python 编程语言的。 Pandas 提供了易于使用的数据结构和数据分析工具,特别适用于处理结构化数据,如表格型数据(类似于Excel表格)。 Pandas 是数据科学和分析领域中常用的工具之一,它使得用户能够轻松地从各种数据源中导入数据,并对数据进行高效的操作和分析。 Pandas 主要引入了两种新的数据结构:Series 和 DataFrame。
636 0
|
6月前
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
6月前
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
6月前
|
测试技术 Python
Python装饰器:为你的代码施展“魔法”
Python装饰器:为你的代码施展“魔法”
346 100
|
6月前
|
开发者 Python
Python列表推导式:一行代码的艺术与力量
Python列表推导式:一行代码的艺术与力量
522 95
|
7月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
994 102
|
7月前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
429 104
|
7月前
|
人工智能 自然语言处理 算法框架/工具
Python:现代编程的首选语言
Python:现代编程的首选语言
336 103
|
7月前
|
机器学习/深度学习 人工智能 数据挖掘
Python:现代编程的首选语言
Python:现代编程的首选语言
283 82

推荐镜像

更多