本文是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,否則呼叫介面會失敗,回傳認證錯誤的訊息,比如,
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中使用的Kusto查詢引擎是一個即席查詢引擎(ad-hoc query engine),它會嘗試在記憶體中保存全部相關資料來滿足查詢,這導致查詢可能會無限制地占用服務資源,帶來風險,因此,Kusto提供了一些內置的查詢限制以避免風險,比如,單次查詢的結果大小不可以超過64MB,
更多限制,請參考:Query limits
自己寫的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,逐個放入任務串列中,最后統一并發執行、獲取結果,
其中使用了requests發送http請求、asyncio實作并發,
總結
本文是我關于Azure Application Insights REST API的知識和實踐的總結,這不是Azure Application Insights REST API的全部,可以參考微軟檔案以獲取更多資訊,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/65537.html
標籤:其他
