MODULE 28 Monitor & Maintain · 10–15% ~3 giờ

Cấu hình Azure Monitor

Azure Monitor là nền tảng giám sát toàn diện của Azure — thu thập metrics và logs từ mọi tầng hạ tầng, phân tích dữ liệu, tạo cảnh báo và trực quan hóa để đảm bảo availability và performance.

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.

Tính năng chính
  • 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
Các nguồn dữ liệu
  • • 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)
Azure Monitor là trung tâm: Tất cả dữ liệu giám sát của Azure — từ VM đến App Service đến VNet — đều chạy qua Azure Monitor. Log Analytics Workspace, Application Insights và Alerts đều là thành phần của Azure Monitor.

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
Platform Metrics (tự động)

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 (cần cấu hình)

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:

1
Application Tier

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.

2
Guest OS Tier

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

3
Azure Resource Tier

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.

4
Azure Subscription Tier

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.

5
Azure Tenant Tier

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

Các loại Activity Log Events
  • 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)
Cấu trúc một Activity Log Entry
  • 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
Truy vấn Activity Log bằng Azure CLI
# 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
Lưu Activity Log dài hơn 90 ngày: Tạo Diagnostic Setting trên Subscription để stream Activity Log sang Log Analytics Workspace hoặc Storage Account. Từ đó có thể truy vấn KQL hoặc archive hàng năm theo yêu cầu compliance.

Bài Tập Thực Hành (Lab)

Lab 28-A: Metrics Explorer Lab 28-B: Diagnostic Settings Lab 28-C: Activity Log Query Lab 28-D: Dashboard
1

Tạo Resource Group, Log Analytics Workspace và VM để giám sát

Azure CLI— Cloud Shell hoặc terminal đã login az
# 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
Verify Portal: Azure Portal → Monitor → Log Analytics workspaces → xác nhận law-az104-m28 xuất hiện với status Active. Portal → Virtual Machines → xác nhận vm-monitor-lab28 running.
2

Bật Diagnostic Settings — gửi VM metrics và resource logs sang Log Analytics

Azure CLI— Chạy được trên PowerShell, CMD, Bash hoặc Azure Cloud Shell
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."
Verify Portal: Portal → VM vm-monitor-lab28 → Diagnostic settings → xác nhận "vm-diag-to-law" trỏ về law-az104-m28. Portal → Subscriptions → [sub của bạn] → Diagnostic settings → xác nhận Activity Log được stream.
3

Xem Metrics Explorer và truy vấn Activity Log trên Portal

Azure CLI— Truy vấn metrics và activity log qua CLI
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
Verify Portal: Azure Portal → Monitor → Metrics → chọn VM → metric "Percentage CPU" → xem biểu đồ. Portal → Monitor → Activity log → filter Resource group = rg-az104-m28 → xác nhận có events xuất hiện.
4

Tạo Azure Monitor Dashboard tùy chỉnh và pin metrics charts

Bash— Cloud Shell hoặc Linux/macOS terminal
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"
Verify Portal: Azure Portal → Dashboard → chọn "AZ104-Module28-Monitor" từ dropdown → xác nhận chart CPU hiện thị. Có thể thêm tiles bằng cách vào Metrics Explorer → pin chart vào dashboard.
5

Cleanup — Dọn dẹp tài nguyên Lab 28

Azure CLI— Chạy được trên PowerShell, CMD, Bash hoặc Azure Cloud Shell
# 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."
Lưu ý: Subscription-level Diagnostic Settings không nằm trong Resource Group nên phải xóa riêng trước. Sau khi xóa RG, kiểm tra Monitor → Log Analytics workspaces để xác nhận workspace đã biến mất.

Kết Quả Đầu Ra

Hiểu kiến trúc Azure Monitor

Mô tả được 5 tầng data sources, vai trò của Metrics Store và Log Analytics trong hệ sinh thái Monitor

Phân biệt Metrics vs Logs

Biết khi nào dùng Metrics Explorer (trend, dashboard) và khi nào cần Log Analytics (audit, deep investigation)

Cấu hình Diagnostic Settings

Bật resource logs và metrics export sang Log Analytics Workspace, Storage Account hoặc Event Hubs

Truy vấn Activity Log

Lọc events theo caller, resource group, operation type; export sang Log Analytics để lưu lâu hơn 90 ngày

Tạo Log Analytics Workspace

Tạo workspace, cấu hình retention, kết nối Diagnostic Settings từ nhiều resources và subscription

Xây dựng Monitor Dashboard

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.

Giải pháp

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.

Triển khai

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.

Lợi ích

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.

Giải pháp

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

Triển khai

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.

Lợi ích

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

Giải pháp

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.

Triển khai

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.

Lợi ích

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.

Zalo