Configure Application Insights Telemetry

Configure Application Insights Telemetry in Azure: a focused lesson on enabling and customizing telemetry for your apps. Hands-on steps, edge cases, and troubleshooting included.

Focus: configure application insights telemetry

Sponsored

You've just deployed an application to Azure, watching it scale beautifully — until a user reports a 500 error or a slowdown that only happens at 2 AM. You're blind: no logs, no metrics, no insight into what went wrong. That's the pain this lesson removes. Configuring Application Insights telemetry gives your application a 24/7 health monitor, a diagnostic magnifying glass, and a performance radar — all without rewriting your app from scratch. Let's unlock that clarity.

The problem this lesson solves

Every Azure developer eventually hits the same wall: your app runs, but you can't see inside it. Debugging becomes a guessing game — restart, reproduce, pray. You need more than logs scattered across servers; you need distributed telemetry — requests, dependencies, exceptions, and traces — all correlated into one view. That's exactly what Application Insights provides. It answers questions like: Which endpoint is slow? Why did that order fail? What's the trend in memory usage? Without it, you're flying a plane with no instruments.

Core concept / mental model

Think of Application Insights as a flight recorder for your cloud app. It captures telemetry — events, metrics, and traces — from your application and sends them to an Azure resource. This resource is like a control tower that visualizes data as dashboards, queryable logs, and alerts.

Here's the anatomy of telemetry in Application Insights:

  • Instrumentation key (or connection string): a unique identifier your app uses to send data.
  • Telemetry processors: your code (or SDK) constructs telemetry items.
  • Channel: batches and sends telemetry to Azure via HTTPS.
  • Resource: stores the data; you view it in the Azure portal.
flowchart LR
  A[Your App] --> B[Application Insights SDK]
  B --> C[Channel]
  C --> D[Azure: App Insights Resource]
  D --> E[Dashboards & Queries]

Think of configuration as two halves: infrastructure (creating the resource) and instrumentation (connecting your code). Both matter — a resource without telemetry is an empty notebook; telemetry without a resource goes nowhere.

How it works step by step

Setting up telemetry follows a predictable flow:

  1. Create an Application Insights resource (or re-use one) to get a connection string.
  2. Install the Application Insights SDK in your app.
  3. Instrument your code — either automatically (auto-instrumentation) or via SDK calls.
  4. Configure sampling, filters, and custom events as needed.
  5. Verify telemetry arrives in the portal.

Cause and effect: without step 1, step 2 produces orphans. More telemetry isn't always better — too much can cost money. Balance matters.

Hands-on walkthrough

Let's configure telemetry for a small Python Flask app. This mirrors what you'll do in production.

Step 1: Create the resource

All examples assume Python 3.10+ and Azure CLI. Sign in, create a resource group if needed, then create an App Insights resource:

az login
az group create --name rg-telemetry-demo --location eastus
az monitor app-insights component create \
  --app demo-app-insights \
  --location eastus \
  --resource-group rg-telemetry-demo \
  --application-type web

The output includes connectionString — copy it. This is your key to the control tower.

Step 2: Install SDK and instrument

Create app.py and install the OpenCensus Azure exporters (a lightweight alternative to the older SDK):

pip install opencensus-ext-azure opencensus-ext-flask
# app.py
from flask import Flask, request
from opencensus.ext.azure.log_exporter import AzureLogHandler
from opencensus.ext.flask.flask_middleware import FlaskMiddleware
import logging

app = Flask(__name__)

# Replace with your connection string
CONNECTION_STRING = "InstrumentationKey=...;IngestionEndpoint=https://..."

# Auto-collect Flask requests
FlaskMiddleware(app, exporter=azure_monitor_exporter.AzureExporter(connection_string=CONNECTION_STRING))

# Set up logging
logger = logging.getLogger(__name__)
logger.addHandler(AzureLogHandler(connection_string=CONNECTION_STRING))
logger.setLevel(logging.INFO)

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

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Run python app.py, hit http://localhost:5000 a few times, then check the portal. Within a minute, you should see requests and traces under Application Insights -> Logs.

Step 3: Custom telemetry

Beyond automatic requests, send custom events and metrics:

from opencensus.stats import stats as stats_module
from opencensus.stats import measure
from opencensus.stats import aggregation
from opencensus.stats import view
from opencensus.ext.azure import metrics_exporter

m = measure.MeasureInt("orders", "number of orders", "count")
v = view.View("orders_view", "total orders", [], m, aggregation.CountAggregation())
stats_module.view_manager.register_view(v)
mmap = stats_module.stats_recorder.new_measurement_map()

def create_order():
    logger.info("Order created")
    mmap.measure_int_put(m, 1)
    mmap.record()

This sends a custom metric you can chart and alert on.

Pro tip: Don't put secrets in code — use environment variables or Azure Key Vault for the connection string.

Compare options / when to choose what

You have several ways to connect your app about telemetry. Choose based on cost, effort, and control.

Option Best for Pros Cons
Auto-instrumentation (Azure App Service, Functions) Zero-code setup No code changes Limited control; only supported runtimes
SDK/OpenCensus Custom apps (Python, Node, .NET) Full control, custom events Requires code changes
OpenTelemetry Future-proof, multi-cloud Vendor-agnostic, rich ecosystem Newer; more setup

If you run on Azure PaaS (App Service), start with auto-instrumentation. If you need custom tracking or run anywhere else, use the SDK/OpenCensus. OpenTelemetry is the long-term standard — adopt it for new services.

Troubleshooting & edge cases

Common issues you'll hit and how to fix them.

  • No telemetry in portal: Check your connection string — a typo or wrong ending point breaks it. Verify network egress (corporate proxies, firewalls) and view live metrics.
  • Duplicate or missing requests: Sampling misconfig can drop data. Set sampling_percentage intentionally.
  • Incorrect timestamps or timezone: Ensure your server clock is synced (NTP).
  • Data volume spikes: Unexpected traffic spikes inflate costs. Enable adaptive sampling or set a daily cap.
  • SDK conflicts: Mixing OpenCensus and OpenTelemetry can cause double-sending or crashes. Use only one.
  • Connection string in source control: Leaked keys are a security risk — rotate and use Key Vault.

Example of a wrong output: logs show No handlers could be found for logger — means logger has no App Insights handler attached. Check your logger configuration.

What you learned & what's next

You now understand the core concept behind configuring Application Insights telemetry — from creating a resource to instrumenting code and verifying arrival. You've completed a practical exercise with custom metrics, and you know how to compare instrumentation methods.

Next, you'll explore querying telemetry for insights — using KQL to find bottlenecks and errors. That's where your flight recorder becomes actionable intelligence.

Key idea: Telemetry quality beats quantity. Configure what you need, then fine-tune.

Practice recap

For practice, add a custom event to your existing Flask app that tracks every 'checkout' attempt, then query it in the Azure portal. Try setting up an alert when the event count drops below a threshold — this simulates a production monitoring scenario.

Common mistakes

  • Hardcoding the connection string in source code — use environment variables or Key Vault.
  • Sending too much telemetry without sampling, leading to high costs and noise.
  • Misconfiguring the SDK to use both OpenCensus and OpenTelemetry, causing double ingestion.
  • Forgetting to flush telemetry on shutdown, so the last events are lost.

Variations

  1. Use OpenTelemetry for vendor-neutral instrumentation.
  2. Enable auto-instrumentation on Azure App Service for zero-code setup.
  3. Use Azure Functions' built-in Application Insights integration.

Real-world use cases

  • A microservices-based e-commerce platform monitors each service for latency and errors, correlating across services.
  • A background job worker sends custom metrics for queue depth and processing time to trigger autoscaling alerts.
  • A mobile API gateway logs every request to audit unauthorized access attempts and track API usage patterns.

Key takeaways

  • Application Insights acts as your app's flight recorder — capture telemetry, not just logs.
  • Always use a connection string (or instrumentation key) correctly — it's your app's ID to send data.
  • Instrument with auto-instrumentation, SDK, or OpenTelemetry based on your app's needs and control.
  • Send custom events and metrics to track what matters to your business.
  • Monitor and tune sampling to balance data richness and cost.
  • Troubleshoot telemetry by checking connection, network, and sampler config.

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.