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. 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:


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()
     .withEventHub(, "MyEventHub")
     .withLog("DataPlaneRequests", 0)
     .withLog("MongoRequests", 0)
     .withMetric("AllMetrics", Period.minutes(5), 0)

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( {
     // Find metric definition for Transactions
        if ("transactions")) {
             // Query metric records
             MetricCollection metricCollection = metricDefinition.defineQuery()
                    ("apiName eq 'PutBlob' and responseType eq 'Success' and geoType eq 'Primary'")

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<EventData> logs = azure.activityLogs().defineQuery()
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")
         .withSms("1", "4255655665")
         .withVoice("1", "2062066050")

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")
          "Single Resource with Multiple Criteria, Multiple Dimensions and Wildcard")
         .withMetricName("CPUPercentage", "Microsoft.Web/serverfarms")
              MetricAlertRuleTimeAggregation.TOTAL, 80)
         .withDimension("Instance", "*")

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")
     .withDescription("Security StorageAccounts ListAccountKeys trigger")
     // fire an alert when all conditions below are true
     .withEqualsCondition("category", "Security")
     .withEqualsCondition("operationName", "Microsoft.Storage/storageAccounts/listkeys/action")

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)
     // define default profile
     .defineAutoscaleProfile("Default profile")
     // defining Monday to Friday profile
     .defineAutoscaleProfile("Monday to Friday")
          .withMetricBasedScale(1, 2, 1)
          // create a scale-out rule
          // create a scale-in rule
          // create schedule for auto scale
          .withRecurrentSchedule("Pacific Standard Time", "09:00",
               DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY,
               DayOfWeek.THURSDAY, DayOfWeek.FRIDAY)
          // define end time for the "Monday to Friday" profile specified above

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

Source: Azure Blog Feed

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.