Search code examples
azureazure-resource-managerazure-monitoringazure-monitorazure-sdk-for-java

How Create Azure Monitor Metrics Alert using Java SDK


I am working on a Java project and need assistance with creating an Azure Monitor metrics alert programmatically using the Azure Java SDK.

I would like to be able to set up an alert based on a specific metric and threshold. For example, I want to create an alert when the CPU usage of a virtual machine exceeds a certain percentage.

Could someone provide me with an example code snippet or guide me on how to achieve this using the Azure Java SDK? Any help or suggestions would be greatly appreciated.


Solution

  • Create an alert when the CPU usage of a virtual machine exceeds a certain percentage.

    You can use the below code to create an alert rule using Azure java sdk.

    Code:

    import com.azure.core.credential.TokenCredential;
    import com.azure.core.http.policy.HttpLogDetailLevel;
    import com.azure.core.management.AzureEnvironment;
    import com.azure.identity.DefaultAzureCredentialBuilder;
    import com.azure.resourcemanager.monitor.models.MetricAlert;
    import com.azure.resourcemanager.monitor.models.MetricAlertRuleCondition;
    import com.azure.resourcemanager.monitor.models.MetricAlertRuleTimeAggregation;
    import com.azure.core.management.profile.AzureProfile;
    import com.azure.resourcemanager.AzureResourceManager;
    
    
    import java.time.Duration;
    
    
    public final class App {
    
        public static boolean runSample(com.azure.resourcemanager.AzureResourceManager azureResourceManager) {
    
                String rgName="your-resourcegrp";
                MetricAlert ma = azureResourceManager.alertRules().metricAlerts().define("Critical performance alert")
                        .withExistingResourceGroup(rgName)
                        .withTargetResource("/subscriptions/xxxxx/resourceGroups/xxxproviders/Microsoft.Compute/virtualMachines/vm678")
                        .withPeriod(Duration.ofMinutes(5))
                        .withFrequency(Duration.ofMinutes(1))
                        .withAlertDetails(3, "This alert rule is for U5 - Single resource-multiple criteria - with dimensions - with star")
                        .withActionGroups("/subscriptions/xxxxxx/resourceGroups/xxxx/providers/microsoft.insights/actiongroups/actiongroup1")
                        .defineAlertCriteria("Metric1")
                            .withMetricName("Percentage CPU")
                            .withCondition(MetricAlertRuleTimeAggregation.TOTAL, MetricAlertRuleCondition.GREATER_THAN, 80)
                            .attach()
                        .create();
                return true;
            }
       /**
         * Main entry point.
         * @param args the parameters
         */
        public static void main(String[] args) {
            try {
    
                final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
                final TokenCredential credential = new DefaultAzureCredentialBuilder()
                    .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
                    .build();
    
                AzureResourceManager azureResourceManager = AzureResourceManager
                    .configure()
                    .withLogLevel(HttpLogDetailLevel.BASIC)
                    .authenticate(credential, profile)
                    .withSubscription("your-subscription-id");
    
                // Print selected subscription
                System.out.println("Selected subscription: " + azureResourceManager.subscriptionId());
    
                runSample(azureResourceManager);
            } catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
            System.out.println("Alert rule created..");
        }
    }
    

    Output:

    Selected subscription: xxxxxxxx
    Alert rule created..
    

    enter image description here

    Portal:

    The above code was executed and created an alert rule successfully for the virtual machine.

    enter image description here

    Reference:

    Monitor-java-metric-alerts-on-critical-performance · GitHub