OpenTelemetry & KQL
Microsoft OpenTelemetry Distro for Python · connection string · cloud role name · sampling · custom spans, metrics and exceptions · KQL operators
By the tools4free.dev team · Last reviewed November 13, 2026
Practice questions for this topic →
Enable OpenTelemetry in Python
OpenTelemetry (OTel) is a vendor-neutral observability framework. You instrument the application, collect telemetry and analyze it in Application Insights. The Microsoft OpenTelemetry Distro automatically collects traces, metrics and logs with built-in instrumentations and exports them to Azure Monitor, any OTLP endpoint, or Microsoft Agent 365.
| Language | Package | Install |
|---|---|---|
| Python | microsoft-opentelemetry | pip install microsoft-opentelemetry |
| Node.js | @microsoft/opentelemetry | npm install @microsoft/opentelemetry |
| .NET | Microsoft.OpenTelemetry | dotnet add package Microsoft.OpenTelemetry |
| Java | Agent or native-image integration | See the Java tabs |
- Python needs Python 3.10 or later.
- Initialize the distro before your application starts handling work: call
use_microsoft_opentelemetrywithenable_azure_monitor=True. - The install steps aren't an upgrade requirement for existing Azure Monitor OpenTelemetry Distro users. Don't initialize both distros in the same application.
- Custom telemetry in Python: the OpenTelemetry API covers custom metrics, dependencies, exceptions and requests; the Python logging module covers traces; the events extension covers custom events.
Connection string, cloud role and sampling
| Way to set the connection string | Languages | Use for |
|---|---|---|
Environment variable APPLICATIONINSIGHTS_CONNECTION_STRING | All | Production |
Configuration file applicationinsights.json | Java only | Production (Java) |
| In code | .NET, Node.js and Python | Local development and test only |
- The connection string identifies the Application Insights resource that receives your telemetry.
- Two or more services that emit telemetry to the same Application Insights resource: you're required to set Cloud Role Names to represent them properly on the Application Map.
- Cloud Role Name uses
service.namespaceandservice.name, and falls back toservice.nameifservice.namespaceisn't set. Cloud Role Instance usesservice.instance.id. - Set them with the
OTEL_RESOURCE_ATTRIBUTESand/orOTEL_SERVICE_NAMEenvironment variables.
| Sampling setting (Python) | Value |
|---|---|
| Default | Rate-limited sampling at five traces per second |
OTEL_TRACES_SAMPLER=microsoft.fixed_percentage | OTEL_TRACES_SAMPLER_ARG is a value in 0.0 to 1.0 (0.1 = about 10%) |
OTEL_TRACES_SAMPLER=microsoft.rate_limited | OTEL_TRACES_SAMPLER_ARG is the maximum traces per second (for example 1.5) |
- Sampling reduces telemetry ingestion volume and cost. Sampling decisions apply to traces (spans). Metrics are never sampled.
- Don't carry over the older Azure Monitor distro's
sampling_ratioandtraces_per_secondarguments; use the two environment variables. - Logs can follow trace sampling decisions: enabled by default in the .NET distro, disabled by default in the Node.js and Python versions.
OTEL_METRIC_EXPORT_INTERVALsets how often metrics are exported; the default is 60000 milliseconds (60 seconds).- Telemetry is cached when the application disconnects from Application Insights, and sending is retried for up to 48 hours.
Custom spans, metrics and exceptions
- Add a custom span when a dependency request isn't collected by an instrumentation library, or to model an application process on the end-to-end transaction view.
tracer.start_as_current_span()starts the span, makes it current and ends it within its context.- A custom span is in the
dependenciestable with dependency typeInProcby default. - For a background job that auto-instrumentation doesn't capture, set
kind = SpanKind.SERVERso that it appears in therequeststable. - The OpenTelemetry Python SDK automatically captures and records exceptions thrown in a span. To record manually, use
record_exception=Falseon the span and callrecord_exception(). - To add attributes to every span, register a
SpanProcessorthroughspan_processors; itson_startmethod callsspan.set_attribute. - Custom metrics: get a meter with
metrics.get_meter_provider().get_meter(...)and create instruments such asmeter.create_histogram.
KQL basics for logs and metrics
| Goal | KQL |
|---|---|
| Glance at a table (arbitrary rows) | SecurityEvent | take 10 |
| Latest 10 rows by time | SecurityEvent | top 10 by TimeGenerated |
| Filter rows | SecurityEvent | where Level == 8 |
| Recent time range | where TimeGenerated > ago(30m) |
| Pick columns | | project TimeGenerated, Computer, Activity |
| Add a column, keep the rest | | extend EventCode=substring(Activity, 0, 4) |
| Count per group | Perf | where TimeGenerated > ago(1h) | summarize count() by ObjectName |
| Average per time bucket | | summarize avg(CounterValue) by bin(TimeGenerated, 1h) |
- Queries can start with a table name or the
searchcommand. Start with a table name: it defines a clear scope and improves performance. KQL is case sensitive. - The pipe character separates commands, so the output of one is the input of the next.
takereturns arbitrary rows in no particular order.sortdoesn't limit the number of records.topsorts on the server side and returns only the top records; descending is the default.==is case-sensitive equality and=~is case-insensitive equality.- Place the time filter immediately after the table name. The time picker defaults to the last 24 hours.
SecurityEventLevel is a string, so cast it (for exampletoint(Level)) before numerical operators.- You need
Microsoft.OperationalInsights/workspaces/query/*/readpermissions, as provided by the Log Analytics Reader built-in role, for example.
KQL aggregation, join and charts
summarizegroups rows by thebyclause and combines each group with an aggregation function such ascount(),avg()orcountif();make_set()builds an array of unique values.- Summarizing by a raw time column creates a group for every millisecond. Use
bin(), which rounds values down to a multiple of a bin size. rendermust be the last operator in the query.projectkeeps only the columns you list;extendkeeps all original columns and adds new ones.
| Join kind | Rows returned |
|---|---|
innerunique (default) | Deduplicated left rows that match the right table |
inner | Only matching rows from both tables |
leftouter | All left rows and only matching right rows |
leftanti | Left rows that don't match any right row |
For best performance, if one table is always smaller than the other, use it as the left side of the join.
Application Insights requests are in the AppRequests table. Columns include AppRoleName, DurationMs, Success and ResultCode.
CLI and PowerShell
| Task | Azure CLI | PowerShell |
|---|---|---|
| Install the Python distro | pip install microsoft-opentelemetry | - |
| Set the connection string for production | export APPLICATIONINSIGHTS_CONNECTION_STRING="<ConnectionString>" | - |
| Keep about 10% of traces | export OTEL_TRACES_SAMPLER="microsoft.fixed_percentage"
export OTEL_TRACES_SAMPLER_ARG=0.1 | - |
| Limit to about 1.5 traces per second | export OTEL_TRACES_SAMPLER="microsoft.rate_limited"
export OTEL_TRACES_SAMPLER_ARG=1.5 | - |
| Custom span (Python) | - | with tracer.start_as_current_span("hello") as span: |
| Latest 10 rows (KQL) | - | SecurityEvent | top 10 by TimeGenerated |
| Count per group (KQL) | - | Perf | where TimeGenerated > ago(1h) | summarize count() by ObjectName |
| Hourly average (KQL) | - | Perf
| where TimeGenerated > ago(7d)
| where Computer == "DC01.na.contosohotels.com"
| where CounterName == "Available MBytes"
| summarize avg(CounterValue) by bin(TimeGenerated, 1h) |
Exam Tips
Tick each tip once you can answer it without looking.
“Install OpenTelemetry for a Python app that reports to Application Insights” → pip install microsoft-opentelemetry. Trap: Microsoft.OpenTelemetry is .NET; @microsoft/opentelemetry is Node.js.
“Production connection string” → Environment variable APPLICATIONINSIGHTS_CONNECTION_STRING. Trap: In code is for local dev/test; applicationinsights.json is Java only.
“Two services in one Application Insights resource look like one node” → Set Cloud Role Names (OTEL_SERVICE_NAME, service.namespace). Trap: The connection string names the resource, not the role.
“Cloud role name when service.namespace isn't set” → Falls back to service.name. Trap: Cloud Role Instance comes from service.instance.id.
“Python distro default sampling” → Rate-limited, five traces per second. Trap: It doesn't keep all traces by default.
“Keep about 10% of traces” → microsoft.fixed_percentage with OTEL_TRACES_SAMPLER_ARG=0.1. Trap: The argument is 0.0 to 1.0, not 10; sampling_ratio is the older distro's argument.
“Reduce metrics volume with sampling” → Not possible: sampling applies to traces; metrics are never sampled. Trap: Logs can follow trace sampling, but metrics don't.
“Custom span for a background job must show in requests” → kind = SpanKind.SERVER. Trap: By default a custom span lands in dependencies as InProc.
“Add the same attribute to every span” → SpanProcessor in span_processors, set_attribute in on_start. Trap: Resource attributes describe the service, not each span.
“Exceptions thrown inside a span” → Recorded automatically; record_exception=False to do it manually. Trap: Manual record_exception() is needed only after you disable the automatic recording.
“Latest N rows by time” → | top N by TimeGenerated. Trap: take is arbitrary; sort doesn't limit rows.
“Average per hour over 7 days” → summarize avg(...) by bin(TimeGenerated, 1h). Trap: Grouping by TimeGenerated alone makes a group per millisecond.
“Add a column and keep the others” → extend. Trap: project drops columns you don't list.
“Case-insensitive match” → =~. Trap: == is case-sensitive.
“Left rows with no match on the right” → join kind=leftanti. Trap: inner keeps matches; the default is innerunique.
“Chart the result of a query” → | render ... as the last operator. Trap: Nothing can follow render.
Sources
- Application Insights OpenTelemetry observability overview
- Enable OpenTelemetry in Application Insights
- Configure OpenTelemetry in Application Insights
- Add and modify OpenTelemetry in Application Insights
- Get started with log queries in Azure Monitor Logs
- Tutorial: Learn common KQL operators
- Tutorial: Use aggregation functions in KQL
- summarize operator
- where operator
- join operator
- render operator
- bin() function
- ago() function
- AppRequests table reference
Checked against Microsoft Learn on November 13, 2026.