Overview and What You Will Learn
Kusto Query Language (KQL) is the read-only query language for Log Analytics, and a KQL query is a pipeline that starts with a table and narrows or reshapes the rows one step at a time. In this lab you will connect a VM to a Log Analytics Workspace, generate some failing log lines, and write queries that go from "a pile of raw logs" to "which error happened, how often, and when".
- Sending VM logs to a workspace with the Azure Monitor Agent and a data collection rule
- Starting a query with a table and filtering by time with
whereandago() - Picking columns with
projectand adding columns withextend - Counting and grouping with
summarizeandbin() - Running queries from the portal or the Azure CLI
Why This Matters in Production
Being able to query logs turns a vague report into a root cause in minutes. Imagine a platform team at a company like Grab told only that "checkout is slow sometimes". Without filtering by time range, error type and frequency, an engineer scrolls through raw text files by hand. With KQL, the same question becomes a precise, repeatable query that you can rerun at the next incident.
Core Principles
Each step in a KQL query is separated by a pipe character and passes its result to the next step, so you can read a query from top to bottom and know exactly what is happening to the data. The usual shape is a table, then filters, then a reshape or summary, then a sort.
filter rows]:::tool W --> S[summarize
count and group]:::tool S --> O[order by
sort results]:::tool O --> R[(Answer)]:::ok classDef src fill:#DBEAFE,color:#1E293B classDef tool fill:#326CE5,color:#FFFFFF classDef ok fill:#10B981,color:#FFFFFF
Before you can query anything, the data has to arrive. The Azure Monitor Agent on the VM collects what a data collection rule (DCR) tells it to collect and sends it to the workspace, where each kind of log lands in its own table such as Heartbeat or Syslog.
Azure Monitor Agent]:::tool --> DCR[Data collection rule]:::soft DCR --> LAW[(Log Analytics
workspace)]:::cloud LAW --> KQL([KQL query]):::ok classDef tool fill:#326CE5,color:#FFFFFF classDef soft fill:#FFEDD5,color:#1E293B classDef cloud fill:#EDE9FE,color:#1E293B classDef ok fill:#10B981,color:#FFFFFF
Detailed Step-by-Step Practical Lab
- Create a resource group and a Log Analytics Workspace, and save the workspace ID for later queries:
az group create --name rg-kql-lab-central --location centralindia az monitor log-analytics workspace create \ --resource-group rg-kql-lab-central \ --workspace-name law-kql-lab WORKSPACE_ID=$(az monitor log-analytics workspace show \ --resource-group rg-kql-lab-central \ --workspace-name law-kql-lab \ --query customerId --output tsv)- Create a VM, give it a system-assigned identity, and install the Azure Monitor Agent:
az vm create \ --resource-group rg-kql-lab-central \ --name vm-kql-lab \ --image Ubuntu2204 \ --size Standard_B1s \ --admin-username azureadmin \ --generate-ssh-keys az vm identity assign \ --resource-group rg-kql-lab-central \ --name vm-kql-lab az vm extension set \ --resource-group rg-kql-lab-central \ --vm-name vm-kql-lab \ --name AzureMonitorLinuxAgent \ --publisher Microsoft.Azure.Monitor \ --enable-auto-upgrade true- Create a data collection rule that sends Syslog to the workspace and attach it to the VM. The portal is the most reliable route for this step:
Portal: Monitor -> Data Collection Rules -> Create Name: dcr-syslog-lab Resource group: rg-kql-lab-central Region: Central India Platform type: Linux Resources: add vm-kql-lab Collect and deliver -> Add data source -> Linux Syslog Set LOG_USER, LOG_AUTH and LOG_DAEMON to minimum level LOG_WARNING Destination: Azure Monitor Logs -> law-kql-lab- Write a few log lines on the VM that imitate a checkout service, some failing and some healthy:
az vm run-command invoke \ --resource-group rg-kql-lab-central \ --name vm-kql-lab \ --command-id RunShellScript \ --scripts 'for i in 1 2 3 4 5; do logger -p user.err -t checkout-service "payment-gateway timeout order=ORD-4821$i"donelogger -p user.warning -t checkout-service "slow response 2400ms order=ORD-48219"'- Wait about 10 minutes for the first logs to arrive. Then run the simplest query, a preview of recent heartbeats. You can paste queries into the workspace's Logs page, or run them with the CLI:
az extension add --name log-analytics az monitor log-analytics query \ --workspace "$WORKSPACE_ID" \ --analytics-query "Heartbeat | take 10" \ --timespan PT1H --output table- Narrow to a time range and one computer with
where:
Heartbeat| where TimeGenerated > ago(1h)| where Computer == "vm-kql-lab"- Keep only the columns that matter with
project:
Heartbeat| where TimeGenerated > ago(1h)| project TimeGenerated, Computer, OSType- Count heartbeats per 10-minute bucket to spot gaps in reporting. The
bin()function groups timestamps into fixed buckets, which is the standard KQL pattern for any time series:
Heartbeat| where TimeGenerated > ago(24h)| summarize Beats = count() by bin(TimeGenerated, 10m)| order by TimeGenerated asc- Find the failing service. Filter on severity instead of searching for the word "error", then group by process to see which one is noisy:
Syslog| where TimeGenerated > ago(6h)| where SeverityLevel in ("err", "crit", "alert", "emerg")| summarize Errors = count() by ProcessName| order by Errors desc- Look at the actual messages, newest first, and add a computed column with
extend:
Syslog| where TimeGenerated > ago(6h)| where ProcessName == "checkout-service" and SyslogMessage has "timeout"| extend Source = strcat(Computer, "/", ProcessName)| project TimeGenerated, Source, SeverityLevel, SyslogMessage| order by TimeGenerated descIn the portal, add
| render timechartto a summarize-by-time query to see errors per bucket as a chart. Then use Save to keep the query for the next incident.Clean up. The workspace, VM and data collection rule all live in this resource group:
az group delete --name rg-kql-lab-central --yes --no-waitProduction Best Practices & Common Pitfalls
Common MistakeWriting a query with no time filter against a workspace holding months of data. It runs slowly, returns far more rows than you can use, and can hit the result limit of 30,000 rows. Start every query with a
where TimeGenerated > ago(...)filter before adding anything else.
TipBuild queries incrementally. Start with
take 10to see the raw columns, then add onewherefilter at a time and check the results after each, instead of writing the final query in one attempt.
RememberTime filters also affect cost on some log tiers. Queries on Basic Logs and archived data are billed by the amount of data scanned, so a narrow time range is cheaper as well as faster.
- Use
summarizeto turn rows into answers. "How many", "average of what" and "grouped by which field" are summarize questions, whilewhereonly narrows which raw rows you see. - Prefer
hasovercontainsfor whole words.hasmatches indexed terms and runs faster, whilecontainsscans for substrings and is slower on large tables. - Filter on structured fields first. Conditions on
SeverityLevel,ProcessNameorComputerare faster and more precise than text searches on the message. - Save and share queries. A saved query for "errors in the last hour for this service" turns a repeatable investigation into one click for the whole team.
- Collect only what you need. Sending every facility at every level into the workspace raises ingestion cost, so set minimum levels deliberately in the data collection rule.
Quick Reference & Troubleshooting Commands
| KQL Operator | Description |
|---|---|
where |
Filter rows based on a condition |
project |
Select specific columns |
extend |
Add a computed column |
summarize |
Aggregate rows with count, average and more |
bin(TimeGenerated, 1h) |
Group timestamps into fixed time buckets |
order by |
Sort results |
take N |
Return only N rows for a quick preview |
ago(1h) |
A relative time meaning one hour ago |