Azure Application Insights REST API Tutorial

This article is a brief introduction to Azure Application Insights REST API, and will include a consumer by way of example Python API's / gadget.

The new job is added to the team making the daily operation and maintenance reporting, production methods go hand portal.azure.com, execute the query multiple times in different pages, export excel, and then manually after the merger, grouping, compilation, analysis and so on. This is a tedious process, in which most of the steps is not really worth the labor, should be handed over to the program. To automate this process, reduce production cost report, I try to use the Azure Application Insights REST API to query the data, using the python client for processing and output. Here some of the relevant knowledge and experience to write here.

 

This link: https://www.cnblogs.com/hhelibeb/p/11543295.html 

Original content, please indicate

Application Insights

Application Insights is part of the monitoring function Azure platform for collecting, analyzing and processing telemetry data from Azure or other local environment. It contains a powerful analysis tool that can help you identify problems and diagnose problems, understand user behavior on the app, you can support continuous improvement in performance and availability of applications. It can and DevOps process integration, and development tools have many connection points.

It supports multiple languages ​​and frameworks such as .NET, Java, Node.js and so on.

For more information, refer to: the What IS the Application Insights?

 

 

Application Insights REST API

In addition to using the Azure, the Application Insights data collected can also be obtained through the REST API, which allows you to use your other applications to use the data. API can be divided into three kinds:

  1. Metrics : polymerization results for the query, such as the total number of abnormalities within a certain time range.

  2. Events : Use OData syntax to access event data to support $ filter, $ orderBy, $ search , $ apply, $ top, $ skip and $ format, a separate event may return event data or aggregated data sets.

  3. Query : allows users to send and in Application Insights Analytics as the Query query data, the data returned will also return schema data. This is the type I used.

format

The API format,

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

among them,

  1. hostname: api.applicationinsights.io
  2. Resource:  the Application ID  , which is a unique identifier for your Application Insights app, you can see the API Access option in the app, see below. (Note: This is not Instrumentation Key, do not wrong)
  3. api-version: the path needs to contain the API versions , Beta or v1.
  4. area: 3 in one query type metrics, events or query.
  5. path: For more information queries, such as queries to which metric. 
  6. parameters: specific and path-related parameters.

(Here is the section on Public API format, in addition to Azure API format )

Authenticate

Application ID is required mentioned above and below mentioned API Key to access the API, or call interface fails, returns an authentication error messages, for example,

AuthorizationRequiredError:"Valid authentication was not provided"。
 

Select Create API key in the API Access option, fill in the description and check the "Read telemetry".

Click Generate key, you will be a key string. Note that here must save the key , because after closing the page, can no longer query the key generated by any means. If the key is lost, only to rebuild another key.

access

With Application ID and API key, you can access the API.

This page has a good example, you can refer to:

GET/Query

Postman can use tools such as test http request.

Write your own query tool

Because the program may require different API to perform different for different Query Application Insight, therefore, the basic idea is to deal with the configuration information in the configuration file, the program reads all of the query to be executed from the configuration file, one by one inquiry, Back to results list.

The following is json configuration file format (profile.json) and python code.

Profiles

{
    "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) )"
        }
    }
}

Description,

  • host: fixed value http://api.applicationinsights.io
  • apps: Application Insight data.
  • apis: Api-related data.
  • queries: query to be executed.
  • default_filter: The default query, only the default function of time, in the example of the recent seven day conditions.

Inquire

Query code is as follows:

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))

 

The basic idea is loaded from the configuration file queries, one by one into the task list, and finally unified concurrent execution, get results.

Wherein the request sending http request, ASYNCIO concurrency.

to sum up

This article is a summary of my knowledge and practice Azure Application Insights REST API's. All this is not the Azure Application Insights REST API, refer to Microsoft's documentation for more information.

Guess you like

Origin www.cnblogs.com/hhelibeb/p/11543295.html