【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

 

相关文章
|
10月前
|
数据库连接 数据库 Python
Python上下文管理器:告别资源泄露的优雅之道
Python上下文管理器:告别资源泄露的优雅之道
395 87
|
SQL 自然语言处理 数据库
【Azure Developer】分享两段Python代码处理表格(CSV格式)数据 : 根据每列的内容生成SQL语句
本文介绍了使用Python Pandas处理数据收集任务中格式不统一的问题。针对两种情况:服务名对应多人拥有状态(1/0表示),以及服务名与人名重复列的情况,分别采用双层for循环和字典数据结构实现数据转换,最终生成Name对应的Services列表(逗号分隔)。此方法高效解决大量数据的人工处理难题,减少错误并提升效率。文中附带代码示例及执行结果截图,便于理解和实践。
375 5
|
10月前
|
安全 数据库连接 Python
Python中的上下文管理器:优雅地管理资源
Python中的上下文管理器:优雅地管理资源
202 6
|
11月前
|
JavaScript 前端开发 机器人
【Azure Bot Service】在中国区Azure上部署机器人的 Python 版配置
本文介绍了在中国区Azure上使用Python SDK配置Azure Bot Service时遇到的问题及解决方案,涵盖参数设置与适配器配置,适用于希望在Azure中国区部署Python机器人的开发者。
287 9
|
API 开发工具 网络架构
【Azure Service Bus】使用Python SDK创建Service Bus Namespace资源(中国区)
本文介绍了如何使用Python SDK创建Azure Service Bus Namespace资源。首先,通过Microsoft Entra ID注册应用获取Client ID、Client Secret和Tenant ID,完成中国区Azure认证。接着,初始化ServiceBusManagementClient对象,并调用`begin_create_or_update`方法创建资源。
316 30
|
人工智能 安全 Shell
Jupyter MCP服务器部署实战:AI模型与Python环境无缝集成教程
Jupyter MCP服务器基于模型上下文协议(MCP),实现大型语言模型与Jupyter环境的无缝集成。它通过标准化接口,让AI模型安全访问和操作Jupyter核心组件,如内核、文件系统和终端。本文深入解析其技术架构、功能特性及部署方法。MCP服务器解决了传统AI模型缺乏实时上下文感知的问题,支持代码执行、变量状态获取、文件管理等功能,提升编程效率。同时,严格的权限控制确保了安全性。作为智能化交互工具,Jupyter MCP为动态计算环境与AI模型之间搭建了高效桥梁。
860 2
Jupyter MCP服务器部署实战:AI模型与Python环境无缝集成教程
|
Python
在VScode环境下配置Python环境的方法
经过上述步骤,你的VSCode环境就已经配置好了。请尽情享受这扇你为自己开启的知识之窗。如同你在冒险世界中前行,你的探索之路只有越走越广,你获得的知识只会越来越丰富,你的能力只会越来越强。
1259 37
|
数据采集 Web App开发 iOS开发
解决Python爬虫访问HTTPS资源时Cookie超时问题
解决Python爬虫访问HTTPS资源时Cookie超时问题
|
存储 监控 API
【Azure App Service】分享使用Python Code获取App Service的服务器日志记录管理配置信息
本文介绍了如何通过Python代码获取App Service中“Web服务器日志记录”的配置状态。借助`azure-mgmt-web` SDK,可通过初始化`WebSiteManagementClient`对象、调用`get_configuration`方法来查看`http_logging_enabled`的值,从而判断日志记录是否启用及存储方式(关闭、存储或文件系统)。示例代码详细展示了实现步骤,并附有执行结果与官方文档参考链接,帮助开发者快速定位和解决问题。
396 22
|
10月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
1659 102

推荐镜像

更多