Azure Monitor SDK for JavaScript

Introduction to Azure Monitor SDK

The Azure Monitor SDK for JavaScript provides a powerful and convenient way to programmatically interact with Azure Monitor services. You can use this SDK to collect, analyze, and act on telemetry data from your Azure resources and on-premises environments.

With this SDK, you can:

Getting Started

Installation

You can install the Azure Monitor SDK for JavaScript using npm or yarn:

npm install @azure/arm-monitor
yarn add @azure/arm-monitor

Authentication

To authenticate with Azure Monitor, you can use several methods. The most common methods include using a service principal or managed identity.

Here's an example using Azure Identity:

Example: Authenticating with DefaultAzureCredential


import { DefaultAzureCredential } from "@azure/identity";
import { MonitorManagementClient } from "@azure/arm-monitor";

async function getMonitorClient() {
    const credential = new DefaultAzureCredential();
    const subscriptionId = "YOUR_SUBSCRIPTION_ID"; // Replace with your subscription ID
    const client = new MonitorManagementClient(credential, subscriptionId);
    return client;
}

getMonitorClient().then(client => {
    console.log("Monitor client authenticated successfully.");
    // Now you can use the client to interact with Azure Monitor
}).catch(error => {
    console.error("Authentication failed:", error);
});
                    

For more details on authentication methods, refer to the Azure SDK authentication documentation.

Core Concepts

Metrics

Metrics are numerical values that describe the state of a resource at a particular point in time. Azure Monitor collects these metrics to provide insights into the performance and health of your services.

Common metrics include CPU usage, network in/out, disk operations, and request counts.

Logs

Logs contain different types of data, including event logs, performance counters, and application-specific logs. Azure Monitor collects these logs for analysis and troubleshooting.

Log data can be queried using the Kusto Query Language (KQL).

Alerts

Alerts notify you of critical conditions in your environment. You can create alert rules based on metrics or logs that trigger actions, such as sending an email or running a webhook.

Usage Examples

Fetching Metrics

Retrieve the average CPU percentage for a virtual machine over the last hour.

Example: Get CPU Usage Metrics


import { DefaultAzureCredential } from "@azure/identity";
import { MonitorManagementClient } from "@azure/arm-monitor";

async function getCpuMetrics(resourceUri: string) {
    const credential = new DefaultAzureCredential();
    const subscriptionId = "YOUR_SUBSCRIPTION_ID"; // Replace with your subscription ID
    const client = new MonitorManagementClient(credential, subscriptionId);

    const metricDefinitions = await client.metricDefinitions.list(resourceUri);
    const cpuMetric = metricDefinitions.find(metric => metric.name.value === "Percentage CPU");

    if (!cpuMetric) {
        console.log("CPU metric definition not found.");
        return;
    }

    const endDate = new Date();
    const startDate = new Date(endDate.getTime() - 60 * 60 * 1000); // Last hour

    const metrics = await client.metrics.list(resourceUri, {
        metricnames: "Percentage CPU",
        timespan: `${startDate.toISOString()}/${endDate.toISOString()}`,
        interval: "PT1M", // 1 minute interval
        aggregation: ["Average"]
    });

    console.log("CPU Usage Metrics:", JSON.stringify(metrics, null, 2));
}

const vmResourceUri = "/subscriptions/YOUR_SUBSCRIPTION_ID/resourceGroups/YOUR_RESOURCE_GROUP/providers/Microsoft.Compute/virtualMachines/YOUR_VM_NAME"; // Replace with your VM resource URI
getCpuMetrics(vmResourceUri).catch(console.error);
                    

Querying Logs

Query Azure Activity Logs for specific events.

Example: Query Activity Logs


import { DefaultAzureCredential } from "@azure/identity";
import { MonitorManagementClient } from "@azure/arm-monitor";

async function queryActivityLogs(subscriptionId: string) {
    const credential = new DefaultAzureCredential();
    const client = new MonitorManagementClient(credential, subscriptionId);

    const endDate = new Date();
    const startDate = new Date(endDate.getTime() - 24 * 60 * 60 * 1000); // Last 24 hours

    const query = `
        AzureActivity
        | where TimeGenerated > datetime(${startDate.toISOString()}) and TimeGenerated < datetime(${endDate.toISOString()})
        | where OperationNameValue == "Microsoft.Compute/virtualMachines/start/action"
        | project TimeGenerated, Caller, ResourceGroup, Properties
    `;

    const result = await client.logAnalytics.executeQuery(subscriptionId, query);
    console.log("Activity Log Query Results:", JSON.stringify(result, null, 2));
}

queryActivityLogs("YOUR_SUBSCRIPTION_ID").catch(console.error);
                    

Note: This example uses a simplified query for demonstration. For complex queries, ensure your KQL syntax is correct.

Creating Alerts

Create a metric alert rule for high CPU usage.

Example: Create Metric Alert Rule


import { DefaultAzureCredential } from "@azure/identity";
import { MonitorManagementClient } from "@azure/arm-monitor";

async function createCpuAlertRule(resourceGroupName: string, alertRuleName: string, resourceUri: string) {
    const credential = new DefaultAzureCredential();
    const subscriptionId = "YOUR_SUBSCRIPTION_ID"; // Replace with your subscription ID
    const client = new MonitorManagementClient(credential, subscriptionId);

    const result = await client.webtest.createOrUpdate(resourceGroupName, alertRuleName, {
        // Simplified alert rule properties - consult API for full details
        location: "global", // Or the appropriate location for your alert rule
        properties: {
            displayName: alertRuleName,
            description: "Alert when CPU usage exceeds 80%",
            severity: 2, // Severity 2 is typically 'Warning'
            enabled: true,
            scopes: [resourceUri],
            condition: {
                odataType: "#Microsoft.Azure.Management.Monitor.CategoryAndCondition",
                category: "Alert",
                criteria: [
                    {
                        odataType: "#Microsoft.Azure.Management.Monitor.Webtest.WebTestLastResultCode",
                        name: "Percentage CPU",
                        operator: "GreaterThan",
                        threshold: 80,
                        aggregationType: "Average",
                        metricNamespace: "Microsoft.Compute/virtualMachines",
                        resourceId: resourceUri
                    }
                ]
            },
            actions: {
                actionGroups: [] // Add action group IDs here if needed
            }
        }
    });

    console.log("Alert rule created:", result);
}

const rgName = "YOUR_RESOURCE_GROUP"; // Replace with your resource group
const alertName = "HighCpuAlert";
const vmUri = "/subscriptions/YOUR_SUBSCRIPTION_ID/resourceGroups/YOUR_RESOURCE_GROUP/providers/Microsoft.Compute/virtualMachines/YOUR_VM_NAME"; // Replace with your VM resource URI
createCpuAlertRule(rgName, alertName, vmUri).catch(console.error);
                    

Creating and managing alert rules can have implications for your Azure costs. Please review Azure Monitor pricing.

API Reference

For a comprehensive list of available methods and their parameters, please refer to the official Azure Monitor SDK for JavaScript API Reference:

@azure/arm-monitor API Reference

The SDK provides clients for managing various Azure Monitor resources, including:

Client Description
MetricsClient Interact with metric definitions and retrieve metric data.
LogAnalyticsClient Execute Log Analytics queries.
AlertRulesClient Manage alert rules for metrics and logs.
ActivityLogsClient List and query Azure Activity Logs.

Troubleshooting

If you encounter issues:

For debugging, consider enabling verbose logging for the Azure SDK client.

Contributing

The Azure SDKs are open source. If you'd like to contribute or report issues, please visit the official Azure SDK for JavaScript GitHub repository.