AzureIntermediate

Azure Monitoring and Observability: Implementation Guide

8 min read

TL;DR

Master Azure monitoring and observability with this comprehensive guide covering Azure Monitor, Log Analytics, Application Insights, and best practices for cloud monitoring.

Azure Monitoring and Observability: Implementation Guide

Executive Summary

Azure's monitoring stack has three layers that are often confused: Azure Monitor collects platform metrics and routes alerts, Log Analytics stores and queries logs, and Application Insights instruments your application code. This guide shows how the three fit together, how to wire diagnostic settings so data actually flows, and how to write the KQL queries and alert rules that turn telemetry into action. After reading it you will be able to design a monitoring setup where an incident produces one clear alert with the logs attached — not a dashboard nobody opens and a mailbox full of noise.

Why This Matters

Most monitoring failures are not missing tools; they are missing data and drowning alerts. The VM that fell over had diagnostic settings never enabled, so there are no logs for the hour that matters. The team that ignores alerts does so because the last fifty were false positives. Both failures are design decisions made early: what to collect, how long to keep it, and what is worth waking someone up for. Observability work done after an incident costs the same as work done before it, except it is done under pressure, with the evidence already gone.

Core Concepts

The Three Layers

ServiceRoleData it holds
Azure MonitorCollection and alerting backbonePlatform metrics, activity log, alert rules
Log AnalyticsLog storage and queryResource logs, agent logs, custom logs, queried with KQL
Application InsightsApplication performance monitoringRequests, dependencies, exceptions, custom events and metrics
Network WatcherNetwork diagnosticsFlow logs, connectivity checks, packet capture

Metrics are cheap, structured, and near-real-time — use them for alerting. Logs are detailed and more expensive — use them for diagnosis. Application Insights traces connect the two for application-level questions.

Getting Data In: Diagnostic Settings

Azure resources emit nothing to Log Analytics until a diagnostic setting says so. This is the single most skipped step in Azure monitoring.

# Enable diagnostic settings
Set-AzDiagnosticSetting `
    -ResourceId $vm.Id `
    -WorkspaceId $workspaceId `
    -Enabled $true `
    -Category @("AllMetrics") `
    -MetricCategory @(
        "CPU",
        "Memory",
        "Network",
        "Disk"
    )

Define diagnostic settings in your infrastructure as code so every new resource is born instrumented, and audit for resources that lack them.

Alert Rules

Metric alerts evaluate a platform metric on a schedule and fire an action group. Define them declaratively so they are reviewable:

{
    "name": "HighMemoryAlert",
    "type": "Microsoft.Insights/metricAlerts",
    "location": "global",
    "properties": {
        "description": "Alert when memory usage exceeds 90%",
        "severity": 2,
        "enabled": true,
        "scopes": ["[parameters('resourceId')]"],
        "evaluationFrequency": "PT1M",
        "windowSize": "PT5M",
        "criteria": {
            "odata.type": "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria",
            "allOf": [
                {
                    "name": "HighMemory",
                    "metricName": "Available Memory Bytes",
                    "operator": "LessThan",
                    "threshold": 1073741824,
                    "timeAggregation": "Average"
                }
            ]
        },
        "actions": [
            {
                "actionGroupId": "[parameters('actionGroupId')]"
            }
        ]
    }
}

Every alert needs three properties most alerts lack: a severity that maps to a response expectation, an action group that reaches a human or an automation, and a runbook link. An alert with no owner and no next step is a log entry with extra steps.

Log Analytics Workspaces

One workspace per environment boundary is the usual pattern; a single workspace for everything simplifies queries but mixes retention and access requirements.

# Create Log Analytics workspace
New-AzOperationalInsightsWorkspace `
    -ResourceGroupName "MonitoringRG" `
    -Name "MyWorkspace" `
    -Location "East US" `
    -Sku "PerGB2018"

# Configure data retention
Set-AzOperationalInsightsWorkspace `
    -ResourceGroupName "MonitoringRG" `
    -Name "MyWorkspace" `
    -RetentionInDays 90

Retention is a cost decision: you pay per GB ingested and per retention period, so set retention per table where the tooling allows it, and be deliberate about verbose sources — a chatty firewall or an unsampled application can dominate the bill.

KQL: Querying What You Collected

Kusto Query Language is how logs become answers. Three patterns cover most operational questions — trend a performance counter, count security events, and aggregate a service log:

// CPU usage by VM
Perf
| where ObjectName == "Processor" and CounterName == "% Processor Time"
| summarize AvgCPU = avg(CounterValue) by Computer, bin(TimeGenerated, 1h)
| render timechart

// Failed authentication attempts
SecurityEvent
| where EventID == 4625
| summarize FailedAttempts = count() by TargetAccount, bin(TimeGenerated, 1h)
| order by FailedAttempts desc

// Storage account operations
StorageBlobLogs
| where OperationName contains "Write"
| summarize DataWritten = sum(RequestBodySize) by AccountName, bin(TimeGenerated, 1d)

Log-based (scheduled query) alerts run a KQL query on a schedule and alert on the result — the right tool for conditions metrics cannot express, such as "more failed sign-ins than successful ones from a single account."

Application Insights: Instrumenting the Application

Platform metrics tell you the VM was busy; Application Insights tells you which request was slow and which dependency failed. For .NET, registration is a few lines, and the dependency and request tracking modules do most of the work:

public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]);

    services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) =>
    {
        module.EnableSqlCommandTextInstrumentation = true;
    });

    services.ConfigureTelemetryModule<RequestTrackingTelemetryModule>((module, o) =>
    {
        module.CollectionOptions.TrackExceptions = true;
    });
}

Custom telemetry earns its place for business events the platform cannot infer — an order processed, a payment retried — with dimensions you will actually filter on:

public class OrderController : Controller
{
    private readonly TelemetryClient _telemetry;

    public OrderController(TelemetryClient telemetry)
    {
        _telemetry = telemetry;
    }

    public async Task<IActionResult> ProcessOrder(Order order)
    {
        var stopwatch = Stopwatch.StartNew();

        try
        {
            // Process order
            _telemetry.TrackEvent("OrderProcessed", new Dictionary<string, string>
            {
                { "OrderId", order.Id },
                { "Amount", order.Amount.ToString() }
            });

            return Ok();
        }
        catch (Exception ex)
        {
            _telemetry.TrackException(ex);
            throw;
        }
        finally
        {
            stopwatch.Stop();
            _telemetry.TrackMetric("OrderProcessingTime", stopwatch.ElapsedMilliseconds);
        }
    }
}

Sampling is the control that keeps Application Insights affordable at volume: adaptive sampling preserves error visibility while cutting successful-request volume. Configure it deliberately rather than discovering it in the invoice.

Alerting Strategy

Tie severity to response, and response to a channel a human actually watches:

SeverityMeaningChannel
CriticalUser impact nowPage: SMS/voice via action group, incident created
WarningDegradation, no user impact yetEmail or chat to the owning team
InformationWorth reviewing in business hoursDigest or dashboard review

Review alert performance monthly: alerts that fire without action get tuned or deleted. Alert fatigue is a system property, not a team discipline problem.

Decision Framework

SituationRecommendation
"Tell me when CPU is saturated"Metric alert on the platform metric — cheap and near-real-time
"Tell me when this pattern appears in logs"Scheduled query (log) alert with KQL
"Why was this request slow?"Application Insights end-to-end transaction view and dependency map
New resource deployedDiagnostic setting applied from IaC in the same change, verified in the workspace
Log bill growing faster than the estateAudit ingestion by table; shorten retention on verbose tables; sample application telemetry
Regulated workloadSeparate workspace, longer retention, access restricted and audited

Implementation Checklist

  • [ ] Diagnostic settings enabled on every production resource, deployed via IaC, with an audit for gaps
  • [ ] Activity log exported to the workspace so control-plane changes are queryable
  • [ ] Every alert has a severity, an action group reaching an owner, and a runbook link
  • [ ] Application Insights connected for production applications, with sampling configured deliberately
  • [ ] Retention set per table based on diagnostic and compliance need, not left at defaults everywhere
  • [ ] A small set of dashboards reflects user-facing health (availability, latency, error rate), not raw resource graphs
  • [ ] Alert review on the calendar: firing alerts without actions are tuned or removed
  • [ ] Ingestion cost reviewed monthly by table and resource
  • Trade-offs

    Full-fidelity logging is expensive and mostly unread; aggressive sampling and short retention are cheap and occasionally missing the one record you needed. There is no setting that escapes this trade — only a deliberate choice per data source. Centralising everything into one workspace simplifies correlation but couples retention, access, and cost across teams. Azure-native tooling integrates cleanly with Azure resources and identity, but estates that span clouds or heavy open-source stacks may find the KQL-and-workspace model a second system alongside the one they already run.

    When Not to Use

  • Log alerts are the wrong tool for simple threshold conditions on platform metrics; they are slower and costlier than metric alerts for the same job.
  • Application Insights custom events for everything is the wrong choice: instrumenting every internal step produces volume without insight. Reserve custom telemetry for business-meaningful events and failure points.
  • A single shared workspace is the wrong choice when workloads have different retention or access requirements — compliance boundaries should be workspace boundaries.
  • Conclusion

    Monitoring works when three habits hold: every resource is born with diagnostic settings, every alert has an owner and a next step, and the data you pay to store is the data you query during incidents. Azure Monitor, Log Analytics, and Application Insights supply the machinery; the discipline of collection, retention, and alert hygiene is what makes it observability rather than storage.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.