Lesson 2 of 2 Distributed Tracing with OpenTelemetry

Instrumenting Python Applications for Azure Monitor

This lesson explains the Azure Monitor OpenTelemetry distro for Python, automatic instrumentation, custom spans, service names and authenticated telemetry.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe what configure_azure_monitor sets up.
  • Identify the libraries instrumented automatically.
  • Explain when and how to create custom spans.
  • Describe how cloud role names and Entra authentication are configured.

The Azure Monitor OpenTelemetry distro

Setting up OpenTelemetry by hand requires a tracer provider, a meter provider, a logger provider, exporters, processors and instrumentations. A distro packages these choices. For Python, azure-monitor-opentelemetry provides configure_azure_monitor(), which sets up all three signals, enables bundled instrumentations and exports to Application Insights. Microsoft now also offers the Microsoft OpenTelemetry Distro (microsoft-opentelemetry, with use_microsoft_opentelemetry(enable_azure_monitor=True)) as its recommendation for new applications; applications already using the Azure Monitor distro need no change.

import logging
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor(logger_name="orders_api")    # reads APPLICATIONINSIGHTS_CONNECTION_STRING
logger = logging.getLogger("orders_api")
logger.setLevel(logging.INFO)

from fastapi import FastAPI                           # import instrumented libraries after configuring
app = FastAPI()

The distro reads the Application Insights connection string from the APPLICATIONINSIGHTS_CONNECTION_STRING environment variable, which is the recommended way to supply it in production. The logger_name option collects logs only from the application's own logger, avoiding the SDK's internal messages. Configuration should run once, as early as possible, before the instrumented libraries are used.

Spot the bug

A distro that misses telemetry

Exam skills 4.2.1

Find the lines that stop this FastAPI app from sending complete, safe telemetry.

Log in to try this activity Interactive activities are free with an account.

Automatic instrumentation

The distro enables instrumentations that create spans without code changes for common libraries: the web frameworks Django, FastAPI and Flask, the HTTP clients requests, urllib and urllib3, the PostgreSQL driver psycopg2, and Azure SDK calls such as Cosmos DB, Service Bus, Key Vault and Storage. Incoming requests become SERVER spans, and outgoing calls become CLIENT spans with standard attributes.

Libraries outside the bundled set can be instrumented by installing the corresponding OpenTelemetry instrumentation package, such as one for psycopg 3, httpx or redis, and enabling it; once the global tracer provider is configured by the distro, their spans flow to Application Insights too. Instrumentations can also be disabled selectively through the distro's options.

Sort into groups

Who creates this span?

Exam skills 4.2.1

Decide how each operation gets a span in Application Insights.

Log in to try this activity Interactive activities are free with an account.

Custom spans, attributes and events

Automatic instrumentation sees requests and calls but not the application's own steps. A RAG pipeline's chunking, prompt assembly or reranking is invisible unless the code creates custom spans. The OpenTelemetry API provides a tracer for this.

from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode

tracer = trace.get_tracer(__name__)

def retrieve(question, tenant):
    with tracer.start_as_current_span("retrieve-context") as span:
        span.set_attribute("app.tenant", tenant)
        span.set_attribute("app.top_k", 5)
        try:
            chunks = vector_search(question, tenant)       # instrumented calls become child spans
            span.set_attribute("app.chunks_returned", len(chunks))
            if not chunks:
                span.add_event("no-context-found")
            return chunks
        except Exception as err:
            span.record_exception(err)
            span.set_status(Status(StatusCode.ERROR, "retrieval failed"))
            raise

Spans started with start_as_current_span become the parent of spans created inside them, including those from automatic instrumentation, so the trace shows the retrieval step containing its database calls. Attributes appear as custom dimensions in Application Insights and can be queried with KQL. Sensitive data, such as prompts containing personal information, should not be added as attributes.

The following diagram compares a request waterfall in Application Insights before and after custom spans are added.

A request waterfall before and after custom spans. Automatic instrumentation records the 4-second request, the 300 ms Cosmos DB dependency and the 800 ms model call, leaving almost three seconds without spans. Custom spans for chunk filtering, reranking and prompt assembly appear as children of the request and show which step is slow.
The positions of the custom spans are illustrative.
Select all that apply

Writing custom spans

Exam skills 4.2.1

Identify the good practices for custom spans in a RAG pipeline.

Log in to try this activity Interactive activities are free with an account.

Service names, authentication and hosting

Application Insights uses the OpenTelemetry service.name resource attribute as the cloud role name, which separates services on the application map and in queries. It is set with the OTEL_SERVICE_NAME environment variable or OTEL_RESOURCE_ATTRIBUTES (for example service.name=orders-api,service.namespace=retail). When several services send to one Application Insights resource, setting distinct names is required for a meaningful map.

By default, telemetry is sent with the instrumentation key in the connection string. For stronger security, local authentication can be disabled on the Application Insights resource so that only Microsoft Entra-authenticated telemetry is accepted; the application then passes a credential to the distro (configure_azure_monitor(credential=DefaultAzureCredential())), and its identity needs the Monitoring Metrics Publisher role on the resource.

Hosting platforms integrate with this model. Container Apps and App Service pass the connection string as an environment variable. Azure Functions can emit OpenTelemetry from both the host and the Python worker when OpenTelemetry mode is enabled in host.json and the worker setting is turned on, so that function invocations join traces from the services that called them.

Automatic instrumentation
Created byInstrumentation libraries
CoversIncoming requests, HTTP calls, database and Azure SDK calls
EffortConfiguration only
Choose when Every service, by default
Custom spans
Created byApplication code with the tracer
CoversBusiness steps such as chunking, reranking, prompt building
EffortA few lines per step
Choose when Steps whose duration or outcome matters
Scenario questions

Securing and hosting telemetry

Exam skills 4.2.1

Choose the configuration that fits each requirement.

Log in to try this activity Interactive activities are free with an account.
Worked example

Finding a slow step in a RAG API

A FastAPI RAG service is instrumented with configure_azure_monitor. Application Insights shows requests taking 4 seconds at the 95th percentile, with a 300 ms Cosmos DB dependency and an 800 ms model call. Nearly three seconds are unaccounted for. Two other services send to the same resource, and the application map shows them all as one node.

The missing time is in code that automatic instrumentation does not cover. Wrapping the pipeline's steps, such as chunk filtering, reranking and prompt assembly, in custom spans with useful attributes reveals which step is slow, because each appears as a child of the request. Setting OTEL_SERVICE_NAME differently for each service gives each its own cloud role name and separates them on the application map.

Raising the sampling ratio would record more of the same incomplete spans. Adding log statements with timings helps but does not place durations in the trace tree. Creating separate Application Insights resources per service would break the shared end-to-end view.

Check yourself

Which environment variable sets the cloud role name that separates services on the application map?

Show answer

OTEL_SERVICE_NAME (or service.name in OTEL_RESOURCE_ATTRIBUTES).

Exam Tips

Remember for the exam

  • configure_azure_monitor() sets up traces, metrics and logs and reads APPLICATIONINSIGHTS_CONNECTION_STRING.
  • Microsoft recommends the Microsoft OpenTelemetry Distro for new apps; existing distro users need no change.
  • Bundled instrumentations: Django, FastAPI, Flask, requests, urllib, urllib3, psycopg2 and the Azure SDK.
  • Custom spans with attributes reveal business steps; OTEL_SERVICE_NAME sets the cloud role name.