Search code examples
azurepowershellazure-metrics-advisor

How can i get the CPU usage for an Azure app service using Powershell?


I need to get some metrics for Azure an app service . Values are the CPU (in %) and Memory consumed ( in %). I want to report if for example the CPU is high for a certain period of time , in order to give an indication that the app service is consuming high memory or resources and then send an email .

I am currently using

Get-AzMetricDefinition -ResourceId 
"/subscriptions/<subscriptionid>/resourceGroups/Default-Web- 
 EastUS/providers/microsoft.web/sites/website2" -DetailedOutput -MetricName 
"BytesSent,CpuTime"

But from this how can i get the % CPU and % Memory. Or is there a different Powershell command ?


Solution

  • To get the CPU usage for an Azure app service using PowerShell:

    There is an Azure PowerShell command called Get-AZMetric to get all the metrics data from a particular resource (Eg: App Service). However, CPU % is not a supported argument for Get-AZMetric, if you copy the resourceID of the Web App properities as it is a cloud service ID.

    We can achieve it for overall AppServicePlan as CPU % supports here.

    If the app services hosted in premium, standard and basic plans, CPU% will comes because of scaling out feature whereas CPU_Time is helpful when hosted in free or the shared app service plans.

    get-azmetric -resourceID "/subscriptions/<subscriptionID>/resourceGroups/<resourceGroupName>/providers/Microsoft.Web/sites/<AppService>" -MetricName "CpuTime"  -DetailedOutput
    

    enter image description here

    After investigating, I've found a way to achieve it with the help of AppServicePlan by taking resourceID as shown:

    enter image description here

     az monitor metrics list --resource "/subscriptions/<subscriptionID>/resourceGroups/<resourceGroupName>/providers/Microsoft.Web/serverfarms/<AppservicePlan>" --metrics "CpuPercentage","MemoryPercentage"
    

    Metrics for CPU Percentage:

    enter image description here

    Metrics for Memory Percentage:

    enter image description here

    Note:

    1. Check the supported metrics through portal by clicking on "Diagnose and solve problems" if needed.

    enter image description here

    1. Issues with AppService environments