KQL for operations: parse logs and log search alerts

Azure log search alerts run a KQL query on a schedule and let you know when the result meets a condition. They pick up things metrics can’t, like a pattern in an app’s log lines, a sudden burst of failed sign-ins, or a server that has stopped sending heartbeats.

Real logs are messy text. Before you can alert on them you need to pull the fields out of lines like “ERROR payment-api order=1002 user=ravi”, and that’s the job of parse, extract and parse_json.

You’ll parse an app log and then build a log search alert for missing heartbeats. Each of these can fail quietly and hide a real problem, and you’ll fix both.

TimeYou needCostBy the end you can
About 50 minuteslaw-saat from Lesson 32, ag-saat-email from Lesson 31, the CLI and the portalA few US cents: one log search alert rule checking every 5 minutes for under an hourParse text and JSON logs with KQL, and build log search alerts that don’t miss failures

What it is, in one line

A log search alert runs a KQL query every few minutes and fires when the results meet the condition you set.

In Simple Words

Reading the school’s complaint slips

Parents drop handwritten slips into a box, things like “Class 4, Monday, bus late 20 minutes”. If you want to count late buses per route, somebody has to read every slip and copy the route and the minutes into columns, and that’s parsing. A teacher who checks the box each morning and phones the transport office when three slips mention the same route is your log search alert.

But a slip written in a different order gets skipped, and a teacher who only reads today’s slips will never notice a bus that stopped coming last week. Those are today’s two breaks.

Engineer's View

Parsing tools and log search alert settings

  • parse: you give it a pattern of fixed text and column names. It’s quick and easy to read, but when a line doesn’t match, all the new columns come out empty. parse-where drops the lines that don’t match instead.
  • extract(): one regular expression per field, so one odd field doesn’t spoil the others. Use verbatim strings like @'user=(\S+)'.
  • parse_json(): use it on JSON lines, then read the fields as j.level and convert them with tostring(), toint() and the like.
  • Log search alert rule: a scope (a workspace or resources), a KQL query, a measure (row count or a column), an operator and threshold, a window size (how far back the query looks, up to 2 days), a frequency (how often it runs), a severity and action groups.
  • Dimensions: you can split one rule by a column like Computer, so each server fires its own alert.
  • Cost: you’re billed per rule and by frequency, and 1-minute checks cost more. Stateful rules resolve by themselves once the condition clears.

How it works, step by step

Here’s what a log search alert does every 5 minutes:

Azure log search alerts: what happens on every scheduled run
  1. Azure Monitor runs your KQL query against the workspace, but only over the window size (say, the last hour).
  2. It measures the result, which is usually the number of rows.
  3. It compares that number with your threshold, something like “greater than 0”.
  4. If it matches for as many evaluations as you asked for, the alert fires and calls the action group.
  5. Once later runs stop matching, the alert resolves.

Heartbeat alerts go wrong at step 1. A server that’s been silent for longer than the window has no rows at all, so “LastSeen older than 10 minutes” can never be true for it.

Azure log search alerts input: parse vs extract vs parse_json

As a rule of thumb, when you alert on the absence of data, compare against a list of what you expect to see and not just against whatever happens to be in the window.

Hands-on lab: parse logs and build Azure log search alerts

Before you run any command, double-check it

Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.

Get the IDs for your workspace and action group, and save the sample app log as a function named AppLog:

$ws = az monitor log-analytics workspace show --resource-group rg-saat-core --name law-saat --query customerId -o tsv
$lawId = az monitor log-analytics workspace show --resource-group rg-saat-core --name law-saat --query id -o tsv
$ag = az monitor action-group show --resource-group rg-saat-core --name ag-saat-email --query id -o tsv
$t = @'
datatable(RawData:string) [
    '2026-10-20T10:01:12Z INFO payment-api order=1001 user=asha ms=120 msg=Paid',
    '2026-10-20T10:02:40Z ERROR payment-api order=1002 user=ravi ms=340 msg=Card declined',
    '2026-10-20T10:03:05Z ERROR payment-api order=1003 user=ravi ms=410 msg=Card declined',
    '2026-10-20T10:04:55Z WARN stock-api order=1004 user=meena ms=900 msg=Slow response',
    '2026-10-20T10:06:30Z ERROR stock-api order=1005 user=asha ms=1500 msg=Timeout calling warehouse',
    '2026-10-20T10:07:10Z INFO payment-api order=1006 user=meena ms=130 msg=Paid',
    '2026-10-20T10:08:45Z ERROR payment-api order=1007 user=ravi ms=380 msg=Card declined',
    '2026-10-20T10:09:59Z ERROR stock-api user=asha ms=1450 msg=Timeout calling warehouse'
]
'@
Set-Content -Path C:\azure-lab\applog.kql -Value $t
az monitor log-analytics workspace saved-search create --resource-group rg-saat-core --workspace-name law-saat --name applog --category saatvedha --display-name AppLog --func-alias AppLog --saved-query '@C:\azure-lab\applog.kql' -o none

Run the KQL steps in the portal, under law-saat, Logs, in KQL mode.

Azure log search alerts lab with the AppLog function in Log Analytics
law-saat Logs in KQL mode, running the AppLog function.

1Parse the log lines into columns

AppLog
| parse RawData with Time:datetime ' ' Level ' ' Service ' order=' Order:long ' user=' User ' ms=' Ms:long ' msg=' Message
| project Time, Level, Service, Order, User, Ms, Message

You should see this (first 3 of 8 rows):

Time                  Level  Service      Order  User  Ms   Message
2026-10-20 10:01:12   INFO   payment-api  1001   asha  120  Paid
2026-10-20 10:02:40   ERROR  payment-api  1002   ravi  340  Card declined
2026-10-20 10:03:05   ERROR  payment-api  1003   ravi  410  Card declined

2Count errors by user and message

AppLog
| parse RawData with Time:datetime ' ' Level ' ' Service ' order=' Order:long ' user=' User ' ms=' Ms:long ' msg=' Message
| where Level == 'ERROR'
| summarize Errors = count() by User, Message
| sort by Errors desc

You should see this:

User  Message                    Errors
ravi  Card declined              3
asha  Timeout calling warehouse  1

Remember that “1” for asha. It’s wrong, and Break It will show you why.

3Parse a JSON log line

datatable(RawData:string) [
    '{"level":"ERROR","service":"stock-api","ms":1500}',
    '{"level":"INFO","service":"payment-api","ms":120}'
]
| extend j = parse_json(RawData)
| project Level = tostring(j.level), Service = tostring(j.service), Ms = toint(j.ms)

You should see this:

Level  Service      Ms
ERROR  stock-api    1500
INFO   payment-api  120

4Create a log search alert for missing heartbeats

This rule runs every 5 minutes, looks back over 1 hour, and fires when any computer’s last heartbeat is more than 10 minutes old:

az monitor scheduled-query create --resource-group rg-saat-core --name al-heartbeat-missing --scopes $lawId --condition "count 'Missing' > 0" --condition-query Missing="Heartbeat | summarize LastSeen = max(TimeGenerated) by Computer | where LastSeen < ago(10m)" --window-size 1h --evaluation-frequency 5m --severity 1 --action-groups $ag --description "A VM stopped sending heartbeats" -o none
az monitor scheduled-query show --resource-group rg-saat-core --name al-heartbeat-missing --query "{enabled:enabled, frequency:evaluationFrequency, window:windowSize, severity:severity}" -o table

You should see this:

Enabled    Frequency    Window    Severity
---------  -----------  --------  ----------
True       PT5M         PT1H      1
Azure log search alerts lab: parsed app log and heartbeat alert rule
Parsed app log lines and the heartbeat alert rule.

✅ Checkpoint: AppLog parses into columns, the JSON line splits into fields, and al-heartbeat-missing is enabled.

Break It, Then Fix It

Neither of these breaks throws an error. Each one gives you a wrong answer that looks right.

1Break it: the line that didn’t parse

After the parse, count all the rows by Service:

AppLog
| parse RawData with Time:datetime ' ' Level ' ' Service ' order=' Order:long ' user=' User ' ms=' Ms:long ' msg=' Message
| summarize Rows = count(), Errors = countif(Level == 'ERROR') by Service

You should see this:

Service      Rows  Errors
payment-api  5     3
stock-api    2     1
             1     0

One row has no service at all. The last log line is missing the “order=” field, so the whole pattern failed and every parsed column stayed empty, Level included. That ERROR line dropped out of the error count, and that’s why asha showed 1 timeout instead of 2.

Fix it: pull out each field with its own regex, so a missing field doesn’t spoil the others:

AppLog
| extend Level = extract(@'Z (\w+) ', 1, RawData),
         User = extract(@'user=(\S+)', 1, RawData),
         Message = extract(@'msg=(.*)', 1, RawData)
| where Level == 'ERROR'
| summarize Errors = count() by User, Message
| sort by Errors desc

You should see this:

User  Message                    Errors
ravi  Card declined              3
asha  Timeout calling warehouse  2

If you have to use parse, put a check like | where isempty(Service) | count on your dashboard so unparsed lines show up instead of disappearing.

2Break it: the heartbeat alert that never fires

web01 and win01 are deallocated, so they’re down, and still no email has come. Run the alert’s query in the portal with the time range set to Last hour:

Heartbeat
| summarize LastSeen = max(TimeGenerated) by Computer
| where LastSeen < ago(10m)

You should see this:

No results found from the last hour

The VMs stopped sending heartbeats days ago, so there are no heartbeat rows for them in the last hour, and a query can’t report a LastSeen that isn’t in its window. The longer a server has been dead, the less chance this alert has of seeing it.

Fix it: compare against the list of computers you expect, and look back the full 2 days:

az monitor scheduled-query update --resource-group rg-saat-core --name al-heartbeat-missing --condition-query Missing="let expected = datatable(Computer:string) ['web01', 'win01']; expected | join kind=leftouter (Heartbeat | summarize LastSeen = max(TimeGenerated) by Computer) on Computer | where isnull(LastSeen) or LastSeen < ago(10m) | project Computer, LastSeen" --window-size 2d -o none

Run the new query in the portal with the time range on Last 48 hours, and you should see something like this:

Computer  LastSeen
web01     2026-10-20 19:24:10
win01     2026-10-20 19:24:40

A computer with no heartbeat at all in 2 days shows an empty LastSeen and still gets counted. Within 5 to 10 minutes, ag-saat-email sends you a “Fired” email. At work you wouldn’t type the expected list in by hand; it comes from a watchlist or Azure Resource Graph.

To clean up, delete the alert so it stops emailing you about your deallocated lab VMs, but keep the functions:

az monitor scheduled-query delete --resource-group rg-saat-core --name al-heartbeat-missing --yes
az monitor scheduled-query list --resource-group rg-saat-core -o tsv

The last command prints nothing.

Azure log search alerts problems: unparsed line and blind heartbeat query
A line that failed to parse, and a heartbeat query that can’t see dead servers.

✅ Checkpoint: You found the unparsed line, counted 2 timeouts for asha, and turned a blind heartbeat alert into one that fires.

This happened at work

The payment errors the dashboard didn’t count

An online retailer’s on-call dashboard counted payment errors by parsing the app’s log lines. After one release the error count fell to almost zero, and the team was pleased with how clean the build looked.

Two days later finance noticed that failed payments had tripled. The new release had added a “trace=” field in the middle of every log line, so the parse pattern stopped matching any of the error lines and each of them landed in an empty row that the dashboard ignored.

What they changed: fields are now pulled out with separate regexes, and the dashboard has a tile that counts lines where parsing failed and alerts above 1%. Developers log errors as JSON so new fields don’t break anything, and any log format change is now on the release checklist.

Common mistakes and troubleshooting

MistakeWhat you seeWhat to do
parse pattern too strictRows with empty columns; counts too lowUse extract() per field or parse-where, and count failures.
Heartbeat alert based on last seen onlyLong-dead servers never alertCompare against an expected list; window up to 2 days.
Window shorter than frequencyEvents between runs are never checkedWindow at least as long as the frequency.
No dimensions on a multi-server ruleOne alert for many servers, details lostSplit by Computer.
1-minute frequency everywhereHigher cost, more noiseUse 5 to 15 minutes unless speed matters.
Alerting on raw text with containsSlow queries, timeoutsUse has, filter time first, parse once.

Interview questions

Click any question to open it. They’re worded the way an interviewer would ask them, and under each one you’ll find why they ask it and one way you could answer in your own words.

Fresher level

1. What is a log search alert?

Why they ask this: To see if you know the basic idea.

How you might answer: It’s an Azure Monitor alert that runs a KQL query against Log Analytics on a schedule, and fires when the result, say the number of rows, crosses a threshold.

2. What does the parse operator do?

Why they ask this: It’s a core KQL tool.

How you might answer: It matches a text column against a pattern of fixed strings and column names, and adds the parts that matched as new columns. Any line that doesn’t match gets empty values.

3. How do you read a field from a JSON log line in KQL?

Why they ask this: It’s something you’ll do all the time.

How you might answer: I’d run parse_json() on the column, then get at the fields with dot or bracket notation and convert them with things like tostring() or toint().

2–5 years experience

4. Your error count dropped after a release. How do you check it’s real?

Why they ask this: They want to see a bit of healthy suspicion.

How you might answer: I’d count the rows where parsing failed or the level column is empty, and compare the total log volume before and after the release. A format change that breaks parsing looks exactly like having fewer errors.

5. How would you alert when a server stops sending data?

Why they ask this: It’s a classic gap and they like to test it.

How you might answer: I’d compare an expected list of servers against the last heartbeat for each one, using a left outer join, and flag the ones that are missing or old. The window has to be long enough, and I’d add Activity log alerts for deallocation as a second signal.

6. What’s the difference between window size and frequency?

Why they ask this: They want to see you understand the timing.

How you might answer: Frequency is how often the query runs, and window size is how far back each run looks. The window should be at least as long as the frequency, otherwise events that happen between runs are never seen.

Senior level

7. How do you make log-based alerting reliable at scale?

Why they ask this: They want to see engineering discipline.

How you might answer: Shared standard parsing functions in the workspace, structured logging from the apps, and dimensions to split by resource. Queries get tested against data we know is there, alerts are deployed as code, and a dashboard tracks parse failures and ingestion gaps.

8. When would you choose a log search alert over a metric alert?

Why they ask this: They want to hear the trade-offs.

How you might answer: For numeric thresholds, metric alerts are quicker and cheaper. Log search alerts are for patterns, joins, text and missing data. Some teams also turn log queries into custom metrics so they get metric-alert speed.

9. How do you reduce alert costs in Log Analytics?

Why they ask this: They’re checking you think about cost.

How you might answer: Use fewer rules with dimensions instead of one rule per resource, pick sensible frequencies, write efficient queries with time filters, and move noisy, low-value detections onto dashboards or reports instead of alerts.

Quick quiz

Q1. What happens to parse columns when a line doesn’t match the pattern?

  1. The query fails
  2. They are empty
  3. The line is deleted from the workspace
  4. They copy the previous row
Show answer

B — Non-matching lines get empty parsed columns.

Q2. Which keeps working when one field is missing from a line?

  1. parse
  2. extract() per field
  3. take
  4. render
Show answer

B — Each extract() is independent.

Q3. A heartbeat alert looks back 1 hour. A server died 3 days ago. Result?

  1. Fires every run
  2. Never fires
  3. Fires once
  4. Deletes the server
Show answer

B — No heartbeat rows exist in the window.

Q4. What is the maximum window size for a log search alert?

  1. 1 hour
  2. 6 hours
  3. 2 days
  4. 30 days
Show answer

C — Log search alerts can look back up to 2 days.

Q5. Which function reads fields from JSON text?

  1. parse_json()
  2. bin()
  3. dcount()
  4. ago()
Show answer

A — parse_json turns JSON text into a dynamic value.

Quick recap

You can now turn messy logs into numbers you can trust, and set up alerts on them that work.

  • parse is fast but fails the whole line on any mismatch.
  • extract() per field survives format changes.
  • parse_json() handles structured logs.
  • Log search alerts: query, measure, threshold, window, frequency.
  • Alert on missing data by comparing with an expected list.

Next lesson

Lesson 35: Azure Backup for VMs → Next, you protect web01 and win01 with Azure Backup, then restore a single file and a whole VM.

Further reading: Azure log search alerts

Want to go deeper into Azure log search alerts? Microsoft’s Types of Azure Monitor alerts and parse operator are good next reads, and the full plan for this course is on the Azure Cloud Administration course page.

Scroll to Top

This website uses cookies

We use a few cookies to keep this site working. If you allow it, we also use Google Analytics to count visits so we can improve our lessons. You can accept all, deny the optional ones, or choose what to allow.