【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],
)
需要注意:
- 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
【Azure 环境】【Azure Developer】使用Python代码获取Azure 中的资源的Metrics定义及数据的更多相关文章
- 【Azure Redis 缓存】使用Python代码获取Azure Redis的监控指标值 (含Powershell脚本方式)
问题描述 通过Metrics监控页面,我们能得知当前资源(如Redis)的运行情况与各种指标.如果我们需要把指标下载到本地或者生成JSON数据导入到第三方的监控平台呢?Azure是否可以通过Pytho ...
- 【Azure Developer】Python代码通过AAD认证访问微软Azure密钥保管库(Azure Key Vault)中机密信息(Secret)
关键字说明 什么是 Azure Active Directory?Azure Active Directory(Azure AD, AAD) 是 Microsoft 的基于云的标识和访问管理服务,可帮 ...
- 【python】获取列表中最长连续数字
最近开发遇到一个功能需求,目的是要获取一个AI分析结果中最长连续帧,比如一个视频中连续3帧有人,那么我认为这个视频就是有人,我就要判断这个视频帧列表中是否有连续的三帧有人.本质就是获取列表中的最长连续 ...
- 万答#2,一样的Python代码,为什么可以删表,却不能更新数据
欢迎来到 GreatSQL社区分享的MySQL技术文章,如有疑问或想学习的内容,可以在下方评论区留言,看到后会进行解答 问题 运行下面的这段Python代码,却总是无法更新数据: import pym ...
- pycharm中运行成功的python代码在jenkin中运行问题总结
我们在用selenium+python完成了项目的UI自动化后,一般用jekins持续集成工具来定期运行,python程序在pycharm中编辑运行成功,但在jenkins中运行失败的两个问题,整理如 ...
- python,如何获取字符串中的子字符串,部分字符串
说明: 比如有一个字符串,python,如何就获取前3位,或者后2位.在此记录下. 操作过程: 1.通过分割符的方式,下标的方式,获取字符串中的子串 >>> text = 'pyth ...
- 当From窗体中数据变化时,使用代码获取数据库中的数据然后加入combobox中并且从数据库中取得最后的结果
private void FormLug_Load(object sender, EventArgs e) { FieldListLug.Clear();//字段清除 DI = double.Pars ...
- 【Azure Developer】使用Postman获取Azure AD中注册应用程序的授权Token,及为Azure REST API设置Authorization
Azure Active Directory (Azure AD) is Microsoft's cloud-based identity and access management service, ...
- 编写python代码获取4k高清壁纸
Huskiesir最近在研究python爬虫大约俩周了吧,由于比较懒,也没把具体研究的过程与经验写下来,实在是一大憾事.这次直接上干货,代码送给大家: import re import request ...
随机推荐
- Netty学习摘记 —— 初步认识Netty核心组件
本文参考 我在博客内关于"Netty学习摘记"的系列文章主要是对<Netty in action>一书的学习摘记,文章中的代码也大多来自此书的github仓库,加上了一 ...
- canvas动画—圆形扩散、运动轨迹
介绍 在ECharts中看到过这种圆形扩散效果,类似css3,刚好项目中想把它用上,but我又不想引入整个echart.js文件,更重要的是想弄明白它的原理,所以自己动手.在这篇文章中我们就来分析实现 ...
- java中请给一个Abstract类实现接口的实例!
2.Abstract类实现接口 马克-to-win:如果实现某接口的类是abstract类,则它可以不实现该接口所有的方法.但其非abstract的子类中必须拥有所有抽象方法的实在的方法体:(当然它a ...
- Android 遮罩层效果--制作圆形头像
(用别人的代码进行分析) 不知道在开发中有没有经常使用到这种效果,所谓的遮罩层就是给一张图片不是我们想要的形状,这个时候我们就可以使用遮罩效果把这个图片变成我们想要的形状,一般使用最多就是圆形的效果, ...
- java中递归的用法和例子
递归 直接或者间接调用自己, public class Test{ public static void main(String[] args){ int i = 5; ...
- mixin和composition api
1. 这两个都是实现组件逻辑复用的法宝 2. composition api是vue3的, composition api的出现就是解决mixins的不足之处的 一. mixin 回顾下mixin, ...
- js 图片上传给后台的3种格式
1. file格式 (创建formData来完成file上传) 我们的接口需求: 代码: <input type="file" id="imgfile" ...
- 最小栈问题:题目描述:设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
MinStack minStack = new MinStack();minStack.push(-2);minStack.push(0);minStack.push(-3);minStack.get ...
- setTimeout中第一个参数
永远不要传递字符串作为setTimeout的第一个参数!!!记住第一个参数只允许函数,或者匿名函数!因为传递字符串有陷阱啊!!它就是披着羊皮的eval啊!!而且上下文会变成全局啊!! 第一个参数为可执 ...
- Blazor组件自做二 : 使用JS隔离制作手写签名组件
Blazor组件自做二 : 使用JS隔离制作手写签名组件 本文相关参考链接 JavaScript 模块中的 JavaScript 隔离 Viewer.js工程 Blazor组件自做一 : 使用JS隔离 ...