Skip to main content

Querying Logs with Kusto Query Language (KQL)

Learn the basic KQL syntax needed to search, filter, and summarize logs in a Log Analytics Workspace to actually find an incident's root cause.

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 where and ago()
  • Picking columns with project and adding columns with extend
  • Counting and grouping with summarize and bin()
  • 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.

flowchart TD T([Table: Syslog]):::src --> W[where
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.

flowchart TD VM[VM with
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

  1. Create a resource group and a Log Analytics Workspace, and save the workspace ID for later queries:
Bash
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)
  1. Create a VM, give it a system-assigned identity, and install the Azure Monitor Agent:
Bash
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
  1. 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:
â—ˆ DIAGRAM
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
  1. Write a few log lines on the VM that imitate a checkout service, some failing and some healthy:
Bash
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"
done
logger -p user.warning -t checkout-service "slow response 2400ms order=ORD-48219"
'
  1. 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:
Bash
az extension add --name log-analytics
az monitor log-analytics query \
--workspace "$WORKSPACE_ID" \
--analytics-query "Heartbeat | take 10" \
--timespan PT1H --output table
  1. Narrow to a time range and one computer with where:
TEXT
Heartbeat
| where TimeGenerated > ago(1h)
| where Computer == "vm-kql-lab"
  1. Keep only the columns that matter with project:
TEXT
Heartbeat
| where TimeGenerated > ago(1h)
| project TimeGenerated, Computer, OSType
  1. 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:
TEXT
Heartbeat
| where TimeGenerated > ago(24h)
| summarize Beats = count() by bin(TimeGenerated, 10m)
| order by TimeGenerated asc
  1. Find the failing service. Filter on severity instead of searching for the word "error", then group by process to see which one is noisy:
TEXT
Syslog
| where TimeGenerated > ago(6h)
| where SeverityLevel in ("err", "crit", "alert", "emerg")
| summarize Errors = count() by ProcessName
| order by Errors desc
  1. Look at the actual messages, newest first, and add a computed column with extend:
TEXT
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 desc
  1. In the portal, add | render timechart to a summarize-by-time query to see errors per bucket as a chart. Then use Save to keep the query for the next incident.

  2. Clean up. The workspace, VM and data collection rule all live in this resource group:

Bash
az group delete --name rg-kql-lab-central --yes --no-wait

Production Best Practices & Common Pitfalls

Common Mistake

Writing 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.

Tip

Build queries incrementally. Start with take 10 to see the raw columns, then add one where filter at a time and check the results after each, instead of writing the final query in one attempt.

Remember

Time 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 summarize to turn rows into answers. "How many", "average of what" and "grouped by which field" are summarize questions, while where only narrows which raw rows you see.
  • Prefer has over contains for whole words. has matches indexed terms and runs faster, while contains scans for substrings and is slower on large tables.
  • Filter on structured fields first. Conditions on SeverityLevel, ProcessName or Computer are 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

Explore More in Azure Monitoring, Identity, and Production Readiness

All 6 Topics

Frequently Asked Questions

Is Querying Logs with Kusto Query Language (KQL) free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Querying Logs with Kusto Query Language (KQL) topic cover?

Learn the basic KQL syntax needed to search, filter, and summarize logs in a Log Analytics Workspace to actually find an incident's root cause.

Found a mistake, an outdated step or a broken link?