Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 42 of 47
❮Prev Next❯

Query Azure Monitor Logs with KQL

Module 5: Monitor & Backup ⏱ 10 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    30-second answer

    Kusto Query Language (KQL) is how you read logs in a Log Analytics workspace. A query starts with a table (AzureActivity, AzureDiagnostics, StorageBlobLogs, Heartbeat, InsightsMetrics) and pipes rows through operators, top to bottom: where filters, summarize aggregates (count(), avg() by a column or bin(TimeGenerated, 5m)), project picks columns, order by sorts, take limits and render draws a chart. Run it in Logs, then save it, pin it to a dashboard or turn it into a log search alert.

    Simulate it » No Azure account needed

    Exam objective: 5.1.3 Query and analyze logs in Azure Monitor. (Skills measured as of April 17, 2026)

    Simulations

    Feel it before you read it. No account needed, nothing leaves this page.

    Azure portal: Query logs with KQL and pin the result Write a KQL query in Logs and pin the chart.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    Open the Log Analytics workspace and select <strong>Logs</strong>. You can also open Logs from any resource, which scopes the query to that resource.

    👆 Click the glowing item in the portal to continue

    Read the steps as text
    1. Open the Log Analytics workspace and select Logs. You can also open Logs from any resource, which scopes the query to that resource.
    2. Switch to KQL mode and write it top to bottom: the table, where to filter, summarize to count per group, order by to sort. Select Run.
    3. One outside IP is behind almost every failure. Next, see when it happened.
    4. bin(TimeGenerated, 15m) groups rows into 15-minute buckets and render timechart draws them. Pin to a dashboard, or select New alert rule to run this query on a schedule.
    5. Pin it to the shared ops dashboard so the team sees it every morning.
    6. Logs cost money per GB ingested. Usage and estimated costs and Tables let you set retention per table and send noisy tables to a cheaper plan.

    🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.

    😟 THE PROBLEM

    You have 4 GB of logs and one question: what failed, and when?

    😊 THE SOLUTION

    Write a short KQL query: filter, summarize, chart.

    • Scrolling through raw rows✓ where to filter
    • Counting by hand✓ summarize count() by
    • No idea when it started✓ bin() and render timechart
    🛠️ Solved with: KQL in Log Analytics

    Start with a question

    How do you find three late deliveries in a warehouse logbook with 40,000 lines?

    You don’t read every line. You say: only this week, only deliveries marked late, then count them per driver. In a spreadsheet you’d filter one column, then make a pivot table.

    KQL is that habit written down. You name the logbook (a table), then add one step per line: keep the late ones (where), count them per driver (summarize), sort, and draw a chart (render). Log Analytics runs it over millions of rows in seconds.

    Explain it like I’m 10

    The technical explanation

    You run queries in Logs: from a Log Analytics workspace, from Monitor > Logs, or from any resource’s Monitoring > Logs blade (which scopes the query to that resource). Switch the editor to KQL mode for full queries. The time range picker applies unless the query has its own TimeGenerated filter.

    The shape of a query

    StorageBlobLogs                                   // 1. start with a table
    | where TimeGenerated > ago(24h)                  // 2. filter early (time first)
    | where StatusCode >= 400
    | summarize Failures = count() by OperationName, CallerIpAddress
    | order by Failures desc
    | take 10

    Each line takes the rows from the line above. Read it out loud and you’ll know what it does.

    Operators you’ll use every week

    OperatorDoesExample
    whereKeeps matching rowswhere ResultType != "Success"
    summarizeGroups and aggregatessummarize count(), avg(DurationMs) by bin(TimeGenerated, 5m)
    projectPicks or renames columnsproject TimeGenerated, Caller, ResourceGroup
    extendAdds a calculated columnextend SizeMB = Size / 1048576
    order by / sort bySortsorder by TimeGenerated desc
    take / limit, topLimits rowstop 10 by Failures
    distinctUnique valuesdistinct Computer
    joinCombines two tables on a keyjoin kind=inner (Heartbeat) on Computer
    renderDraws a chartrender timechart

    Useful comparisons: == (case-sensitive), =~ (case-insensitive), !=, has (whole-word match, fast), contains (any substring, slower), in ("a","b"), between (a .. b). Time helpers: ago(1h), now(), bin(TimeGenerated, 1h). Aggregates: count(), dcount(), avg(), max(), min(), sum(), percentile(x, 95), arg_max(TimeGenerated, *).

    Admin tables worth knowing

    TableComes fromTypical question
    AzureActivityActivity log exported with a subscription diagnostic settingWho deleted resources last week?
    AzureDiagnosticsResource logs in Azure diagnostics mode (Key Vault, many PaaS services)Who got secrets from the vault?
    StorageBlobLogsBlob service diagnostic setting (resource-specific)Which IP keeps getting 403?
    HeartbeatAzure Monitor AgentWhich VMs went silent?
    Perf, InsightsMetricsAMA data collection rules, VM insightsWhich VM is short of memory?
    Event, SyslogAMA data collection rulesWhich Windows service crashed?
    AzureMetricsMetrics sent through a diagnostic settingLong-term metric history

    If a table is empty, it’s usually not a query problem: nothing is sending data there yet.

    Queries an admin actually writes

    // Who deleted things in the last 7 days?
    AzureActivity
    | where TimeGenerated > ago(7d)
    | where OperationNameValue endswith "DELETE" and ActivityStatusValue == "Success"
    | project TimeGenerated, Caller, ResourceGroup, _ResourceId
    
    // VMs that stopped reporting
    Heartbeat
    | summarize LastSeen = max(TimeGenerated) by Computer
    | where LastSeen < ago(15m)
    
    // Failed blob requests per 15 minutes, as a chart
    StorageBlobLogs
    | where StatusCode >= 400
    | summarize count() by bin(TimeGenerated, 15m)
    | render timechart

    From the CLI, az monitor log-analytics query runs the same text (PowerShell: Invoke-AzOperationalInsightsQuery):

    az monitor log-analytics query -w <workspace GUID> \
      --analytics-query "StorageBlobLogs | where StatusCode >= 400 | summarize count() by OperationName" \
      -t P1D

    From query to action

    In the Logs toolbar you can Save a query (to a query pack), Share a link, Export to CSV or Power BI, Pin to a dashboard or workbook, or select New alert rule. A log search alert runs the query on a schedule (for example every 5 minutes over the last 15) and fires when the number of rows or an aggregated value crosses a threshold, then calls an action group.

    Architect level Query scope, cost and speed

    A query run from a resource’s Logs blade is resource-context: it only sees rows for that resource, even in a shared workspace. That’s how people with access to one VM can query only its data, depending on the workspace access mode. From the workspace, you see everything you have rights to.

    Queries on Analytics tables don’t cost extra; you pay for ingestion and retention. Basic and Auxiliary table plans are cheaper to ingest but charge per GB scanned and support a limited set of operators. Keep queries fast by filtering on TimeGenerated first, using has over contains, and projecting only the columns you need before a join.

    Real-world business scenario

    Logistics

    Fabrikam Logistics (fictional)

    The problem
    Every Monday someone asked which VMs had gone silent over the weekend and who had changed what. An admin spent the morning clicking through activity logs and VM blades.
    What they used
    The activity log and the Azure Monitor Agent sent data to one Log Analytics workspace. The team saved three KQL queries (silent VMs from Heartbeat, deletes from AzureActivity, top failing storage callers from StorageBlobLogs), pinned them to a shared dashboard and turned the Heartbeat query into a log search alert.
    Why that choice
    One query answered in seconds what had taken hours, and the alert caught silent VMs on Saturday instead of Monday.
    The result
    The Monday check went from about two hours to a five-minute look at the dashboard.

    When to use it and when not to

    ✓ Use it when…

    • You need to answer who, what and when across many log records.
    • You want a chart or a table you can pin, share or export.
    • You want an alert on a pattern in logs rather than a single metric value.

    ✕ Think twice when…

    • Simple threshold alerts on one number such as CPU. A metric alert is faster and cheaper.
    • Questions about data that never reaches the workspace. Fix the diagnostic setting or agent first.
    • Changing data. KQL only reads; it can't update or delete rows.

    ↔ Alternatives to consider

    • Metrics explorer for quick charts of platform metrics.
    • Workbooks to combine several queries and metrics into an interactive report.
    • Azure Resource Graph (also KQL) to query resource configuration across subscriptions.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    Test yourself with exercises

    5 original practice questions in the AZ-104 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.

    Question 1

    Question 1 of 5

    You need to return only the failed blob requests from the StorageBlobLogs table. Which KQL operator should you use after the table name?

    Question 2

    Question 2 of 5

    You need to display the number of failed requests in 15-minute intervals as a line chart. Which query should you run?

    Question 3

    Question 3 of 5

    You must identify the users who deleted Azure resources during the last seven days. The activity log is exported to a Log Analytics workspace. Which table should you query?

    Question 4

    Question 4 of 5

    You run the following query: Heartbeat | summarize LastSeen = max(TimeGenerated) by Computer | where LastSeen < ago(15m). What does the query return?

    Question 5

    Question 5 of 5

    You write a KQL query that returns the top failing callers of a storage account. You need to be notified when the query returns results, and the query must run every 10 minutes. What should you create?

    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 does a KQL query flow?

    Model answer

    Top to bottom, like a pipeline. You start with a table, then each line after a pipe takes the rows from the line above and does one thing to them: filter, group, pick columns, sort, chart. Reading it out loud usually tells you what it does.

    Intermediate How would you find which VMs stopped sending heartbeats in the last 15 minutes?

    Model answer

    Heartbeat, summarize the latest TimeGenerated by Computer with max(), then where that last heartbeat is older than ago(15m). That gives one row per silent machine, and I can save it as a log search alert.

    Experienced developer Why put where before summarize?

    Model answer

    Filtering first means fewer rows to group, so the query is faster and cheaper, especially with a time filter on TimeGenerated. It also stops you counting rows you didn't mean to. The same goes for using has instead of contains on big string columns.

    Scenario Your manager asks who deleted resources in the production subscription last week. What do you run?

    Model answer

    If the activity log is exported to a workspace I'd query AzureActivity, where OperationNameValue ends with DELETE and ActivityStatusValue is Success, over the last 7 days, and project the time, Caller, ResourceGroup and the resource. If it isn't exported, I'd use the Activity log blade with a Delete filter, which covers the last 90 days.

    Quick revision

    Key points

    • A query starts with a table and pipes rows through operators, top to bottom.
    • where filters, summarize groups and aggregates, project picks columns, order by sorts, take limits, render charts.
    • bin(TimeGenerated, 5m) buckets time for charts; ago(1h) gives a time to filter on.
    • Admin tables to know - AzureActivity, AzureDiagnostics, resource-specific tables like StorageBlobLogs, Heartbeat, Perf, InsightsMetrics, Event, Syslog.
    • Queries can be saved, pinned, exported and turned into log search alerts.

    Important terminology

    KQL
    Kusto Query Language, the read-only query language for Azure Monitor Logs, Azure Data Explorer and Microsoft Sentinel.
    Log Analytics workspace
    The Azure resource that stores logs in tables and runs KQL queries against them.
    where
    Keeps only rows that match a condition, such as where StatusCode >= 400.
    summarize
    Groups rows and calculates aggregates such as count(), avg(), max() or dcount() by one or more columns.
    bin()
    Rounds values into buckets, most often time, as in bin(TimeGenerated, 5m).
    project
    Chooses, renames or orders the columns you want in the result.
    render
    Draws the result as a chart such as timechart, barchart or piechart.
    Log search alert
    An alert rule that runs a KQL query on a schedule and fires when the result meets a condition.

    Common mistakes

    • Putting the table name after the first pipe. The table always comes first.
    • Using SQL habits such as SELECT or WHERE x = 'y'. KQL uses project and ==.
    • Querying a table that's empty because no diagnostic setting or agent sends data to it.

    Exam tips

    • "Count per 5 minutes and chart it" = summarize count() by bin(TimeGenerated, 5m) | render timechart.
    • "Show only some columns" = project. "Top 10" = top 10 by or order by … | take 10.
    • Equality is ==. Case-insensitive equality is =~.

    Five quick revision questions

    1. 1.Which operator filters rows?Show

      where.

    2. 2.Which operator groups rows and counts them?Show

      summarize (with count()).

    3. 3.How do you group events into 15-minute buckets?Show

      bin(TimeGenerated, 15m).

    4. 4.Which table holds exported activity log events?Show

      AzureActivity.

    5. 5.How do you run a KQL query on a schedule and get notified?Show

      Create a log search alert rule.

    Official references

    Finished this lesson? Tick it off. Your progress is saved in this browser.

    Next up: Alert Rules, Action Groups and Alert Processing Rules

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.