Lý Thuyết Cốt Lõi
1. Tổng Quan Azure Monitor
Azure Monitor là dịch vụ giám sát đầy đủ của Azure Platform, thu thập và phân tích telemetry từ mọi tầng: Applications, Operating Systems, Azure Resources, Azure Subscriptions, và Azure Tenants. Mục tiêu là tối đa hóa availability và performance của ứng dụng.
- • Monitor & Visualize: Metrics, dashboards, workbooks
- • Query & Analyze: Log Analytics, Activity Log, Application Insights
- • Alert & Act: Metric alerts, log alerts, action groups
- • Integrate: Export sang Event Hub, Storage, Partner solutions
- • Application code (Application Insights SDK)
- • Guest OS (Azure Monitor Agent / Log Analytics Agent)
- • Azure Resources (Diagnostic settings)
- • Azure Subscription & Tenant (Activity Log, Entra ID logs)
- • Custom sources (REST API, Logic Apps)
2. Metrics vs Logs — Hai Loại Dữ Liệu Giám Sát
Azure Monitor thu thập hai loại dữ liệu cơ bản: Metrics (số liệu thời gian thực) và Logs (bản ghi sự kiện dạng text). Hiểu rõ sự khác biệt giúp chọn đúng công cụ phân tích.
| Tiêu chí | Metrics | Logs |
|---|---|---|
| Cấu trúc | Số liệu theo thời gian (timestamp, value, dimensions) | Bản ghi văn bản tự do, có schema hoặc unstructured |
| Lưu trữ | Azure Monitor Metrics Store (93 ngày mặc định) | Log Analytics Workspace (30–730 ngày) |
| Truy vấn | Metrics Explorer, Portal charts | KQL (Kusto Query Language) trong Log Analytics |
| Độ trễ | Gần thời gian thực (1–3 phút) | 2–5 phút (ingestion pipeline) |
| Dùng khi | CPU %, memory %, network bytes — trend analysis | Audit trail, error diagnosis, security investigation |
Azure tự động thu thập platform metrics cho mọi resource mà không cần cấu hình — CPU usage, Disk read/write IOPS, Network in/out, HTTP request count. Miễn phí. Xem trong Metrics Explorer.
Resource logs (Diagnostic Logs) phải bật thủ công qua Diagnostic Settings trên từng resource. Chọn đích: Log Analytics Workspace, Storage Account, hoặc Event Hubs. Tính phí theo GB ingested.
3. Monitoring Data Tiers — Tầng Dữ Liệu Giám Sát
Azure Monitor thu thập dữ liệu từ 5 tầng (tiers) khác nhau. Mỗi tầng cần cách cấu hình riêng để bật data collection:
Performance và functionality của application code. Thu thập bằng Application Insights — SDK inject vào code hoặc auto-instrumentation. Data: request rates, response times, exceptions, dependencies.
Operating system trên VM hoặc container. Thu thập bằng Azure Monitor Agent (AMA) — agent cài trên VM, đọc performance counters, event logs, syslog. Thay thế Log Analytics Agent (deprecated).
Operation và performance của Azure resource (VM, Storage, VNet, SQL). Platform metrics tự động. Resource logs cần bật Diagnostic Settings và chọn Log Analytics Workspace làm đích.
Operation và management của Azure subscription. Chính là Activity Log — ghi lại mọi control-plane operation: tạo/xóa/sửa resource, role assignment, policy change. Miễn phí, lưu 90 ngày.
Dịch vụ cấp tenant như Microsoft Entra ID. Thu thập bằng Entra Diagnostic Settings — gửi sign-in logs, audit logs sang Log Analytics Workspace. Cần Entra ID P1/P2.
4. Activity Log — Lịch Sử Hoạt Động Subscription
Activity Log ghi lại mọi control-plane operation trong subscription Azure. Đây là nguồn audit trail quan trọng — ai đã làm gì, khi nào, với resource nào. Dữ liệu Activity Log lưu tự động 90 ngày, không tốn phí.
- • Administrative: tạo/sửa/xóa resource (Create VM, Delete RG)
- • Security: Azure Security Center alerts
- • ServiceHealth: thông báo về sự cố Azure service outage
- • ResourceHealth: trạng thái health của từng resource
- • Alert: record khi Azure Monitor alert kích hoạt
- • Autoscale: event scale out/in của VMSS, App Service
- • Recommendation: Azure Advisor gợi ý tối ưu
- • Policy: policy evaluation effect (Deny, Audit, Deploy)
- • eventTimestamp: thời gian xảy ra event
- • operationName: tên operation (Microsoft.Compute/virtualMachines/write)
- • resourceId: ARM resource ID đầy đủ
- • caller: identity thực hiện (user UPN hoặc service principal)
- • status: Accepted / Succeeded / Failed
- • correlationId: GUID liên kết nhiều events cùng request
- • level: Critical / Error / Warning / Informational
# Xem activity log 24h qua
az monitor activity-log list \
--start-time $(date -u -d '24 hours ago' '+%Y-%m-%dT%H:%M:%SZ') \
--output table
# Lọc theo resource group
az monitor activity-log list \
--resource-group rg-az104-m28 \
--start-time 2026-06-01T00:00:00Z \
--output table
# Lọc theo caller (ai thực hiện)
az monitor activity-log list \
--caller "[email protected]" \
--start-time 2026-06-01T00:00:00Z \
--query "[].{Time:eventTimestamp,Operation:operationName.value,Status:status.value}" \
--output table
Bài Tập Thực Hành (Lab)
Tạo Resource Group, Log Analytics Workspace và VM để giám sát
# Tạo Resource Group
az group create \
--name rg-az104-m28 \
--location southeastasia \
--tags Course=AZ-104 Module=28 Environment=Lab
# Tạo Log Analytics Workspace
az monitor log-analytics workspace create \
--resource-group rg-az104-m28 \
--workspace-name law-az104-m28 \
--location southeastasia \
--sku PerGB2018 \
--retention-time 30
# Lấy Workspace ID và Key (dùng để kết nối agent)
WORKSPACE_ID=$(az monitor log-analytics workspace show \
--resource-group rg-az104-m28 \
--workspace-name law-az104-m28 \
--query customerId -o tsv)
WORKSPACE_KEY=$(az monitor log-analytics workspace get-shared-keys \
--resource-group rg-az104-m28 \
--workspace-name law-az104-m28 \
--query primarySharedKey -o tsv)
echo "Workspace ID: $WORKSPACE_ID"
echo "Workspace Key: $WORKSPACE_KEY"
# Tạo VM Ubuntu để giám sát
az vm create \
--resource-group rg-az104-m28 \
--name vm-monitor-lab28 \
--image Ubuntu2204 \
--size Standard_B1s \
--admin-username azureuser \
--generate-ssh-keys \
--location southeastasia \
--tags Course=AZ-104 Module=28
law-az104-m28 xuất hiện với status Active. Portal → Virtual Machines → xác nhận vm-monitor-lab28 running.
Bật Diagnostic Settings — gửi VM metrics và resource logs sang Log Analytics
WORKSPACE_ID=$(az monitor log-analytics workspace show \
--resource-group rg-az104-m28 \
--workspace-name law-az104-m28 \
--query id -o tsv)
VM_ID=$(az vm show \
--resource-group rg-az104-m28 \
--name vm-monitor-lab28 \
--query id -o tsv)
# Bật Diagnostic Settings trên VM — gửi metrics sang Log Analytics
az monitor diagnostic-settings create \
--name "vm-diag-to-law" \
--resource "$VM_ID" \
--workspace "$WORKSPACE_ID" \
--metrics '[{"category":"AllMetrics","enabled":true,"retentionPolicy":{"enabled":false,"days":0}}]'
# Bật Diagnostic Settings trên Subscription — gửi Activity Log sang Log Analytics
SUB_ID=$(az account show --query id -o tsv)
az monitor diagnostic-settings subscription create \
--name "sub-activitylog-to-law" \
--location southeastasia \
--workspace "$WORKSPACE_ID" \
--logs '[{"category":"Administrative","enabled":true},{"category":"Security","enabled":true},{"category":"ServiceHealth","enabled":true},{"category":"Alert","enabled":true},{"category":"Policy","enabled":true}]'
echo "Diagnostic settings đã được cấu hình."
echo "Dữ liệu sẽ xuất hiện trong Log Analytics sau 5-10 phút."
Xem Metrics Explorer và truy vấn Activity Log trên Portal
VM_ID=$(az vm show \
--resource-group rg-az104-m28 \
--name vm-monitor-lab28 \
--query id -o tsv)
# Xem danh sách metrics có sẵn cho VM
az monitor metrics list-definitions \
--resource "$VM_ID" \
--query "[].{Name:name.value,Unit:unit,Desc:displayDescription}" \
--output table | head -20
# Lấy CPU Percentage của VM trong 1 giờ qua
az monitor metrics list \
--resource "$VM_ID" \
--metric "Percentage CPU" \
--interval PT5M \
--start-time $(date -u -d '1 hour ago' '+%Y-%m-%dT%H:%M:%SZ') \
--end-time $(date -u '+%Y-%m-%dT%H:%M:%SZ') \
--aggregation Average \
--query "value[0].timeseries[0].data[*].{Time:timeStamp,CPU:average}" \
--output table
# Xem Activity Log — lọc các delete operation gần đây
az monitor activity-log list \
--resource-group rg-az104-m28 \
--start-time $(date -u -d '24 hours ago' '+%Y-%m-%dT%H:%M:%SZ') \
--query "[?contains(operationName.value,'delete') || contains(operationName.value,'write')].{Time:eventTimestamp,Op:operationName.value,Caller:caller,Status:status.value}" \
--output table
Tạo Azure Monitor Dashboard tùy chỉnh và pin metrics charts
SUB_ID=$(az account show --query id -o tsv)
VM_ID=$(az vm show \
--resource-group rg-az104-m28 \
--name vm-monitor-lab28 \
--query id -o tsv)
# Tạo dashboard JSON template
cat > /tmp/monitor-dashboard.json << EOF
{
"lenses": {
"0": {
"order": 0,
"parts": {
"0": {
"position": {"x": 0, "y": 0, "colSpan": 6, "rowSpan": 4},
"metadata": {
"type": "Extension/Microsoft_Azure_Monitoring/PartType/MetricsChartPart",
"settings": {
"content": {
"options": {
"chart": {
"metrics": [{
"resourceMetadata": {"id": "$VM_ID"},
"name": "Percentage CPU",
"aggregationType": 4,
"namespace": "microsoft.compute/virtualmachines",
"metricVisualization": {"displayName": "CPU %"}
}],
"title": "VM CPU Usage — Lab 28",
"titleKind": 1,
"visualization": {"chartType": 2}
}
}
}
}
}
}
}
}
},
"metadata": {
"model": {
"timeRange": {
"value": {"relative": {"duration": 24, "timeUnit": 1}},
"type": "MsPortalFx.Composition.Configuration.ValueTypes.TimeRange"
}
}
}
}
EOF
# Deploy dashboard
az portal dashboard create \
--name "AZ104-Module28-Monitor" \
--resource-group rg-az104-m28 \
--location southeastasia \
--input-path /tmp/monitor-dashboard.json
echo "Dashboard tạo thành công."
echo "Xem tại: Portal → Dashboard → AZ104-Module28-Monitor"
Cleanup — Dọn dẹp tài nguyên Lab 28
# Xóa Diagnostic Settings trên Subscription
az monitor diagnostic-settings subscription delete \
--name "sub-activitylog-to-law" \
--yes
# Xóa Resource Group — kéo theo VM, Log Analytics Workspace, Dashboard
az group delete --name rg-az104-m28 --yes --no-wait
echo "Cleanup đã được kích hoạt. RG sẽ bị xóa trong vài phút."
Kết Quả Đầu Ra
Mô tả được 5 tầng data sources, vai trò của Metrics Store và Log Analytics trong hệ sinh thái Monitor
Biết khi nào dùng Metrics Explorer (trend, dashboard) và khi nào cần Log Analytics (audit, deep investigation)
Bật resource logs và metrics export sang Log Analytics Workspace, Storage Account hoặc Event Hubs
Lọc events theo caller, resource group, operation type; export sang Log Analytics để lưu lâu hơn 90 ngày
Tạo workspace, cấu hình retention, kết nối Diagnostic Settings từ nhiều resources và subscription
Pin metrics charts, tạo shared dashboard cho team ops, tùy chỉnh time range và aggregation type
Ứng Dụng Thực Tế
Tình huống 1: Tập đoàn bán lẻ VN — Giám sát hạ tầng đa site
Hệ thống ERP chạy trên 30 VM trải dài 3 region, cần dashboard tập trung và phát hiện sớm bất thường performance.
Một Log Analytics Workspace trung tâm thu nhận diagnostic logs từ toàn bộ 30 VM. Bật Azure Monitor Agent trên tất cả VMs qua Policy (DeployIfNotExists). Dashboard chia sẻ toàn team Ops.
Diagnostic Settings trên mỗi VM gửi metrics (CPU, Disk, Network) sang workspace. Activity Log subscription stream về workspace để audit. Workbooks tạo báo cáo tuần tự động.
Từ 30 dashboard riêng lẻ xuống 1 view tập trung. Phát hiện VM có CPU cao bất thường trong vòng 5 phút. Audit trail đầy đủ khi kiểm toán PDPA.
Tình huống 2: Fintech startup — Activity Log làm audit trail bảo mật
Startup fintech cần chứng minh với đối tác ngân hàng rằng mọi thay đổi hạ tầng đều được ghi lại và lưu giữ tối thiểu 1 năm.
Stream Activity Log (Administrative + Security + Policy categories) sang Log Analytics Workspace với retention 365 ngày. Đồng thời archive sang Storage Account (immutable blob) để bằng chứng pháp lý.
Subscription Diagnostic Setting → 2 destinations: Log Analytics (query) + Storage Account (archive). Policy DeployIfNotExists tự động bật Diagnostic Settings cho mọi resource mới trong subscription.
Đáp ứng yêu cầu PCI-DSS log retention. Query KQL trong Log Analytics cho audit nhanh. Storage archive immutable không ai xóa được — bằng chứng pháp lý bền vững.
Tình huống 3: Chuỗi bệnh viện — Monitoring đa tầng ứng dụng HIS
Hệ thống HIS (Hospital Information System) chạy App Service + SQL Database + Storage, cần visibility từ application code đến infrastructure.
Application Insights cho App Service (application tier) — track response time, exception rate. Diagnostic Settings trên SQL Database — query performance insights, deadlocks. Platform metrics trên Storage — transaction rate, latency.
Tất cả đổ về 1 Log Analytics Workspace. Application Map trong Application Insights visualize toàn bộ dependency. Azure Monitor Workbook tổng hợp health score cho ban lãnh đạo.
MTTR (Mean Time to Resolution) giảm từ 4h xuống 30 phút nhờ Application Map. SQL slow query phát hiện chủ động trước khi ảnh hưởng bác sĩ. Compliance report HIPAA sẵn sàng.