在c#中获取Azure vm的指标

时间:2018-01-04 16:38:31

标签: c# azure virtual-machine metrics

我有下面的代码来检索Azure虚拟机的CPU百分比。 我想要网络输入,网络输出,磁盘读取字节,磁盘写入字节,磁盘读取操作,磁盘写入操作的指​​标。我为queryString提供的内容似乎并不重要,我总是得到cpu百分比。我如何获得其他指标?

private void test()
{
    string vmName = "myVM";
    string resourceId = "/subscriptions/{subscriptionId}/resourceGroups/ResourceGroupWest/providers/Microsoft.Compute/virtualMachines/" + vmName;
    var subscriptionId = "mySubscriptionID";
    var clientId = "myClientID";
    var secret = "myKey";
    var tenantId = "myTenantID";
    resourceId = resourceId.Replace("{subscriptionId}", subscriptionId);

    MonitorClient readOnlyClient = AuthenticateWithReadOnlyClient(tenantId, clientId, secret, subscriptionId).Result;

    string queryString = "name.value eq 'CpuPercentage'";
    ODataQuery<MetadataValue> odataQuery = new ODataQuery<MetadataValue>(queryString);
    var vals = readOnlyClient.Metrics.List(resourceId, odataQuery );
    foreach (MetricValue v in vals.Value[0].Timeseries[0].Data)
    {
        if (v.Average != null)
        {
            totalAverage += v.Average.Value;
        }
    }
    totalAverage = totalAverage / vals.Value[0].Timeseries[0].Data.Count;
}

private static async Task<MonitorClient> AuthenticateWithReadOnlyClient(string tenantId, string clientId, string secret, string subscriptionId)
{
    // Build the service credentials and Monitor client            
    var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);            
    var monitorClient = new MonitorClient(serviceCreds);           
    monitorClient.SubscriptionId = subscriptionId;            
    return monitorClient;        
}

1 个答案:

答案 0 :(得分:2)

  

对于我为queryString提供的内容似乎并不重要,我总是得到cpu百分比。我如何获得其他指标?

您可以从Supported metrics with Azure Monitor获取其他指标名称。 如果您想获得多个指标,可以使用附加指标。 CPU指标是Azure VM的默认指标

Remove-AzureRmResource -ApiVersion $Apiversion  -ResourceGroupName $ResourceGroupName -ResourceName $ResourceName -ResourceType microsoft.web/sites/<Webjob-type>/<Webjob-name> -Force

我之前也做了一个演示,更多细节请参考另一个SO thread

 var queryString = "(name.value eq 'Disk Write Operations/Sec' or  name.value eq 'Percentage CPU' or  name.value eq 'Network In' or  name.value eq 'Network Out' or  name.value eq 'Disk Read Operations/Sec' or  name.value eq 'Disk Read Bytes' or  name.value eq 'Disk Write Bytes')";