KQL Queries for Logs and Metrics
30-second answer
Kusto Query Language (KQL) asks questions of the logs in Application Insights and Log Analytics. A query starts with a table and pipes rows through operators: where filters, project picks columns, extend adds columns, summarize aggregates (count(), avg(), percentile()) usually by bin(timestamp, 5m), and render timechart draws it. A log search alert runs a KQL query on a schedule; a metric alert watches a numeric metric in near real time.
Exam objective: 4.2.2 Write KQL queries to analyze logs and metrics. (Skills measured as of October 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
Open <strong>Logs</strong> in the workspace and switch to <strong>KQL mode</strong>. Each <code>|</code> passes rows to the next step: filter, group, chart.
👆 Click the glowing item in the portal to continue
Read the steps as text
- Open Logs in the workspace and switch to KQL mode. Each | passes rows to the next step: filter, group, chart.
- A spike at 09:15. You don’t want to find the next one by luck, so select + New alert rule.
- The query becomes the condition: every 5 minutes, alert if failures are greater than 10.
- An action group says who hears about it and how. Reuse one across many alerts.
- Give it a clear name and a severity. The name is what lands in someone’s inbox.
- Review and Create. Log search alerts are billed per rule, a few dollars a month at most.
- Next time failures spike, the alert fires and the on-call engineer gets a message with a link back to the query.
🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.
🖱️ Drag to rotate · scroll or pinch to zoom
Ask with KQL
Kusto Query Language (KQL) reads top to bottom through pipes: requests | where success == false | summarize count() by bin(timestamp, 5m) | render timechart. where filters, summarize aggregates, project picks columns, join combines tables.
🤔 What happens if…
Read this tour as text
- Secrets don’t belong in code. A connection string in
config.pyends up in git, in screenshots and in old laptops. Azure Key Vault stores secrets, keys and certificates. The app reads them at run time with a managed identity, so there’s no password to steal. - Versions and rotation. Each time you set a secret, Key Vault keeps a new version. Apps that ask for the secret without a version get the latest. Rotation creates a new version: for keys, a rotation policy does it on a schedule; for secrets, Key Vault raises a
SecretNearExpiryevent through Event Grid and your function sets the new value. Apps pick it up without a redeploy. - App Configuration. Azure App Configuration holds settings as key-values with optional labels (dev, prod) and feature flags. It can point at Key Vault with Key Vault references. Apps refresh settings without restarting, often by watching a sentinel key.
- A trace across services. One user question goes web API → queue → worker → Cosmos DB → model. OpenTelemetry gives every hop a span that shares one trace ID, so you see the whole journey. The Azure Monitor OpenTelemetry Distro sends it to Application Insights.
- Find the slow span. The trace shows each span’s duration. Here the model call is fine, but a Cosmos DB query without a partition key takes 2.4 seconds. Custom spans and attributes (like
tenant.id) make the story even clearer. - Logs live in tables. Application Insights and Log Analytics store telemetry in tables:
requests,dependencies,exceptions,traces, plus metrics. Container Apps logs land inContainerAppConsoleLogs_CL, AKS inContainerLogV2. - Ask with KQL. Kusto Query Language (KQL) reads top to bottom through pipes:
requests | where success == false | summarize count() by bin(timestamp, 5m) | render timechart.wherefilters,summarizeaggregates,projectpicks columns,joincombines tables. - Turn a query into an alert. A log search alert runs a KQL query on a schedule and fires when the result crosses a threshold. A metric alert watches a number like CPU or queue length. Either can email the team or call a webhook.
A user says "the chat hung". Instrument the app with OpenTelemetry, find the failed request with KQL, follow its operation_Id to the slow model call, measure dependencies and set an alert so you hear about it first next time.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
The logs exist, but finding one error takes an hour of scrolling.
😊 THE SOLUTION
Ask the logs a question with KQL and chart the answer.
- Endless scrolling✓ where and project
- No trend view✓ summarize by bin()
- Find out from users✓ Log search alerts
Start with a question
The logs have everything. So why does finding one error take an hour?
Because you’re scrolling. Two million log lines a day, and you’re paging through them looking for the one that says “timeout”. By the time you find it, users have already told you the app is broken.
The logs aren’t the problem. Reading them by hand is. KQL lets you ask the logs a question, like “how many requests failed in each 5-minute window today?”, and get a chart back in a second. Then you save that question as an alert, so next time you hear about it before your users do.
Explain it like I’m 10
The technical explanation
Where the data lives
Telemetry from Application Insights and other Azure resources lands in tables. The same data has two sets of names, depending on where you query it:
| Data | Application Insights (classic names) | Log Analytics workspace |
|---|---|---|
| Incoming requests | requests (timestamp, name, success, duration, resultCode) | AppRequests (TimeGenerated, Name, Success, DurationMs, ResultCode) |
| Outgoing calls | dependencies | AppDependencies |
| Exceptions | exceptions | AppExceptions |
| Log messages | traces | AppTraces |
| Custom metrics | customMetrics | AppMetrics |
| Container Apps stdout/stderr | — | ContainerAppConsoleLogs_CL (ContainerAppName_s, Log_s) |
| AKS container logs | — | ContainerLogV2 (PodName, ContainerName, LogMessage) |
Every Application Insights row carries operation_Id (the OpenTelemetry trace ID) and cloud_RoleName (the service name). In the workspace those are OperationId and AppRoleName.
The operators you’ll use every day
A query reads top to bottom. Each | hands the rows to the next step.
| Operator | Does | Example |
|---|---|---|
where | Keeps matching rows | where timestamp > ago(1h) and success == false |
project | Picks (and renames) columns | project timestamp, name, duration |
extend | Adds a calculated column | extend seconds = duration / 1000 |
summarize | Groups and aggregates | summarize count(), avg(duration) by name |
bin() | Buckets numbers or time | by bin(timestamp, 5m) |
top / sort by / take | Orders and limits | top 10 by duration desc |
join | Combines two tables | join kind=inner (exceptions) on operation_Id |
render | Draws a chart | render timechart |
Useful aggregates: count(), countif(), dcount() (distinct count), avg(), sum(), max(), percentile(duration, 95) and percentiles(duration, 50, 95, 99).
Queries worth knowing
Failed requests over time:
requests
| where timestamp > ago(24h)
| summarize failed = countif(success == false), total = count() by bin(timestamp, 5m)
| extend failRate = round(100.0 * failed / total, 1)
| render timechart
Slowest operations by 95th percentile:
requests
| where timestamp > ago(1h)
| summarize p95 = percentile(duration, 95), calls = count() by name
| top 10 by p95 desc
Which dependency is slow for the /ask endpoint:
dependencies
| where timestamp > ago(1h) and operation_Name == "POST /ask"
| summarize avgMs = avg(duration), p95 = percentile(duration, 95) by target, type
| sort by p95 desc
Failed requests with their exception message (a join on the trace ID):
requests
| where timestamp > ago(1h) and success == false
| project operation_Id, name, resultCode, timestamp
| join kind=inner (
exceptions | project operation_Id, type, outerMessage
) on operation_Id
| take 50
Errors from one container app:
ContainerAppConsoleLogs_CL
| where TimeGenerated > ago(30m)
| where ContainerAppName_s == "summary-worker" and Log_s has "error"
| project TimeGenerated, RevisionName_s, Log_s
| sort by TimeGenerated desc
A custom metric your code sends (for example tokens used):
customMetrics
| where timestamp > ago(1d) and name == "gen_ai.tokens"
| summarize tokens = sum(valueSum) by bin(timestamp, 1h), cloud_RoleName
| render timechart
-
1 Table
requests: every incoming call.
-
2 where
Last 24 hours, failed only.
-
3 summarize
Count per 5-minute bin.
-
4 render
A timechart you can pin or alert on.
Logs vs metrics, and the two alert types
Metrics are numbers sampled at regular intervals (CPU, request count, queue length), stored in a time-series database and fast to chart in Metrics explorer. Logs are rows with lots of detail, queried with KQL.
| Metric alert | Log search alert | |
|---|---|---|
| Watches | A platform or custom metric | The result of a KQL query |
| Evaluated | About every minute | On a schedule you set (for example every 5 minutes over the last 15) |
| Good for | CPU over 80%, queue length over 1,000 | Failure rate per endpoint, a specific exception text, a pattern across tables |
| Cost | Lower | Higher, and grows with how often it runs |
Both send notifications through an action group (email, SMS, webhook, Logic App, Azure Function). In the portal you can go straight from a query in Logs to New alert rule, and the query is carried over.
Architect level Writing queries that stay fast and cheap
Filter on time first, then on other columns, because tables are partitioned by time and the engine can skip whole chunks. Prefer has over contains for whole words: has uses the term index, contains scans every string. Project away big columns (like customDimensions) before a join, and put the smaller table on the left. For dashboards over long periods, summarise into bins instead of returning raw rows. And for alerts, keep the look-back window short: a log search alert that scans 24 hours every 5 minutes is slow and costs more than one that scans 15 minutes.
Real-world business scenario
Northwind Retail (fictional)
- The problem
- A product Q&A assistant on Container Apps failed now and then, but the team only found out from customer complaints and spent an hour each time searching raw logs.
- What they used
- A KQL query on requests that calculates the failure rate per 5 minutes, a join to exceptions on operation_Id to show the error message, a ContainerAppConsoleLogs_CL query for the worker, and a log search alert at 5% failures over 10 minutes.
- Why that choice
- The query answers the real question (how often, where, and why) in seconds, and the alert runs the same query on a schedule.
- The result
- The next incident, a model quota limit, paged the on-call engineer within ten minutes, with the exception text already in the alert.
When to use it and when not to
✓ Use it when…
- You need to find, count or chart events across millions of log rows.
- You want to correlate requests, dependencies and exceptions by operation_Id.
- An alert depends on a condition only a query can express.
✕ Think twice when…
- A simple threshold on a number Azure already tracks as a metric. A metric alert is faster and cheaper.
- Changing data. KQL is read-only for querying.
↔ Alternatives to consider
- Metrics explorer and metric alerts for CPU, request counts and queue lengths.
- Application Insights views (application map, failures, performance) for a quick look before writing a query.
Test yourself with exercises
5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner How do you read a KQL query?
Model answer
Top to bottom. It starts with a table, and each pipe passes the rows to the next operator. So requests | where success == false | count means "take requests, keep the failed ones, count them".
Intermediate How would you find the slowest operations in the last hour?
Model answer
requests | where timestamp > ago(1h) | summarize p95 = percentile(duration, 95), calls = count() by name | top 10 by p95 desc. I use the 95th percentile rather than the average because a few very slow calls hide inside an average.
Experienced developer Why does the same query fail when you run it in the Log Analytics workspace instead of Application Insights?
Model answer
Workspace-based Application Insights stores data in tables with different names and columns. In Application Insights Logs I can use requests with timestamp, success and duration. In the workspace the table is AppRequests with TimeGenerated, Success and DurationMs. Same data, different schema.
Scenario A container app is crash-looping. Where do you look with KQL?
Model answer
ContainerAppConsoleLogs_CL for what the app wrote to stdout and stderr, filtered by ContainerAppName_s and sorted by time, and ContainerAppSystemLogs_CL for platform events like failed probes. For AKS I'd query ContainerLogV2 by PodName and ContainerName.
Architecture & design When would you pick a log search alert over a metric alert?
Model answer
A metric alert when there's a metric that already says it, like CPU, request count or Service Bus queue length. It's evaluated about every minute and is cheaper. A log search alert when the condition needs a query, like "more than 5% of /ask calls failed for tenant X" or "this exception text appeared". It runs on a schedule, so it's a bit slower to fire.
Quick revision
Key points
- A query starts with a table; each | passes rows to the next operator.
- where filters, project picks columns, extend adds computed columns.
- summarize aggregates with count(), avg(), percentile(), dcount() by one or more columns.
- bin(timestamp, 5m) buckets time; render timechart draws a chart.
- top, sort by (order by), take limit rows; join combines tables, often on operation_Id.
- Classic names: requests, dependencies, exceptions, traces, customMetrics. Workspace names: AppRequests, AppDependencies, AppExceptions, AppTraces, AppMetrics.
- Log search alerts run KQL on a schedule; metric alerts watch metrics in near real time.
Important terminology
- KQL
- Kusto Query Language, the read-only, pipe-based query language used by Azure Monitor Logs, Application Insights and Azure Data Explorer.
- Log Analytics workspace
- The Azure Monitor store that holds log tables you query with KQL.
- summarize
- The KQL operator that groups rows and calculates aggregates such as count(), avg() and percentile().
- bin()
- A KQL function that rounds values (usually time) down into fixed-size buckets, such as 5-minute intervals.
- Workspace-based Application Insights
- Application Insights that stores data in a Log Analytics workspace, in tables such as AppRequests and AppDependencies.
- Log search alert
- An Azure Monitor alert rule that runs a KQL query on a schedule and fires when the result meets a condition.
- Metric alert
- An Azure Monitor alert rule that evaluates a numeric metric, such as CPU or request count, every minute or so.
Common mistakes
- Using timestamp and success in a workspace query, where the columns are TimeGenerated and Success.
- Forgetting a time filter such as ago(1h), which scans more data and runs slower.
- Averaging durations when the question asks for the experience of most users. Use percentiles.
Exam tips
- "Count failures in 5-minute intervals" = summarize count() by bin(timestamp, 5m).
- "Show a trend as a line chart" = render timechart.
- "Combine a request with its exceptions" = join on operation_Id.
- "Alert on a pattern in log data" = log search alert.
Five quick revision questions
-
1.Which operator adds a calculated column?Show
extend.
-
2.Which function returns the time 24 hours ago?Show
ago(24h).
-
3.Which table holds outgoing calls in classic Application Insights?Show
dependencies.
-
4.Which table holds Container Apps console output?Show
ContainerAppConsoleLogs_CL.
-
5.Which operator keeps only some columns?Show
project.
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.