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.
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
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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
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
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.
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).
In the Azure portal → your resource → Metrics, you can chart any metric over time — calls, errors, latency — and see trends.
Detailed logs are routed to a Log Analytics workspace where you can write KQL queries to search, filter, and aggregate them.
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.
The total number of API calls made to your service in a time period. Use this to understand usage volume and growth trends.
Calls that returned an HTTP 2xx response — the service processed the request successfully. Compare against Total Calls to calculate success rate.
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.
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.
HTTP 4xx errors — your request was wrong. Common causes: invalid API key (401), bad request format (400), rate limit exceeded (429).
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.
Total bytes sent TO the service. Useful for billing analysis — some services charge based on the amount of data processed.
Total bytes returned FROM the service. Responses — especially from language models — can be large. Monitor this for unexpected cost spikes.
How to view metrics in the Azure portal
portal.azure.com → search for your resource → click it to open
Under the Monitoring section. This opens the Metrics Explorer.
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.
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 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
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.
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 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.
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 Category | What it records | Use 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
Left menu → Monitoring section → Diagnostic settings → click + Add diagnostic setting
Check Audit, RequestResponse, and AllMetrics for full coverage.
Tick Send to Log Analytics workspace and select your workspace. Optionally also send to a Storage Account for archiving.
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.
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 Keyword | What it does | SQL equivalent |
|---|---|---|
TableName | Start with the table to query — always first | FROM TableName |
| where | Filter rows — keep only rows matching a condition | WHERE |
| project | Choose which columns to show (drop the rest) | SELECT col1, col2 |
| summarize | Group and aggregate — count, average, sum | GROUP BY + SUM/COUNT |
| order by | Sort the results by a column | ORDER BY |
| take | Return only the first N rows | TOP N / LIMIT N |
| extend | Add a new calculated column to the results | Computed column |
ago() | Time function — "1h ago" means one hour before now | DATEADD / 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.
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
Which resource to monitor — your Azure AI service, a resource group, or entire subscription.
The threshold that triggers the alert — e.g. "Total Errors > 10 in a 5-minute window."
Who/what gets notified — email, SMS, webhook, Logic App, Azure Function.
How serious: 0 (Critical) → 1 (Error) → 2 (Warning) → 3 (Informational) → 4 (Verbose).
Alert rules commonly tested on the exam
Creating an alert rule — portal walkthrough
Left menu → Monitoring → Alerts → click + Create → Alert rule
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)
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.
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
- ✅ $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
- ✅ 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
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
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.
Which diagnostic settings destination should they choose?
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.