Azure Application Insights REST API使用教程


本文是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種:

  1. Metrics: 用於查詢聚合結果,比如一定時間范圍內的系統異常總數量。

  2. Events: 使用OData語法訪問event數據,支持$filter, $orderBy, $search, $apply, $top, $skip and $format,可以返回單獨的event數據或者event集的聚合數據。

  3. Query: 允許用戶發送和在Application Insights Analytics中一樣的Query查詢數據,返回數據的同時也會返回數據的schema。這是我用到的類型。

格式

API的格式如下,

 https://{hostname}/{api-version}/apps/{resource}/{area}/[path]?[parameters]

其中,

  1. hostname: api.applicationinsights.io
  2. resource: Application ID ,也就是你的Application Insights app的唯一標識符,可以在app的API Access選項中看到,見下圖。(注意:這不是Instrumentation Key,不要用錯)
  3. api-version: 路徑中需要包含API versions,Beta或v1。
  4. area: 3中查詢類型之一metrics, events或query。
  5. path: 查詢的詳細信息,比如要查詢哪個metric。 
  6. 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的全部,可以參考微軟文檔以獲取更多信息。

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM