Azure Application Insights REST API使用教程
- 2019 年 10 月 3 日
- 筆記
本文是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: 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,否則調用介面會失敗,返回認證錯誤的消息,比如,
在API Access選項下選擇Create API key,填寫描述並勾選”Read telemetry”。
點擊Generate key,會得到一個key字元串。注意,在這裡必須保存key,因為關閉頁面之後,無法通過任何方式再查詢到生成的key。如果key丟失,只能重建另一個key。
訪問
有了Application ID和API key,就可以訪問API了。
這個頁面有一個很好的例子,可以參考:
可以用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,逐個放入任務列表中,最後統一併發執行、獲取結果。
其中使用了request發送http請求、asyncio實現並發。
總結
本文是我關於Azure Application Insights REST API的知識和實踐的總結。這不是Azure Application Insights REST API的全部,可以參考微軟文檔以獲取更多資訊。