前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >将Azure Application Insights的数据整合到你自己的应用中

将Azure Application Insights的数据整合到你自己的应用中

作者头像
Edi Wang
发布2019-07-15 11:51:44
1.6K0
发布2019-07-15 11:51:44
举报
文章被收录于专栏:汪宇杰博客

微软智慧云Azure有一个非常强大的监视工具, 称为Application Insights。它可以监视我们Web应用程序的各个方面,包括客户端和服务器指标、错误详细信息、性能等。我的博客也在使用Application Insights,但每次我想要查看数据时, 我都必须转到Azure门户,即使是PV或服务器响应时间等基本指标也是如此。我希望我能在自己的应用程序中的获取这些数据,并仅将Azure门户用于高级分析方案。本文将给出解决方案。

Application Insights 提供了一组 REST API,使我们的开发人员可以使用 Azure 中的相同数据。我在 C# 中使用此 API 来检索我需要的数据,您也可以使用 jQuery、JAVA、PHP 或任何您喜欢的方法来完成它。

01

获取应用程序标识及API Key

打开Azure门户,在Application Insights页面下点击 API Access

复制Application ID,之后我们用得着。然后点击 Create API key

输入一个描述,并选择 Read telementry 复选框。然后点击 Generate key

你的Key创建完成后,复制并保存到安全的位置,因为这个key只会在Azure门户里显示这么一次!

02

在 API Explorer 中测试

在浏览器里打开 https://dev.applicationinsights.io/apiexplorer/metrics,用你的 Application ID API Key 测试REST API。

例如,我需要获取过去24小时的PV,测试如下:

我们能够在API Explorer里看到生成的地址及参数信息:

GET /v1/apps/YOUR-APPLICATION-ID/metrics/pageViews/count?timespan=P1D&aggregation=sum HTTP/1.1

Host: api.applicationinsights.io

x-api-key: YOUR-API-KEY

返回内容是Json格式的字符串

HTTP/1.1 200

content-type: application/json; charset=utf-8

{

"value": {

"start": "2018-12-17T11:17:13.443Z",

"end": "2018-12-18T11:17:13.443Z",

"pageViews/count": {

"sum": 709

}

}

}

这意味着API能够正常工作。我们会用相同的终端地址去整合到我们自己的应用里。

03

整合到ASP.NET Core应用中

这一步完全取决于你自己的实现方式,下面的样例代码仅仅是我在自己博客系统里使用的,满足我自己需求的,所以会有很多硬编码的地方。

我的C# MetricsReader

public class MetricsReader

{

private const string AzureAppInsightApiEndpointAddress = "https://api.applicationinsights.io/v1/apps/{0}/{1}/{2}?{3}";

private const string AzureAppInsightAppId = "<YOUR-APPLICATION-ID>";

private const string AzureAppInsightApiKey = "<YOUR-API-KEY>";

public async Task<dynamic> GetP1DIntMetrics(string query, string aggregation)

{

var response = await GetAppInsightDataAsync(query, $"timespan=P1D&aggregation={aggregation}");

if (response.IsSuccess)

{

var obj = JsonConvert.DeserializeObject<dynamic>(response.Item);

return obj;

}

return null;

}

public async Task<Response<string>> GetAppInsightDataAsync

(string queryPath, string parameterString)

{

return await GetAppInsightDataAsync(AzureAppInsightAppId, AzureAppInsightApiKey, "metrics", queryPath, parameterString);

}

private async Task<Response<string>> GetAppInsightDataAsync

(string appid, string apikey, string queryType, string queryPath, string parameterString)

{

var client = new HttpClient();

client.DefaultRequestHeaders.Accept.Add(

new MediaTypeWithQualityHeaderValue("application/json"));

client.DefaultRequestHeaders.Add("x-api-key", apikey);

var req = string.Format(AzureAppInsightApiEndpointAddress, appid, queryType, queryPath, parameterString);

var response = client.GetAsync(req).Result;

if (!response.IsSuccessStatusCode)

{

return new FailedResponse<string>(ResponseFailureCode.RemoteApiFailure)

{

Message = response.ReasonPhrase

};

}

var result = await response.Content.ReadAsStringAsync();

return new SuccessResponse<string> { Item = result };

}

}

在我的ASP.NET Controller里,我有一个方法去调用MetricsReader

[HttpGet("getpv")]

public async Task<int> GetPageViewsForLast24Hours()

{

var response = await _metricsReader.GetP1DIntMetrics(MetricId.PageViewsCount, MetricAggregation.Sum);

if (null != response)

{

return (int)response.value[MetricId.PageViewsCount].sum;

}

return -1;

}

最后,在前端页面上,我用jQuery去获取里面的值

var aiMetricReader = {

getMetricsNumber: function(url, funcSuccess) {

$.ajax({

url: url,

datatype: 'json',

success: function (data) {

funcSuccess(data);

},

error: function(e) {

toastr.error(e);

}

});

}

};

aiMetricReader.getMetricsNumber('getpv',

function (data) {

$("#page-views").html(data);

});

现在,我可以在博客的管理后台里构建一个简单的dashboard,仅仅显示我最关心的数据。

对于复杂的场景和完整数据,我依然可以去Azure门户查看。

Application Insights (应用程序洞察服务)

https://docs.microsoft.com/en-us/azure/application-insights/app-insights-overview

REST API 文档

https://dev.applicationinsights.io/quickstart

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-12-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 汪宇杰博客 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档