Dashboard Part 1 Monitor & Manage
⚙️ Part 1 · Topic 4 of 5

Monitor & Manage Azure AI Services

Once your Azure AI service is deployed and secured, you need to keep it healthy, understand how it's being used, catch problems early, and keep costs under control. This topic covers Azure Monitor, Application Insights, diagnostic logs, KQL queries, alert rules, and cost management.

🐍 Python examples included ☁️ Portal walkthroughs included ⏱️ ~45 min read Prerequisites: T1, T2, T3
🔗
Building on Previous Topics

This topic uses: resource, resource group, subscription, endpoint, API key, managed identity, and environment variable from Topics 1–3. New concepts — Azure Monitor, KQL, diagnostic settings — are all introduced before they appear in any code or walkthrough.

Monitoring terms you must know

Azure Monitor

Microsoft's central monitoring platform for all Azure resources. It collects metrics (numbers that measure performance) and logs (records of events that happened). Think of it as the health dashboard for your entire Azure environment.

Metric

A numeric measurement collected at regular intervals. Examples for AI services: total API calls per minute, average response latency in milliseconds, number of errors per hour. Metrics are great for spotting trends and triggering alerts.

Log

A detailed record of something that happened — who called the service, what they requested, what the response was, did it succeed or fail. Logs give you the "why" behind what metrics show. More detailed than metrics but also larger to store.

Application Insights

An Azure Monitor feature specifically designed for monitoring applications. It tracks performance, usage patterns, exceptions, and custom events. Unlike basic Azure Monitor metrics, it can track what happens inside your Python application code — not just at the infrastructure level.

Diagnostic Settings

A configuration on an Azure resource that tells Azure Monitor where to send the resource's logs and metrics. You choose what to capture (audit logs, request logs, metrics) and where to send it (Log Analytics workspace, Storage Account, or Event Hub).

Log Analytics Workspace

A storage and query service for logs. Once you route your Azure AI service logs here via diagnostic settings, you can search and analyse them using KQL (Kusto Query Language). Think of it as a database specifically for Azure logs.

KQL — Kusto Query Language

The query language used to search and analyse data in a Log Analytics workspace. Similar to SQL but designed for log data. You write a query that says what table to look in, what to filter by, and how to summarise the results.

Alert Rule

A rule that watches a metric or log condition and triggers a notification when the condition is met. For example: "Alert me if error rate exceeds 5% in any 5-minute window." Alert rules can trigger emails, SMS, webhooks, or automated actions via Logic Apps or Azure Functions.

Action Group

A collection of notification targets that get triggered when an alert fires. An action group might contain: send email to the on-call engineer, send an SMS, and call a webhook to create a ServiceNow incident. You reuse one action group across multiple alert rules.

Pricing Tier (in cost context)

From Topic 2 you know F0 is free and S0 is paid. In cost management, you also need to know that S0 charges per API call (pay-as-you-go). Understanding your call volume helps forecast costs. Azure Cost Management helps you set budgets and alerts.

Budget (Azure Cost Management)

A spending limit you set in Azure Cost Management. You define a monthly spend threshold (e.g. $100/month) and Azure sends you alerts when you reach 80%, 90%, or 100% of that budget. It does NOT automatically stop services — it only sends notifications.

Retention Period

How long logs are kept before being deleted. In Log Analytics, the default retention is 30 days. You can extend it (up to 730 days, at extra cost). For compliance, some organisations must retain logs for 90 days or more — this affects your Log Analytics configuration.

How Azure Monitor works for AI services

🏥
Analogy — A hospital patient monitoring system

Imagine a patient in a hospital hooked up to monitors. The monitors constantly measure vitals — heart rate, blood pressure, oxygen — these are metrics. The medical chart records every event — "patient complained of chest pain at 14:32, given medication at 14:35" — these are logs. The alarm on the monitor goes off if heart rate goes above 120 — that's an alert rule. The nurse is paged automatically — that's an action group.

Azure Monitor does exactly the same for your AI service.

The monitoring data flow

1
Your Azure AI Service generates data

Every API call your service handles produces data — how long it took, whether it succeeded, how many tokens were used. This data is captured automatically by Azure at the platform level.

2
Azure Monitor collects it

Azure Monitor sits in the middle, collecting both metrics (numeric measurements) and logs (event records) from your resource. This happens automatically for metrics — logs require you to configure diagnostic settings (covered in Section 4).

3
You view metrics in Metrics Explorer

In the Azure portal → your resource → Metrics, you can chart any metric over time — calls, errors, latency — and see trends.

4
Logs go to Log Analytics for deep analysis

Detailed logs are routed to a Log Analytics workspace where you can write KQL queries to search, filter, and aggregate them.

5
Alert rules watch for problems and notify you

Alert rules monitor metrics or log query results 24/7. When a threshold is crossed, they trigger an action group that notifies the right people or systems.

The metrics you can track

Azure AI services automatically emit these metrics to Azure Monitor. No configuration needed — they appear as soon as your resource exists. You view them in the Azure portal → your resource → Metrics.

Total Calls

The total number of API calls made to your service in a time period. Use this to understand usage volume and growth trends.

e.g. 45,230 calls in the last hour
Successful Calls

Calls that returned an HTTP 2xx response — the service processed the request successfully. Compare against Total Calls to calculate success rate.

e.g. 45,180 successful / 45,230 total = 99.9%
Total Errors

The number of calls that failed. A spike here usually means your app has a bug, the service is misconfigured, or you're hitting a rate limit.

e.g. 50 errors in the last hour
Server Errors

HTTP 5xx errors — the service itself failed, not your request. These are Azure-side problems. If you see these, check Azure Service Health for incidents.

e.g. HTTP 503 Service Unavailable
Client Errors

HTTP 4xx errors — your request was wrong. Common causes: invalid API key (401), bad request format (400), rate limit exceeded (429).

e.g. HTTP 429 Too Many Requests
Latency

How long the service takes to respond, in milliseconds. High latency means slow responses for your users. Usually shown as average, P95, or P99 percentile.

e.g. avg 245ms, P99 1200ms
Data In

Total bytes sent TO the service. Useful for billing analysis — some services charge based on the amount of data processed.

e.g. 2.3 GB sent in the last day
Data Out

Total bytes returned FROM the service. Responses — especially from language models — can be large. Monitor this for unexpected cost spikes.

e.g. 8.1 GB received in the last day

How to view metrics in the Azure portal

1
Go to your Azure AI resource

portal.azure.com → search for your resource → click it to open

2
Click Metrics in the left menu

Under the Monitoring section. This opens the Metrics Explorer.

3
Select a metric to chart

Click + Add metric → choose from the list (e.g. Total Calls) → choose aggregation (Sum, Average, Max) → the chart appears. You can add multiple metrics to the same chart.

4
Adjust the time range

Use the time picker (top right) to view metrics for Last 1 hour, Last 24 hours, Last 7 days, or a custom range.

Monitoring what happens inside your application

Azure Monitor metrics show you what's happening at the service level — how many calls, how fast. Application Insights goes deeper — it shows you what's happening inside your Python application: which functions are slow, which exceptions are being thrown, how users are flowing through your app.

💡
Azure Monitor vs Application Insights — The Difference

Azure Monitor watches the AI service itself — total calls, latency, errors reported by Azure. It answers: "Is the service healthy?"

Application Insights watches your application code — exceptions, custom events, end-to-end request tracking. It answers: "Is my app using the service correctly and efficiently?"

On the exam, if the scenario mentions monitoring an application or tracking custom events, the answer is Application Insights. If it's about monitoring the Azure resource itself, the answer is Azure Monitor.

Adding Application Insights to your Python app

A new Python concept here: with statement (context manager). It is used by the Application Insights SDK to track operations. It is explained fully in the code comments.
Install with: pip install azure-monitor-opentelemetry

# Install first: pip install azure-monitor-opentelemetry

# This library instruments your Python app to send telemetry to Application Insights
from azure.monitor.opentelemetry import configure_azure_monitor

import os
from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential


# ── Step 1: Set up Application Insights ──────────────────────────────

# Your Application Insights connection string
# Found in: Azure portal → Application Insights resource → Overview → Connection String
# Format: InstrumentationKey=xxx;IngestionEndpoint=https://...;LiveEndpoint=https://...
connection_string = os.environ.get("APPLICATIONINSIGHTS_CONNECTION_STRING")

# configure_azure_monitor() sets up automatic telemetry collection
# After this line, Python exceptions, HTTP calls, and performance data
# are automatically sent to Application Insights — no extra code needed
configure_azure_monitor(connection_string=connection_string)


# ── Step 2: Use your AI service normally — telemetry is collected auto ─

key      = os.environ.get("LANGUAGE_KEY")
endpoint = os.environ.get("LANGUAGE_ENDPOINT")
client   = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))

# This call is now automatically tracked by Application Insights
# Duration, success/failure, and any exceptions are recorded
result = client.analyze_sentiment(documents=["Azure AI is excellent!"])

print(f"Sentiment: {result[0].sentiment}")
# Application Insights receives: duration of this call, success=True, HTTP status


# ── Step 3: Add a custom event (optional but powerful) ────────────────

# New concept: "from X import Y" — importing a specific class from a library
from opentelemetry import trace

# Get the tracer — this lets us create custom tracking spans
# A span is a named unit of work that gets recorded in Application Insights
tracer = trace.get_tracer(__name__)

# "with" statement — new Python concept explained:
# "with tracer.start_as_current_span(...) as span:" means:
#   "Start tracking a named operation called 'sentiment-analysis-batch'
#    and call it 'span' inside this block"
# Everything inside the indented block is timed and recorded as one unit
# When the block finishes (or if an error occurs), the span is automatically closed
with tracer.start_as_current_span("sentiment-analysis-batch") as span:

    # Add custom attributes to this span — extra information to record
    span.set_attribute("document.count", 3)   # How many documents we're analysing
    span.set_attribute("batch.type", "sentiment")  # What type of analysis

    # The actual AI call happens inside the "with" block
    # so Application Insights knows it's part of this named operation
    docs = ["Great service!", "Terrible experience.", "It was okay."]
    results = client.analyze_sentiment(documents=docs)

    # New concept: for loop — runs the indented block once for each item in a list
    # "for doc in results" means: take each item from results, call it "doc", run the block
    for doc in results:
        print(f"  Sentiment: {doc.sentiment} | Score: {doc.confidence_scores}")

# After the "with" block: Application Insights records the complete span
# including duration, custom attributes, and any exceptions that occurred

Routing logs to the right destination

By default, Azure AI service logs are not stored anywhere — they are generated and discarded. To keep them for analysis, you must configure diagnostic settings to route them to a destination.

Three log destinations

📋
Log Analytics Workspace

Best for analysis and querying. Logs are stored in a structured database you can query with KQL. You can write dashboards, alert rules, and complex queries. This is the most common destination for operational analysis.

Recommended for querying
🗄️
Azure Storage Account

Best for long-term archival. Logs are stored as JSON files in Blob Storage. Cheaper than Log Analytics for long retention periods. Not easy to query directly — use this for compliance archiving where you need logs kept for years.

Best for archiving
📡
Azure Event Hub

Best for streaming to external systems. Logs are streamed in real time to Event Hub, where external systems (like Splunk, Datadog, or your own SIEM) can consume them. Use when you already have a non-Azure monitoring platform.

Best for external SIEM
🎯
Exam Tip — Splunk Integration

Given your Splunk background — this is relevant. If an exam scenario mentions sending Azure AI service logs to Splunk or another external SIEM, the answer is Event Hub as the destination in diagnostic settings. Splunk has a connector that reads from Event Hub. You would NOT send logs directly to Splunk from Azure — you go Azure → Event Hub → Splunk.

Log categories for Azure AI services

When setting up diagnostic settings, you choose which log categories to capture:

Log CategoryWhat it recordsUse when
AuditEvent Key reads, key regenerations, changes to network rules, RBAC assignments. Who did what to manage the resource. Security auditing, compliance, detecting unauthorised changes.
RequestResponse Every API call — timestamp, caller IP, request type, response code, latency. Debugging errors, understanding usage patterns, billing analysis.
Trace Detailed internal service traces — very verbose. Useful for deep debugging. Only when investigating a specific hard-to-reproduce issue.

How to configure diagnostic settings — portal walkthrough

1
Open your AI resource → Diagnostic settings

Left menu → Monitoring section → Diagnostic settings → click + Add diagnostic setting

2
Choose log categories and metrics

Check Audit, RequestResponse, and AllMetrics for full coverage.

3
Choose destination

Tick Send to Log Analytics workspace and select your workspace. Optionally also send to a Storage Account for archiving.

4
Save

Click Save. Logs start flowing within a few minutes. New logs appear in Log Analytics within 5–15 minutes.

Writing KQL queries to analyse Azure AI service logs

KQL (Kusto Query Language) is how you search your logs in Log Analytics. It looks a bit like SQL but works differently. Let's learn the key building blocks before reading actual queries.

🔎
KQL is like filtering a spreadsheet with pipes

Think of each log entry as a row in a spreadsheet. KQL lets you:
• Pick which spreadsheet (table) to look at
• Filter to only rows matching your criteria
• Pick which columns to show
• Sort and group the results

The | symbol (pipe) chains these steps together — the output of one step flows into the next, like water through pipes.

KQL building blocks

KQL KeywordWhat it doesSQL equivalent
TableNameStart with the table to query — always firstFROM TableName
| whereFilter rows — keep only rows matching a conditionWHERE
| projectChoose which columns to show (drop the rest)SELECT col1, col2
| summarizeGroup and aggregate — count, average, sumGROUP BY + SUM/COUNT
| order bySort the results by a columnORDER BY
| takeReturn only the first N rowsTOP N / LIMIT N
| extendAdd a new calculated column to the resultsComputed column
ago()Time function — "1h ago" means one hour before nowDATEADD / NOW()-1h

Exam-ready KQL queries for Azure AI services

These are the queries the exam most commonly tests. Read the comments — they explain what every line does.

Query 1 — View all errors in the last 24 hours
// AzureDiagnostics is the main table that holds logs from Azure resources AzureDiagnostics | where TimeGenerated > ago(24h) // Only look at the last 24 hours | where ResourceProvider == "MICROSOFT.COGNITIVESERVICES" // Only Azure AI Services logs | where ResultType == "Failed" // Only failed requests | project TimeGenerated, OperationName, ResultDescription, CallerIPAddress // Show only these 4 columns — drop everything else | order by TimeGenerated desc // Most recent errors first
Query 2 — Count errors by type in the last hour
AzureDiagnostics | where TimeGenerated > ago(1h) | where ResourceProvider == "MICROSOFT.COGNITIVESERVICES" | where ResultType == "Failed" | summarize ErrorCount = count() by ResultDescription // Group rows by error message, count how many of each | order by ErrorCount desc // Most common error first
Query 3 — Average latency per hour over the last day
AzureDiagnostics | where TimeGenerated > ago(24h) | where ResourceProvider == "MICROSOFT.COGNITIVESERVICES" | summarize AvgLatencyMs = avg(DurationMs) by bin(TimeGenerated, 1h) // bin(TimeGenerated, 1h) groups timestamps into 1-hour buckets // avg(DurationMs) calculates the average latency in each bucket | order by TimeGenerated asc // Oldest first — good for trend charts
Query 4 — Audit log: who regenerated an API key?
AzureDiagnostics | where TimeGenerated > ago(7d) // Last 7 days | where ResourceProvider == "MICROSOFT.COGNITIVESERVICES" | where OperationName == "List Account Keys" // Filter to key-related operations only or OperationName == "Regenerate Account Key" | project TimeGenerated, OperationName, CallerIPAddress, Identity | order by TimeGenerated desc
Query 5 — Check TLS versions used by clients
AzureDiagnostics | where ResourceProvider == "MICROSOFT.COGNITIVESERVICES" | where TimeGenerated > ago(1d) | summarize RequestCount = count() by TlsVersion_s // Group by TLS version used | order by RequestCount desc // Use this to identify clients still using outdated TLS 1.0 or 1.1
How to run KQL queries in the portal

Azure portal → Log Analytics workspaces → your workspace → Logs. Paste any query above into the query editor and click Run. Results appear as a table below. You can also access logs from your AI resource directly: your resource → Monitoring → Logs.

Getting notified when something goes wrong

You shouldn't need to check metrics manually every hour. Alert rules watch your metrics and logs 24/7 and notify you automatically when a threshold is breached.

Anatomy of an alert rule

🎯
Scope

Which resource to monitor — your Azure AI service, a resource group, or entire subscription.

📐
Condition

The threshold that triggers the alert — e.g. "Total Errors > 10 in a 5-minute window."

📢
Action Group

Who/what gets notified — email, SMS, webhook, Logic App, Azure Function.

⚙️
Severity

How serious: 0 (Critical) → 1 (Error) → 2 (Warning) → 3 (Informational) → 4 (Verbose).

Alert rules commonly tested on the exam

Alert type
Condition example
Why monitor this
High error rate
Total Errors > 50 in 5 minutes
App bugs, bad requests, auth failures
High latency
Avg Latency > 2000ms over 10 minutes
Service degradation, slow responses
Key regeneration
AuditEvent: Regenerate Account Key detected
Security — alert on unexpected key changes
429 rate limit hits
Client Errors with HTTP 429 > 0
You're hitting your quota ceiling
Zero calls
Total Calls = 0 for 15 minutes (during business hours)
Detect outages — service may be down

Creating an alert rule — portal walkthrough

1
Open your AI resource → Alerts

Left menu → Monitoring → Alerts → click + Create → Alert rule

2
Set the Condition

Click Add condition → choose signal type (Metrics or Log search) → select the metric (e.g. Total Errors) → set threshold (e.g. Greater than 10) → set evaluation frequency (e.g. every 5 minutes over a 5-minute window)

3
Create or select an Action Group

Click + Create action group → name it → add actions: Email/SMS/Push/Voice → add your email address → OK. You can reuse this action group across multiple alert rules.

4
Name the alert and set severity → Review + Create

Give it a descriptive name like "AI Language — High Error Rate". Choose severity 1 (Error) for this example. Click Review + create.

Keeping Azure AI costs under control

Azure AI services charge per API call (on S0 tier). Unexpected traffic spikes or misconfigured apps can run up large bills. The exam tests your knowledge of cost management tools and strategies.

F0 vs S0 — cost implications

F0
Free Tier
  • ✅ $0/month
  • ✅ Great for learning and dev
  • ❌ Limited calls per minute
  • ❌ Limited calls per month
  • ❌ Only 1 per service per subscription
  • ❌ No private endpoints
  • ❌ No SLA guarantee
S0
Standard Tier
  • ✅ Pay per call (varies by service)
  • ✅ No monthly call limit
  • ✅ Private endpoints supported
  • ✅ SLA guarantee (99.9% uptime)
  • ✅ Multiple per subscription
  • ⚠️ Costs scale with usage

Cost management tools

The central tool for viewing and managing Azure spending. Found at: Azure portal → search "Cost Management".

Key features:
Cost Analysis — charts of actual spend by service, resource group, tag, or time period
Budgets — set a monthly spend limit and get notified at 80%, 90%, 100%
Forecasts — projected spend based on current usage trends
Cost Alerts — alerts when actual or forecast spend exceeds thresholds

Important exam fact: Budgets do NOT stop services from running. They only send notifications. To actually stop spending, you would need to delete or disable resources manually (or automate it via a Logic App).

Tags are key-value labels you apply to Azure resources. For example: Department: Finance, Project: CustomerAI, Environment: Production.

In Cost Management, you can filter and group costs by tag. This lets you answer "how much did the Finance department's AI services cost this month?" — very useful for chargeback/showback in enterprises like CIBC.

How to apply tags: Azure portal → your resource → Tags → add key-value pairs → Save.

Every Azure AI service has quota limits — maximum calls per minute (TPM = Transactions Per Minute) and per month. Hitting quota returns HTTP 429 (Too Many Requests).

To manage quota:
• Azure portal → your resource → Quotas (or Resource Management → Quotas)
• You can request quota increases from Microsoft
• For Azure OpenAI: quota is measured in TPM (Tokens Per Minute) — the number of tokens processed per minute across all deployments

Cost optimisation strategies for the exam:
• Use F0 for development, S0 only for production
• Implement caching — don't call the AI service for the same input twice
• Choose the right model — GPT-3.5-turbo is far cheaper than GPT-4o for simple tasks
• Monitor token usage for OpenAI — unnecessary long prompts cost more

🎯
Exam Tip — Budget Behaviour

A very common exam question: "A company sets a $500 budget for their Azure AI service. The budget is reached. What happens?"

The answer is: Nothing happens automatically. Azure sends email notifications to the budget owner but does NOT stop the service, delete resources, or restrict API calls. The service continues running and continues charging. To stop it you must manually intervene.

What this topic is tested on

⚠️
Top 5 Tested Facts from This Topic

1. Diagnostic settings must be explicitly configured — Logs do not go anywhere by default. You must create a diagnostic setting and choose a destination. Metrics are always collected automatically — only logs need configuration.

2. Log Analytics = KQL queries; Storage Account = archiving — If an exam scenario says "query logs" → Log Analytics. "Archive logs for 2 years" → Storage Account. "Stream to Splunk" → Event Hub.

3. Budgets don't stop services — Budgets send notifications only. Services keep running even after budget is exhausted.

4. Application Insights = application-level monitoring — If a scenario mentions tracking exceptions, custom events, or end-to-end request traces in your application code → Application Insights. Azure Monitor metrics alone cannot track what happens inside your app.

5. Alert severity levels — 0 = Critical, 1 = Error, 2 = Warning, 3 = Informational, 4 = Verbose. Lower number = higher severity. The exam may show a severity number and ask what it means.

Test your understanding

5 questions — select an answer to see the explanation immediately.

Topic 4 Quiz 1 / 5
Scenario: A DevOps engineer needs to store Azure AI Language service logs for compliance purposes for 2 years. The logs will rarely be queried — they just need to be retained safely and cheaply.

Which diagnostic settings destination should they choose?

💡 Explanation

B is correct. Azure Storage Account is the cheapest option for long-term log archiving. Logs are stored as JSON files in Blob Storage. Log Analytics (option A) is more expensive for long retention and is optimised for querying, not archiving — the scenario says logs "will rarely be queried." Event Hub (option C) is for real-time streaming to external systems. Application Insights (option D) monitors application code, not compliance archiving.

A developer needs to write a KQL query that shows only failed requests to their Azure AI service in the last 6 hours, and shows the most recent failures first. Which query is correct?

💡 Explanation

A is correct. KQL queries start with the table name, then use pipe-separated operators in logical order: filter by time, filter by condition, then sort. Option B has the operators in the wrong order (ordering before filtering is less efficient but more importantly the exam expects the standard pattern). Option C uses SQL syntax — not KQL. Option D uses incorrect KQL syntax (where ago(6h) is not valid — it should be where TimeGenerated > ago(6h)).

Scenario: A company's Azure AI service budget is set to $500/month. On the 20th of the month, the actual spend reaches $500. The development team continues making API calls for the rest of the month.

What happens when the $500 budget is reached?

💡 Explanation

B is correct. Azure Cost Management budgets are notification-only. When the threshold is reached, Azure sends email alerts to the configured recipients. The service continues running, API calls continue working, and billing continues to accumulate beyond the budget amount. Azure does NOT automatically stop, throttle, or delete resources when a budget is exceeded. To prevent overspending you must take manual action or set up automation (e.g. a Logic App that disables the resource when a budget alert fires).

A developer wants to track exceptions thrown in their Python application when calling Azure AI services, and send custom events to understand user behaviour. Which monitoring tool should they use?

💡 Explanation

B is correct. Application Insights is specifically designed for application-level monitoring — tracking exceptions thrown in your code, custom events you define, user flows, and performance. Azure Monitor Metrics (option A) monitors the AI service at the infrastructure level — total calls, latency — but cannot see inside your Python code. Log Analytics/KQL (option C) can query diagnostic logs but doesn't track application-level custom events. Cost Management (option D) is for billing, not application monitoring.

An alert rule on an Azure AI Language service is configured with severity 1. What does severity 1 mean, and what is the most severe level?

💡 Explanation

B is correct. Azure alert severity levels: 0 = Critical (most severe), 1 = Error, 2 = Warning, 3 = Informational, 4 = Verbose (least severe). Lower number = higher severity — the opposite of what many people intuitively expect. Severity 0 (Critical) is for outages affecting all users. Severity 1 (Error) is for significant errors requiring prompt action. There is no severity 5 in Azure.

Mark this topic as complete