5: Monitor and Maintain Azure Resources

    Monitor resources in Azure.

    Cloud infrastructure is opaque without instrumentation. A team cannot see CPU spikes on a VM scale set, failed deployments in a resource group, or 503 errors from an Application Gateway unless those signals are collected, stored, and queryable. Azure Monitor is the platform that solves this problem by ingesting telemetry from every Azure resource, every supported on-premises machine, and every custom application that emits logs. The alternative, polling resources individually through ARM APIs or running standalone tools per service, does not scale beyond a handful of resources and provides no historical analysis.

    Azure Monitor itself is a control plane and a billing boundary. Underneath it, the actual data lives in two stores with very different shapes. Metrics are numeric measurements sampled at fixed intervals (typically one minute) and stored in a multidimensional time-series database. Logs are heterogeneous records of varying schema (events, traces, audit entries, performance counters) stored in a Log Analytics workspace, which is a fully managed Azure Data Explorer cluster. The two stores have different retention policies, different query interfaces, and different cost models, and choosing which one to use for a given signal is the first design decision every administrator makes.

    Metrics versus logs versus the activity log

    Platform metrics are emitted automatically by every Azure resource. A virtual machine produces Percentage CPU, Network In Total, and OS Disk Write Operations/Sec; a storage account produces Transactions, Ingress, and SuccessE2ELatency; an Application Gateway produces Failed Requests and Healthy Host Count. These metrics arrive in Azure Monitor Metrics within one to three minutes of the underlying event, are retained for 93 days at one-minute granularity, and are queried through the Metrics Explorer blade or the az monitor metrics list command. There is no charge for platform metrics. Guest OS metrics (memory, logical disk space, process count) are not platform metrics; they require the Azure Monitor Agent because the hypervisor cannot see inside the guest.

    Resource logs (formerly called diagnostic logs) describe the internal operations of a resource. A key vault writes a AuditEvent entry every time a secret is read; a storage account writes a StorageRead entry for every blob GET; a network security group writes a flow log entry for every connection. Resource logs are never collected by default. The administrator must create a diagnostic setting on each resource that names a destination (Log Analytics workspace, storage account, or event hub) and selects which log categories to forward. Without this step the data is generated by the resource but never stored anywhere queryable.

    The activity log is a third, separate data stream that records control plane operations at the subscription level. It captures every ARM API call that wrote to a resource: who created a VM, who deleted a network security group, who modified a role assignment. It also records service health events, policy compliance changes, and autoscale actions. The activity log is retained for 90 days at no cost and is queryable from the portal or through az monitor activity-log list. To retain it longer, create a subscription-level diagnostic setting that exports it to a workspace, storage account, or event hub.

    Log Analytics workspaces and KQL

    A Log Analytics workspace is the storage and query engine for all log data, including the activity log, resource logs, guest OS logs collected by AMA, Application Insights telemetry, and custom logs sent through the Data Collector API or HTTP Ingestion API. Each workspace is regional and is billed by ingested GB plus retained GB beyond the included period. The default interactive retention is 30 days (90 days for the AzureActivity and Usage tables); this can be extended on a per-table basis up to 730 days. Beyond 730 days the data can be moved to the archive tier, which is cheaper but is not directly queryable; archived data must be brought back through a search job or table restore before it can be queried again.

    Queries against a workspace are written in Kusto Query Language (KQL). KQL is read-only, declarative, and uses a pipe-forward syntax similar to PowerShell. A query starts with a table name, pipes through operators like where, summarize, project, extend, join, and ends with a result set that can be displayed in a chart, saved as a function, pinned to a workbook, or used as the criteria for a log search alert. The most important operators for the exam are summarize (aggregation with count(), avg(), percentile()), bin() (time bucketing), and render (visualization hint).

    // Top 10 VMs by average CPU over the last hour, bucketed into 5-minute intervals
    InsightsMetrics
    | where TimeGenerated > ago(1h)
    | where Namespace == "Processor" and Name == "UtilizationPercentage"
    | summarize avg(Val) by Computer, bin(TimeGenerated, 5m)
    | top 10 by avg_Val desc
    | render timechart
    
    // All failed sign-ins to Azure resources from a specific IP in the activity log
    AzureActivity
    | where TimeGenerated > ago(7d)
    | where CallerIpAddress == "203.0.113.42"
    | where ActivityStatusValue == "Failure"
    | project TimeGenerated, Caller, OperationNameValue, ResourceGroup, _ResourceId
    

    Diagnostic settings, AMA, and data collection rules

    A diagnostic setting is the configuration object that wires a resource's log and metric output to a destination. Each setting selects one or more log categories (the categories available depend on the resource type), one or more metric categories, and one to three destinations: a Log Analytics workspace, an Azure Storage account, an event hub, or a partner solution. The administrator can also direct logs to a specific destination per category, which is useful when long-term audit logs go to cheap storage while operational logs go to a workspace for live querying.

    # Create a diagnostic setting on a storage account that sends StorageRead and
    # Transaction metrics to a Log Analytics workspace
    az monitor diagnostic-settings create \
     --name "ds-stcontoso-to-log" \
     --resource "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-contoso-prod-eus/providers/Microsoft.Storage/storageAccounts/stcontosoprodeus001/blobServices/default" \
     --workspace "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-contoso-prod-eus/providers/Microsoft.OperationalInsights/workspaces/log-contoso-prod-eus" \
     --logs '[{"category":"StorageRead","enabled":true}]' \
     --metrics '[{"category":"Transaction","enabled":true}]'
    

    The Azure Monitor Agent (AMA) replaces the retired Log Analytics agent and is the only supported in-guest agent for collecting Windows event logs, syslog, performance counters, and custom text logs from VMs and Arc-enabled servers. AMA is configured through data collection rules (DCRs), which are stand-alone ARM resources that define what to collect, how to transform it, and where to send it. A single DCR can target many machines through a data collection rule association (DCRA), and one machine can have multiple associations, which means data collection logic is decoupled from the agent itself.

    📊 Limit: A single Azure resource can have at most 5 diagnostic settings. Exceeding this returns a 400 error when the sixth setting is created.

    📊 Limit: The activity log retains 90 days of events at no charge. To preserve events longer, create a subscription diagnostic setting that exports to a workspace, storage account, or event hub.

    💡 Exam Trap: Platform metrics and guest OS metrics are not the same. Platform metrics for a VM come from the host (CPU, network, disk I/O on the host side). Memory utilization, logical disk free space, and process-level data require AMA inside the guest. A scenario that asks for "memory usage on the VM" is asking for AMA, not platform metrics.

    💡 Exam Trap: The Log Analytics agent (MMA) was retired on August 31, 2024 and cannot be used for new deployments. Any exam answer that proposes installing the MMA or "Microsoft Monitoring Agent" for new collection is wrong. The correct answer is to deploy AMA through a DCR.

    Alerts and action groups

    An alert is a rule that evaluates a signal continuously and triggers an action when a condition is met. Azure Monitor supports four alert types and they differ in the data source they read, the cost model, and the kinds of conditions they can express.

    A metric alert evaluates a platform metric or a custom metric against a static threshold or a dynamic threshold computed by machine learning. Metric alerts have low latency (the alert can fire within one to two minutes of the signal) and are cheap (priced per alert rule per month). They support multiple dimensions: a single rule can monitor "CPU above 80% on every VM in a resource group" rather than requiring one rule per VM.

    A log search alert (sometimes called a log alert) runs a saved KQL query on a schedule and triggers when the result set meets a condition. The condition can be "number of results greater than N" (number of results alert) or "any value in a specified column outside a threshold" (metric measurement alert). Log search alerts can express logic that metric alerts cannot, like correlating events across two tables, but they have higher latency (minimum frequency is one minute, recommended five minutes) and are billed per query execution.

    An activity log alert triggers on a specific subscription-level event. The condition is matched against fields in the activity log: a resource type, an operation name, a status, a caller. Activity log alerts are free and are the right tool for "notify the team whenever any VM is deleted" or "alert when an Azure Advisor recommendation appears."

    A smart detection alert (in Application Insights) and a Service Health alert (for Azure platform incidents) round out the catalog, though both are narrower in scope.

    # Metric alert: fire when average CPU on vm-app01 exceeds 85% for 5 minutes
    az monitor metrics alert create \
     --name "alert-vm-app01-cpu-high" \
     --resource-group "rg-contoso-prod-eus" \
     --scopes "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-contoso-prod-eus/providers/Microsoft.Compute/virtualMachines/vm-app01" \
     --condition "avg Percentage CPU > 85" \
     --window-size 5m \
     --evaluation-frequency 1m \
     --severity 2 \
     --action "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-contoso-prod-eus/providers/Microsoft.Insights/actionGroups/ag-contoso-ops"
    

    An action group is a named collection of notification and automation actions that one or more alerts can invoke. A single action group can contain email recipients, SMS recipients, voice call recipients, push notifications to the Azure mobile app, webhook URLs, ITSM connector entries, Logic App invocations, Azure Function calls, Event Hub publishers, and Automation Runbook triggers. Action groups are reusable across alerts, which keeps notification logic out of individual alert rules. A common pattern is one action group per on-call rotation rather than per alert.

    # Create an action group with one email receiver and one webhook
    $email = New-AzActionGroupReceiver -Name "ops-team" -EmailReceiver -EmailAddress "ops@contoso.com"
    $webhook = New-AzActionGroupReceiver -Name "pagerduty" -WebhookReceiver -ServiceUri "https://events.pagerduty.com/integration/abc123/enqueue"
    Set-AzActionGroup -ResourceGroupName "rg-contoso-prod-eus" -Name "ag-contoso-ops" `
     -ShortName "ops" -Receiver $email,$webhook
    

    Metric aggregation, dimensions, and time grain

    A platform metric is not a single number; it is a stream of samples. Each metric has a default aggregation type (Average, Total, Minimum, Maximum, Count) and one or more dimensions that allow the same metric to be sliced by an attribute. The Transactions metric on a storage account, for example, has dimensions for ApiName, Authentication, ResponseType, and GeoType, so a single metric chart can show "successful GET operations by anonymous callers" without any custom code. Metric alerts can target a specific dimension value or use the "split by dimension" feature to evaluate the same threshold against every dimension value separately, which is how a single rule can monitor every VM in a resource group.

    Time grain is the bucket size used for aggregation when querying or charting metrics. Platform metrics arrive at one-minute granularity and Azure Monitor automatically rolls them up to coarser grains (5 minutes, 15 minutes, 1 hour, 6 hours, 12 hours, 1 day) the older the data gets. Alert rules can choose an evaluation window from 1 minute to 24 hours. A common mistake is setting a 5-minute window with a 1-minute evaluation frequency and expecting the alert to fire immediately on a single spike; the rule actually requires the average across the 5-minute window to exceed the threshold, so a 30-second spike will not trigger it.

    Workspace design and cost control

    Log Analytics workspace cost is dominated by ingestion (per GB ingested) and, secondarily, by retention beyond the included period. The default pricing tier is Pay-as-you-go, and commitment tiers (100 GB/day through 5000 GB/day) provide a discount in exchange for a daily commitment. Two design decisions drive ingestion cost: which data is sent to the workspace at all (controlled at the source through diagnostic settings and DCRs), and which tables retain that data beyond the default 30 days. Per-table retention overrides allow expensive verbose tables (AzureDiagnostics, AppTraces) to be kept short while keeping cheaper audit tables (AzureActivity, SigninLogs) for the full compliance window.

    Three workspace topology patterns appear on the exam. A single central workspace per tenant simplifies cross-resource queries and is the right answer when one team owns monitoring. A workspace per region reduces egress and aligns with data residency, and is the right answer when multiple geographies have separate compliance regimes. A workspace per environment (production, non-production) provides clean access boundaries through Azure RBAC and is the right answer when developers should not see production telemetry. Workspaces in different regions can be queried together with cross-workspace KQL using the workspace() function.

    📊 Limit: Azure Monitor metrics retain platform metrics for 93 days at 1-minute granularity. Custom metrics sent through the Azure Monitor REST API are also retained for 93 days.

    Workbooks, VM insights, and Network Watcher

    Workbooks are interactive reports that combine KQL queries, ARM metric queries, parameter selectors, and text into a single shareable document. They are useful for dashboards that need parameters (region, resource group, time range) that the viewer can adjust without editing the underlying queries.

    VM insights is a curated set of dashboards and a managed DCR that provides performance, dependency, and health monitoring for VMs and VM scale sets. Enabling VM insights deploys the Azure Monitor Agent and, optionally, the Dependency Agent (for the service map that shows which processes are talking to which other processes). The collected data lands in the InsightsMetrics, VMComputer, VMProcess, VMBoundPort, and VMConnection tables.

    Network Watcher is a regional service that provides per-region tools for diagnosing network configuration: Connection Monitor (continuous reachability tests between source and destination), IP flow verify (will this specific packet be allowed or denied by NSGs and UDRs), Next hop (what is the resolved route for traffic leaving a NIC), Effective security rules (the combined NSG rules applied to a NIC), Connection troubleshoot (one-shot reachability test with diagnostic output), Packet capture (timestamped pcap on a running VM), and VNet flow logs (the successor to NSG flow logs).

    💡 Exam Trap: Network Watcher is enabled per region, not per VNet. When a VNet is created in a region for the first time, Network Watcher is auto-enabled in that region. Disabling Network Watcher in a region disables it for every VNet in that region.

    ⚠️ Anti-Pattern: Creating one diagnostic setting per resource manually through the portal at scale. This breaks on the 6th resource of a new type because the configuration drifts. Use Azure Policy with DeployIfNotExists effects that target resource types and apply diagnostic settings automatically when matching resources appear.

    Architecture: how telemetry flows from a resource to an alert

    The diagram below shows the path that a typical metric or log takes from a resource through Azure Monitor to a responder. Understanding this flow is what lets an administrator decide where to instrument, where to filter, and where to alert.

    Architecture Flow: Azure Monitor Data Pipeline

    Decision tree: choosing the right monitoring signal

    When a customer asks "how do I monitor X," the answer depends on what X is, how fast the alert must fire, and what kind of condition is being evaluated. The decision tree below codifies the choice.

    Decision Tree: Choosing the Right Azure Monitor Signal

    🎯 Scenario: A Contoso administrator must alert the on-call team when any storage account in subscription sub-prod-001 has more than 50 HTTP 503 responses in any 15-minute window. Platform metrics do not break Transactions down by response code, so a metric alert is not sufficient. The administrator enables the StorageRead, StorageWrite, and StorageDelete log categories on each storage account through a diagnostic setting that targets the central workspace log-contoso-prod-eus. A log search alert runs the KQL StorageBlobLogs | where StatusCode == 503 | summarize count() by bin(TimeGenerated, 15m), AccountName every five minutes with a threshold of 50. The alert links to the ag-contoso-ops action group, which emails the team and posts a webhook to PagerDuty.

    Decision rule

    Choose a metric alert when the signal is a numeric platform metric and the condition is a threshold (latency, CPU, queue depth). Choose a log search alert when the condition requires correlating fields, filtering on a property not exposed as a metric dimension, or comparing across tables. Choose an activity log alert when the trigger is a control plane operation (create, delete, role assignment, policy non-compliance). Choose VM insights and AMA when the signal originates inside the VM guest.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Microsoft - AZ-104 learning hub.