Your profile

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

Lesson 28 of 28

KQL Queries for Logs and Metrics

Module 4: Secure & Monitor ⏱ 11 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) 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.

    Simulate it » No Azure account needed

    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.

    Azure portal: Query logs with KQL and alert on the result Run KQL in Logs and turn it into an alert.
    </> Embed

    Embed this simulation

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

    Loading the portal…

    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
    1. Open Logs in the workspace and switch to KQL mode. Each | passes rows to the next step: filter, group, chart.
    2. A spike at 09:15. You don’t want to find the next one by luck, so select + New alert rule.
    3. The query becomes the condition: every 5 minutes, alert if failures are greater than 10.
    4. An action group says who hears about it and how. Reuse one across many alerts.
    5. Give it a clear name and a severity. The name is what lands in someone’s inbox.
    6. Review and Create. Log search alerts are billed per rule, a few dollars a month at most.
    7. 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.

    😟 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
    🛠️ Solved with: KQL

    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:

    DataApplication Insights (classic names)Log Analytics workspace
    Incoming requestsrequests (timestamp, name, success, duration, resultCode)AppRequests (TimeGenerated, Name, Success, DurationMs, ResultCode)
    Outgoing callsdependenciesAppDependencies
    ExceptionsexceptionsAppExceptions
    Log messagestracesAppTraces
    Custom metricscustomMetricsAppMetrics
    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.

    OperatorDoesExample
    whereKeeps matching rowswhere timestamp > ago(1h) and success == false
    projectPicks (and renames) columnsproject timestamp, name, duration
    extendAdds a calculated columnextend seconds = duration / 1000
    summarizeGroups and aggregatessummarize count(), avg(duration) by name
    bin()Buckets numbers or timeby bin(timestamp, 5m)
    top / sort by / takeOrders and limitstop 10 by duration desc
    joinCombines two tablesjoin kind=inner (exceptions) on operation_Id
    renderDraws a chartrender 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. 1 Table

      requests: every incoming call.

    2. 2 where

      Last 24 hours, failed only.

    3. 3 summarize

      Count per 5-minute bin.

    4. 4 render

      A timechart you can pin or alert on.

    How one query narrows the data

    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 alertLog search alert
    WatchesA platform or custom metricThe result of a KQL query
    EvaluatedAbout every minuteOn a schedule you set (for example every 5 minutes over the last 15)
    Good forCPU over 80%, queue length over 1,000Failure rate per endpoint, a specific exception text, a pattern across tables
    CostLowerHigher, 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

    Online retail

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

    Question 1

    Question 1 of 5

    You need a KQL query that shows the number of failed requests in each 5-minute interval during the last 24 hours as a line chart in Application Insights. Which query should you use?

    Question 2

    Question 2 of 5

    You must list failed requests together with the exception message that each request produced. Both tables are in the same Application Insights resource. Which column should you use to join the requests table to the exceptions table?

    Question 3

    Question 3 of 5

    Application Insights is workspace-based. A developer runs the following query directly in the Log Analytics workspace: requests | where timestamp > ago(1h) | summarize avg(duration). The query fails because the table cannot be found.

    Which table and time column should the developer use in the workspace?

    Question 4

    Question 4 of 5

    You need to identify the 10 operations with the highest 95th percentile duration during the last hour. Which KQL statement should you add after requests | where timestamp > ago(1h)?

    Question 5

    Question 5 of 5

    You need to be notified when more than 5 percent of requests to the /ask endpoint fail within 10 minutes. The failure rate must be calculated from request telemetry by using a query. Which type of alert rule 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 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. 1.Which operator adds a calculated column?Show

      extend.

    2. 2.Which function returns the time 24 hours ago?Show

      ago(24h).

    3. 3.Which table holds outgoing calls in classic Application Insights?Show

      dependencies.

    4. 4.Which table holds Container Apps console output?Show

      ContainerAppConsoleLogs_CL.

    5. 5.Which operator keeps only some columns?Show

      project.

    Official references

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

    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.