• 4 min read

Manage Azure Monitor using Java

Azure Monitor maximizes the availability and performance of your applications by delivering an end-to-end monitoring solution for collecting, analyzing, and acting on telemetry from your cloud and on-premises environments.

Azure Monitor maximizes the availability and performance of your applications by delivering an end-to-end monitoring solution for collecting, analyzing, and acting on telemetry from your cloud and on-premises environments. It helps you understand how your applications are performing and proactively identifies issues affecting them and the resources they depend on. Today, we released version 1.16 of the Azure Management Libraries for Java. Now you can programmatically manage Azure Monitor using Azure Management Libraries for Java, specifically, you can:

  • Manage Diagnostic Settings
  • Stream logs and metrics to Event Hub, Storage Account or Log Analytics
  • Query Metrics
  • Set up Metric Alerts
  • Query Activity Logs
  • Set up Activity Log Alerts
  • Setup Auto Scale
  • Perform Advanced Analytics

If you you’re ready to dive right in, go to the Azure Management Libraries for Java GitHub repo:

Getting started

Add the following dependency fragment to your Maven POM file to use 1.16 version of the libraries:


     com.microsoft.azure
     azure
     1.16.0

Stream Azure Service Logs and Metrics through Event Hub

Azure diagnostic logs – service and app logs from managed Azure services and resources – can be streamed in near real-time to any third-party logging and telemetry systems of your choice, such as Elastic Stack, Splunk or Grafana, by creating an Event Hub and streaming service logs and metrics to the Event Hub:

DiagnosticSetting ds = azure.diagnosticSettings()
     .define("DiaEventHub")
     .withResource(docDb.id())
     .withEventHub(eventHubAuthRule.id(), "MyEventHub")
     .withLog("DataPlaneRequests", 0)
     .withLog("MongoRequests", 0)
     .withMetric("AllMetrics", Period.minutes(5), 0)
     .create();

Read on for the full sample code.

Query Metrics

Through metrics emitted by Azure resources, Azure Monitor enables you to gain visibility into the performance and health of Azure services and your applications running on Azure. Using Java code, you can query metrics for any Azure resources, for example:

// Get metric definitions for storage account
for (MetricDefinition metricDefinition : azure.metricDefinitions().listByResource(storageAccount.id())) {
     // Find metric definition for Transactions
        if (metricDefinition.name().localizedValue().equalsIgnoreCase("transactions")) {
             // Query metric records
             MetricCollection metricCollection = metricDefinition.defineQuery()
                  .startingFrom(recordDateTime.minusDays(7))
                  .endsBefore(recordDateTime)
                  .withAggregation("Average")
                  .withInterval(Period.minutes(5))
                  .withOdataFilter
                    ("apiName eq 'PutBlob' and responseType eq 'Success' and geoType eq 'Primary'")
                  .execute();
                   …

Read on for the full sample code.

Query Activity Logs

Azure Activity Log is a subscription log that provides insights into subscription-level events occurring in Azure. These events include a range of data from Azure Resource Manager operational data to service health updates. Using activity logs, you can determine who, when and what changes were applied on resources in your subscription.

You can query activity logs for the same period from the previous example.

// Query activity logs
PagedList logs = azure.activityLogs().defineQuery()
     .startingFrom(recordDateTime.minusDays(7))
     .endsBefore(recordDateTime)
     .withAllPropertiesInResponse()
     .filterByResource(storageAccount.id())
     .execute();
 
for (EventData event : logs) {
     ...
     System.out.println("tCaller: " + event.caller());
     System.out.println("tCorrelationId: " + event.correlationId());
     System.out.println("tSubscriptionId: " + event.subscriptionId());
}

Read on for the full sample code.

Setup Metric Alerts

An Action Group is a collection of notification preferences that can be defined by you. Notifications can be configured to call a telephone number, send an SMS message, send an e-mail, call a Web hook, send data to an ITSM tool, call a Logic App in Azure or send push notifications to the Azure app.

Using Java code, you can create an Action Group to be notified when metric alert conditions are triggered:

ActionGroup ag = azure.actionGroups().define("criticalPerformanceActionGroup")
     .withExistingResourceGroup(rgName)
     .defineReceiver("tierOne")
         .withPushNotification("ops_on_duty@performancemonitoring.com")
         .withEmail("ops_on_duty@performancemonitoring.com")
         .withSms("1", "4255655665")
         .withVoice("1", "2062066050")
         .withWebhook("https://www.weeneedmorepower.performancemonitoring.com")
     .attach()
     .defineReceiver("tierTwo")
          .withEmail("ceo@performancemonitoring.com")
          .attach()
     .create();

Then, create a Metric Alert for triggering notifications. For example, you can create a metric alert which triggers notifications when there are critical changes to the performance of Web apps on Azure App Service:

MetricAlert ma = azure.alertRules().metricAlerts().define("Critical performance alert")
     .withExistingResourceGroup(rgName)
     .withTargetResource(servicePlan.id())
     .withPeriod(Period.minutes(5))
     .withFrequency(Period.minutes(1))
     .withAlertDetails(3,
          "Single Resource with Multiple Criteria, Multiple Dimensions and Wildcard")
     .withActionGroups(ag.id())
     .defineAlertCriteria("Metric1")
         .withMetricName("CPUPercentage", "Microsoft.Web/serverfarms")
         .withCondition(MetricAlertRuleCondition.GREATER_THAN,
              MetricAlertRuleTimeAggregation.TOTAL, 80)
         .withDimension("Instance", "*")
         .attach()
    
     .create();

Read on for the full sample code.

Setup Activity Log Alerts

Just like metric alerts, you can audit and receive notifications when important events or activities are occurring in your subscription through Activity Log Alerts. You can create an activity log alert and specify an action group to be notified.

For example, using Java code, you can setup an activity log alert for potential security breaches and send notifications to users:

ActivityLogAlert ala = azure.alertRules().activityLogAlerts().define("Potential security breach alert")
     .withExistingResourceGroup(rgName)
     .withTargetSubscription(azure.subscriptionId())
     .withDescription("Security StorageAccounts ListAccountKeys trigger")
     .withRuleEnabled()
     .withActionGroups(ag.id())
     // fire an alert when all conditions below are true
     .withEqualsCondition("category", "Security")
     .withEqualsCondition("resourceId", storageAccount.id())
     .withEqualsCondition("operationName", "Microsoft.Storage/storageAccounts/listkeys/action")
     .create();

Read on for the full sample code.

Setup Autoscale

Autoscale allows you to have the right amount of resources running to handle the load on your applications. It allows you to add instances to handle increases in load and save money by removing instances that are idling. You can define configuration of auto scale-out and scale-in rules by using a define() and create() method chain.

For example, using Java code, you can setup auto scale to scale out or scale instances based on pre-defined conditions, say the number of HTTP requests received by Web apps on App Service:

AutoscaleSetting scaleSettings = azure.autoscaleSettings().define(autoscaleSettingsName)
     .withRegion(Region.US_SOUTH_CENTRAL)
     .withExistingResourceGroup(rgName)
     .withTargetResource(webapp.appServicePlanId())
     // define default profile
     .defineAutoscaleProfile("Default profile")
          .withFixedInstanceCount(1)
          .attach()
     // defining Monday to Friday profile
     .defineAutoscaleProfile("Monday to Friday")
          .withMetricBasedScale(1, 2, 1)
          // create a scale-out rule
          .defineScaleRule()
               ...
               .attach()
          // create a scale-in rule
          .defineScaleRule()
               ...        
               .attach()
          // create schedule for auto scale
          .withRecurrentSchedule("Pacific Standard Time", "09:00",
               DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY,
               DayOfWeek.THURSDAY, DayOfWeek.FRIDAY)
          .attach()
          // define end time for the "Monday to Friday" profile specified above
          ...
     .create();

Read on for the full sample code.

Try managing Azure Monitor using Java today

Test it out, stream logs and metrics from managed Azure services and resources, setup some alerts, put some load on them and see for yourself how these telemetry data can help with performance and root cause analysis troubleshooting. Tell us what you think (via e-mail or comments below).

You can get more samples from our GitHub repo.

Additional resources