本文是 Azure Application Insights REST API 的简单介绍, 并会包含一个通过 Python 消费 API 的示例 / 小工具.
新加入的 team 中的一项工作是制作日常的运维报表, 制作方式是手工前往 portal.azure.com, 在网页中多次执行不同的查询语句, 导出 Excel, 之后再人工进行合并, 分组, 汇总, 分析等等. 这是一个繁琐的过程, 其中大部分步骤其实不值得花费人工, 应该交给程序. 为了自动化这一过程, 降低报表的制作成本, 我尝试使用了 Azure Application Insights REST API 查询数据, 使用 python 客户端进行处理, 输出. 下面把相关的一些知识和经验写在这里.
本文链接: https://www.cnblogs.com/hhelibeb/p/11543295.html
原创内容, 转载请注明
Application Insights
Application Insights 是 Azure 平台的监控功能的一部分, 用于收集, 分析和处理来自 Azure 或其它本地环境的遥测数据. 它包含强有力的分析工具, 可以帮助你发现问题, 诊断问题, 理解用户在 App 上的行为, 可以支持你持续地改进应用的性能和可用性. 它可以和 DevOps 过程集成, 和很多开发工具有连接点.
它支持多种语言和框架, 比如. NET, Java, 和 Node.JS 等.
更多信息, 参考: What is Application Insights?
Application Insights REST API
除了在 Azure 中使用外, Application Insights 收集的数据也可以通过 REST API 获取, 这使得你可以用自己的其它应用来使用相关数据. API 可以分为 3 种:
Metrics: 用于查询聚合结果, 比如一定时间范围内的系统异常总数量.
Events: 使用 OData 语法访问 event 数据, 支持 $filter, $orderBy, $search, $apply, $top, $skip and $format, 可以返回单独的 event 数据或者 event 集的聚合数据.
Query: 允许用户发送和在 Application Insights Analytics 中一样的 Query 查询数据, 返回数据的同时也会返回数据的 schema. 这是我用到的类型.
格式
API 的格式如下,
https://{hostname}/{API-version}/apps/{resource}/{area}/[path]?[parameters]
其中,
hostname: http://api.applicationinsights.io/
resource: Application ID , 也就是你的 Application Insights App 的唯一标识符, 可以在 App 的 API Access 选项中看到, 见下图.(注意: 这不是 Instrumentation Key, 不要用错)
API-version: 路径中需要包含 API versions,Beta 或 v1.
area: 3 中查询类型之一 metrics, events 或 query.
path: 查询的详细信息, 比如要查询哪个 metric.
parameters: 和 path 相关的具体参数.
(这里是有关 Public API format 的部分, 此外还有 Azure API format)
认证
需要使用上文提到的 Application ID 和下面提到的 API Key 来访问 API, 否则调用接口会失败, 返回认证错误的消息, 比如,
AuthorizationRequiredError:"Valid authentication was not provided".
在 API Access 选项下选择 Create API key, 填写描述并勾选 "Read telemetry".
点击 Generate key, 会得到一个 key 字符串. 注意, 在这里必须保存 key, 因为关闭页面之后, 无法通过任何方式再查询到生成的 key. 如果 key 丢失, 只能重建另一个 key.
访问
有了 Application ID 和 API key, 就可以访问 API 了.
这个页面有一个很好的例子, 可以参考:
GET/Query
可以用 postman 之类的工具测试 http 请求.
自己写的 query 工具
因为程序可能需要对不同的 Application Insight 的不同的 API 执行不同的 Query, 因此, 基本的处理思路是在配置文件中配置相关信息, 程序从配置文件中读取需要执行的全部 query, 逐一查询后, 返回结果列表.
下面是 JSON 格式的配置文件 (profile.JSON) 和 python 代码.
配置文件
- {
- "application_insight": {
- "host": "api.applicationinsights.io",
- "apps": {
- "my-app-insights": {
- "id": "d1e9f429-c437-6034b32df878",
- "description": "it is an example",
- "apis": {
- "exception_monitor": {
- "description": "daily report",
- "key": "01234qwerrttyypolmknbshjdfggu",
- "version": "v1"
- }
- }
- }
- },
- "queries": [
- {
- "name": "query1",
- "app": "my-app-insights",
- "api": "exception_monitor",
- "statement": "exceptions | where operation_Name == \"\"",
- "time_field_name": "timestamp"
- },
- {
- "name": "query2",
- "app": "my-app-insights",
- "api": "exception_monitor",
- "statement": "exceptions | where operation_Name contains \"AdapterV1\"",
- "time_field_name": "timestamp"
- }
- ],
- "default_filter": {
- "time_range": "between( endofday( now(), -8) .. endofday( now(), -1) )"
- }
- }
- }
说明,
host: 固定值 http://api.applicationinsights.io/
apps:Application Insight 相关数据.
apis:API 相关数据.
queries: 需要执行的 query.
default_filter: 默认的查询条件, 目前只有默认时间功能, 例子里的条件是最近 7 个整天.
查询
查询代码如下:
- import requests
- import JSON
- import asyncio
- async def request_get(url, headers, name):
- return {name: JSON.loads(requests.get(url, headers=headers).text)}
- async def __execute_query(config):
- default_filter = config["default_filter"]
- http_requests = []
- for query in config["queries"]:
- App = config["apps"][query["app"]]
- API = App["apis"][query["api"]]
- query_url = f'''https://{config["host"]}/{api["version"]}/apps/{app["id"]}/query?query={query["statement"]}'''
- if query["time_field_name"] and default_filter["time_range"]:
- query_url = query_url + f'''and {query["time_field_name"]} {default_filter["time_range"]}'''
- headers = {'X-Api-Key': API["key"]}
- http_requests.append(request_get(query_url, headers, query["name"]))
- return await asyncio.gather(*http_requests)
- def execute_query():
- with open('profile.json', 'r') as config_file:
- query_config = JSON.load(config_file)["application_insight"]
- return asyncio.run(__execute_query(query_config))
基本思路是从配置文件加载 queries, 逐个放入任务列表中, 最后统一并发执行, 获取结果.
其中使用了 https://2.python-requests.org//zh_CN/latest/ 发送 http 请求, 实现并发.
总结
本文是我关于 Azure Application Insights REST API 的知识和实践的总结. 这不是 Azure Application Insights REST API 的全部, 可以参考微软文档以获取更多信息.
来源: https://www.cnblogs.com/hhelibeb/p/11543295.html