问题描述
我正在尝试使用PerformanceCounters
读取我的应用程序的CPU和内存使用情况.代码:
I'm trying to read the CPU and Memory usage for my app using PerformanceCounters
.code:
PerformanceCounter cpuCounter;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
var result = cpuCounter.NextValue();//ERROR HERE
我收到一个未经授权的异常.我该如何解决?
I'm getting a Unauthorized exception.How can I work around this?
我试图为处理器数量和内存设置当前实例名称,但是没有运气...
Edit 1:
I tried to set the current instance name for both the processor count and the memory without luck...
.ToString()
是
推荐答案
根据异常信息,它表明我们无权访问Performance Monitor.由于WebApp是沙盒,如果我们使用Azure WebApp ,我们无权这样做.
According to the exception information, it indicates that we have no access to Performance Monitor. As WebApp is a sandbox, if we use the Azure WebApp, we have no access to do that.
我的建议是我们可以使用Application Insight来做到这一点.我们需要为WebApp配置Application Insight,更多详细信息,请参阅文档.关于Application Insight中的性能计数器,我们可以参考此教程.
My suggestion is that we could use Application Insight to do that. We need to configurate Application Insight for WebApp, more details please refer to the document. About Performance Counters in the Application Insight, we could refer to this tutorials.
如果我们尝试使用Application Insight API,则需要创建Apikey .我们还可以从文档中获取演示代码.它对我来说正常工作.
If we try to use Application Insight API, we need to create a Apikey. We also could get demo code from the document. It works correctly for me.
static void Main(string[] args)
{
var applicationId = "xxxxxxxx";
var applicationKey = "xxxxxxxx";
var queryPath = "performanceCounters/processCpuPercentage";
var queryType = "metrics";
var str = GetTelemetry(applicationId, applicationKey, queryType, queryPath, "");
}
public static string GetTelemetry(string appid, string apikey,
string queryType, string queryPath, string parameterString)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("x-api-key", apikey);
var req = string.Format(Url, appid, queryType, queryPath, parameterString);
HttpResponseMessage response = client.GetAsync(req).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
else
{
return response.ReasonPhrase;
}
}
这篇关于Azure-如何读取Web应用程序的cpu和内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!