Set Up Azure Monitor

Set up Azure Monitor for applications in this hands-on Azure tutorial. Learn the core concepts, step-by-step configuration, troubleshooting tips, and what to study next.

Focus: set up azure monitor for applications

Sponsored

You've built the app, deployed it to Azure, and it's working — until a user reports a 500 error you can't reproduce. Logs are scattered, metrics are missing, and you're flying blind. That's the problem this lesson solves: setting up Azure Monitor for applications so you can see exactly what's happening inside your app, track performance, catch errors, and respond before users even notice. By the end, you'll have a working Application Insights setup, know how to query your telemetry, and understand where this fits in your Azure journey.

The problem this lesson solves

Every application running in production eventually fails. The question isn't if, but when — and how fast you can find out. Without proper monitoring, you're left with:

  • Blind deployments — you push code, it breaks, and you only hear about it from angry users.
  • Haphazard debugging — reproducing issues by guessing, instead of looking at actual telemetry.
  • Silent performance degradation — your API slowly gets slower, but no one notices until it's critical.
  • Wasted time in meetings — "Can you just check the logs?" becomes a full-time job.

Azure Monitor for applications — specifically Application Insights — gives you a single pane of glass for your app's health. It collects metrics (response times, failure rates), logs (traces, exceptions), and distributed traces (requests across services) automatically. You can set up alerts that page you before a problem becomes an outage.

Pro tip: Monitoring isn't just for production. Even in development, Application Insights helps you spot performance regressions early — especially in microservices or distributed systems where a call might span multiple components.

By the end of this lesson, you'll be able to answer: "Is my app healthy?" with confidence — and prove it with data.

Core concept / mental model

Think of Azure Monitor as the nervous system for your Azure resources. Application Insights is the part of that system dedicated to your application's code — the nerves that sense what's happening inside your app and report back to the brain (the Azure portal).

Here's the model:

  • Azure Monitor — the overarching platform that collects, analyzes, and acts on telemetry from all your Azure resources (VMs, databases, containers, etc.).
  • Application Insights — a feature of Azure Monitor focused specifically on application-level telemetry: requests, dependencies, exceptions, traces, and custom events.
  • Telemetry — the data your app emits. This can be automatic (built-in instrumentation) or manual (you write code to send custom events).
  • Instrumentation key / connection string — the "address" your app uses to send telemetry to the correct Application Insights resource.
  • Log Analytics workspace — the storage and query engine where your telemetry lives. You query it with KQL (Kusto Query Language).

When you set up Application Insights, you're essentially wiring your app to emit signals about its own health. Those signals flow to Azure, where you can:

  • View live metrics and trends in the portal.
  • Create dashboards for your team.
  • Set alerts that fire when a threshold is crossed (e.g., failure rate > 5%).
  • Run ad-hoc queries to diagnose a specific issue.

Mental model: If your app is a patient, Azure Monitor is the hospital's monitoring system, and Application Insights is the heart-rate monitor strapped to your specific patient. You can see the heartbeat in real time, and an alarm rings when something goes wrong.

How it works step by step

Wiring your app to Azure Monitor isn't magic — it's a series of deliberate steps. Here's the high-level flow:

  1. Create an Application Insights resource — this is the logical container for your app's telemetry. You'll get a connection string (like a phone number for your app to call).
  2. Add the Application Insights SDK to your app — a NuGet package for .NET, npm package for Node.js, etc. The SDK automatically collects HTTP requests, exceptions, and dependency calls.
  3. Configure the connection string — the SDK needs to know where to send telemetry. You'll typically store this in an environment variable or App Service setting (never hard-code it).
  4. Build and deploy — as your app runs, the SDK collects telemetry and sends it to Application Insights in near real time.
  5. Verify in the portal — check the Application Insights resource, run a query, and confirm you see requests flowing.
  6. Set up alerts — create alert rules on metrics like server response time or failed requests, so you get notified proactively.

The lifecycle in more detail

  • Development: You add the SDK and test locally. Telemetry flows to your Azure resource immediately.
  • Deployment: Your app runs anywhere — Azure, on-prem, or another cloud — as long as it can reach the ingestion endpoint. (That's the beauty: Application Insights is cloud-native and works from anywhere.)
  • Operations: You monitor dashboards, query logs, and act on alerts. Over time, you refine which metrics matter most.

Hands-on walkthrough

Let's put this into practice. We'll set up Application Insights for a simple Python Flask app and deploy it to Azure App Service. You'll see telemetry flowing in real time.

Prerequisites

  • An Azure subscription (free tier is fine).
  • Azure CLI installed and logged in (az login).
  • Python 3.10+ with pip.
  • A sample Flask app — we'll create one in a minute.

Step 1: Create the Application Insights resource

Open a terminal and run:

# Set your variables
export RESOURCE_GROUP="rg-monitoring-demo"
export LOCATION="eastus"
export INSIGHTS_NAME="appinsights-demo"

# Create a resource group (if not exists)
az group create --name $RESOURCE_GROUP --location $LOCATION

# Create the Application Insights resource
az monitor app-insights component create \
  --app $INSIGHTS_NAME \
  --location $LOCATION \
  --resource-group $RESOURCE_GROUP

# Retrieve the connection string
az monitor app-insights component show \
  --app $INSIGHTS_NAME \
  --resource-group $RESOURCE_GROUP \
  --query connectionString -o tsv

The command outputs something like:

InstrumentationKey=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/

Save the connection string in a safe place (we'll inject it into the app later).

Pro tip: Using the --query flag with Azure CLI is a great pattern for scripting. You can pipe it directly into a variable or a configuration file.

Step 2: Create a Flask app with the OpenTelemetry SDK

The easiest way to instrument a Python app is with the OpenTelemetry SDK, which Azure Monitor supports natively. Create a new folder and a requirements.txt:

pip install flask opencensus-ext-azure opencensus-ext-flask

Now create app.py:

from flask import Flask, request
import random
import time
from opencensus.ext.azure.log_exporter import AzureLogHandler
from opencensus.ext.flask.flask_middleware import FlaskMiddleware
import logging

app = Flask(__name__)

# Configure Azure Log Exporter
logger = logging.getLogger(__name__)
logger.addHandler(AzureLogHandler(connection_string="<YOUR_CONNECTION_STRING>"))
logger.setLevel(logging.INFO)

# Automatically trace all Flask requests
middleware = FlaskMiddleware(app)

@app.route("/")
def home():
    logger.info("Home page accessed")
    return "Hello, Azure Monitor!"

@app.route("/api/delay")
def delayed():
    wait = random.randint(1, 5)
    time.sleep(wait)
    logger.info(f"Delayed endpoint called, waited {wait}s")
    return {"wait_seconds": wait}

@app.route("/api/error")
def error():
    try:
        raise ValueError("Intentional error for monitoring")
    except Exception:
        logger.exception("An error occurred")
        return {"error": "something went wrong"}, 500

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)

Note: In production, never hard-code the connection string. Use an environment variable. We'll set it via App Service settings.

Run the app locally to check it works:

python app.py

Now hit the endpoints a few times — use your browser or curl:

curl http://localhost:8080/
curl http://localhost:8080/api/delay
curl http://localhost:8080/api/error

Step 3: Deploy to Azure App Service

For simplicity, let's deploy using Azure App Service with a local Git or ZIP deploy. First, create the App Service and set the connection string:

export APP_SERVICE_NAME="my-monitored-app"
export CONN_STRING=$(az monitor app-insights component show --app $INSIGHTS_NAME --resource-group $RESOURCE_GROUP --query connectionString -o tsv)

# Create App Service plan and web app
az appservice plan create --name "plan-monitoring" --resource-group $RESOURCE_GROUP --sku F1 --is-linux
az webapp create --name $APP_SERVICE_NAME --resource-group $RESOURCE_GROUP --plan "plan-monitoring" --runtime "PYTHON:3.10"

# Set the connection string as an app setting
az webapp config appsettings set --resource-group $RESOURCE_GROUP --name $APP_SERVICE_NAME --settings "APPLICATIONINSIGHTS_CONNECTION_STRING=$CONN_STRING"

# Deploy from local folder (requires git or zip deploy)
cd my_flask_app_folder
az webapp up --name $APP_SERVICE_NAME --resource-group $RESOURCE_GROUP

(Adjust the deploy steps based on your app structure — you'll need a startup.txt or Procfile for Flask on App Service, but for this demo, az webapp up will detect the Python app.)

Step 4: Verify telemetry in Application Insights

Once your app is running, generate some traffic:

curl https://$APP_SERVICE_NAME.azurewebsites.net/
curl https://$APP_SERVICE_NAME.azurewebsites.net/api/delay
curl https://$APP_SERVICE_NAME.azurewebsites.net/api/error

Back in the Azure portal, open your Application Insights resource. Under Investigate > Transactions, you should see a list of requests. If you click on one, you'll see the trace, including the custom log we sent.

Now try a KQL query to see your data:

requests
| where timestamp > ago(1h)
| project timestamp, name, success, duration, resultCode
| order by timestamp desc

And to see exceptions:

exceptions
| where timestamp > ago(1h)
| project timestamp, type, method, problemId

Pro tip: Use | take 10 to limit results while testing. Queries can be expensive if you accidentally scan a month of high-volume telemetry.

Step 5: Set up an alert rule

Now let's automate the response. Create an alert on failed requests:

az monitor metrics alert create \
  --name "High Failures" \
  --resource-group $RESOURCE_GROUP \
  --scopes $(az monitor app-insights component show --app $INSIGHTS_NAME --resource-group $RESOURCE_GROUP --query id -o tsv) \
  --condition "count failed requests > 5" \
  --description "Alert when more than 5 failed requests in a minute"

You'll get an email (or action group) when the threshold is breached. To test, hit /api/error more than 5 times in a minute.

Note: Alerts have a frequency and evaluation period. By default, the Azure CLI alert may evaluate every minute. Adjust with --frequency and --window-size for finer control.

Compare options / when to choose what

Azure Monitor offers multiple ways to get telemetry from your app. Here's a comparison to help you choose:

Approach Best for Pros Cons
Application Insights SDK (OpenCensus/OpenTelemetry) Code-level insight, custom events, distributed tracing Deep integration, custom metrics, rich context Requires code changes, adds a dependency
App Service built-in monitoring Quick start without code changes Zero-code, works with any language Limited to HTTP calls and basic metrics, no custom events
Azure Monitor Agent (source: VM) VM-level monitoring, OS metrics No app changes needed Not application-specific; you see the VM, not the app logic
Log Analytics workspace + custom logging You already use Log Analytics, want full KQL power Flexible, can store any data No pre-built app telemetry; you build everything yourself

When to choose what:

  • For a new app or when you need detailed diagnostics (like custom events or dependency tracing), use the SDK.
  • For a quick smoke test on an existing App Service, enable Application Insights from the portal — it can add the SDK automatically (at least for .NET/Node.js).
  • If your app runs on a VM and you just need CPU/memory, use the Azure Monitor Agent.
  • If you're building a custom telemetry pipeline, start with a Log Analytics workspace and use the Logs Ingestion API.

Troubleshooting & edge cases

Even with the SDK, things can go wrong. Here are the common issues you'll hit:

  • No telemetry appears in the portal.
  • Check your connection string is correct and not truncated. Use print(os.getenv('APPLICATIONINSIGHTS_CONNECTION_STRING')) to verify.
  • Ensure your app is actually running and receiving traffic. requests table stays empty if no requests reach the app.
  • Firewall rules on your App Service might block outbound calls to ingestion endpoints. Allow HTTPS to *.applicationinsights.azure.com.

  • Alerts never fire.

  • Check the alert condition — maybe your metric is failed requests but you're looking at requests? Understand the metric names.
  • The alert might not have an action group configured, so no notification is sent. Use az monitor metrics alert action-group list to verify.
  • The evaluation period might be longer than your test window — wait a few minutes.

  • Custom logging doesn't appear.

  • If you use logging.exception, make sure your logger level is set to ERROR or lower. By default, Python's root logger might not propagate.
  • Check for missing AzureLogHandler — it's part of opencensus-ext-azure. Import errors will silently skip logging.

  • Performance hit.

  • The OpenCensus SDK adds a small overhead. In high-throughput apps, use sampling to send a percentage of telemetry. Set sampling_rate in the exporter configuration.
  • In .NET apps, disable expensive collectors like dependency tracking for internal services if not needed.

  • Telemetry from local dev only, not production.

  • Your app might be using a different connection string in production. Inject it via environment variables consistently.

What you learned & what's next

In this lesson, you learned how to set up Azure Monitor for applications using Application Insights. Specifically:

  • What Azure Monitor and Application Insights are, and how they fit together.
  • How to create an Application Insights resource and get a connection string.
  • How to instrument a Flask app with OpenCensus to send requests, traces, and custom logs.
  • How to verify telemetry in the portal and run KQL queries.
  • How to create metric alerts to get notified proactively.
  • How to troubleshoot common setup issues.

You've now got the foundation for observability — the ability to know what your app is doing at any moment. This is crucial for the next lesson in the track, where you'll likely learn about Azure Log Analytics workspaces or advanced alerting with action groups. Understanding how to collect and query telemetry will make those lessons much easier, because you already know where the data lives and how to access it.

Next step: In the upcoming lesson, you'll learn how to query your Application Insights data in depth with Kusto, create dashboards, and set up more sophisticated alerts. The skills you've built here — understanding telemetry, connection strings, and alert conditions — will be your starting point.

Practice recap

To solidify your skills, create a new Application Insights resource and instrument the sample Flask app above. Generate a few requests, then try the KQL queries to find the slowest request and the most common exception. Finally, add an alert that notifies you when the average response time exceeds 2 seconds.

Common mistakes

  • Hard-coding the connection string in your code. Instead, use environment variables or Azure App Service settings — you'll avoid leaking secrets in your repo.
  • Forgetting to add the AzureLogHandler to the root logger. If your logger is configured incorrectly, custom log messages silently disappear.
  • Creating an alert without an action group — the alert rule exists, but no one gets notified. Always attach an email, SMS, or webhook.
  • Not generating any traffic before checking the portal, so requests is empty and you think it's broken. Drive a few requests with curl first.

Variations

  1. Use the Azure portal to add Application Insights to an existing App Service — it can auto-instrument .NET or Node.js apps with minimal code changes.
  2. For .NET apps, use the official Microsoft.ApplicationInsights.AspNetCore SDK instead of OpenCensus — it gives you automatic HTTP dependency tracking out of the box.
  3. Use the OpenTelemetry collector as an agent alongside your app to process and export telemetry to Azure Monitor, giving you more control over sampling and exporting.

Real-world use cases

  • A production e-commerce site uses Application Insights to monitor checkout failures and receives an alert before customer complaints.
  • A microservices team traces a slow API call across three services using distributed tracing to find the bottleneck exactly.
  • A DevOps engineer uses KQL queries in Application Insights to analyze error rates after a release and roll back if thresholds are exceeded.

Key takeaways

  • Azure Monitor is the umbrella; Application Insights is the app-level telemetry tooling inside it.
  • The connection string is the key — it's how your app talks to Application Insights. Keep it secret and inject via settings.
  • OpenCensus/OpenTelemetry lets you instrument Python apps quickly with automatic request tracking and custom logging.
  • KQL queries in the portal let you investigate issues beyond what dashboards show.
  • Alerts are essential — set them up early so you're notified proactively, not reactively.
  • Troubleshooting is easier when you trace the path: app → connection string → ingestion → portal.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.