在數據 API 產生器中使用 Azure Application Insights

Azure Application Insights 是一項應用程式效能監控(APM)服務,能自動擷取請求、追蹤、例外及效能指標。 將它與 Data API 建構器(DAB)整合,有助於你監控執行時行為、診斷問題,並優化生產環境的效能。

顯示 Application Insights 遙測流程的圖表。

警告

Application Insights 與 DAB 的整合在 Azure App Service 網頁應用程式上可能會因雙重儀器而受到限制。 Application Insights 在你自架容器、Azure 容器應用或 Azure Kubernetes Service(AKS)中,搭配 DAB 運作最佳。 如果你必須使用 App Service,請徹底測試或考慮其他監控方式。

先決條件

  • 現有的 DAB 設定檔。
  • Azure Application Insights 資源.
  • Application Insights 連線字串。
  • 數據 API 產生器 CLI。 安裝 CLI

取得連接字串

在設定 DAB 之前,請從 Azure 取得 Application Insights 的連線字串。

Azure 入口網站

  1. 在 Azure 入口網站中瀏覽到您的 Application Insights 資源。
  2. 請前往 概覽 或 物業。
  3. 複製 連接字串 (不是 Instrumentation 鍵)。

Azure CLI

az monitor app-insights component show \
  --app my-app-insights \
  --resource-group my-rg \
  --query connectionString -o tsv

連接字串格式

InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://<region>.in.applicationinsights.azure.com/;LiveEndpoint=https://<region>.livediagnostics.monitor.azure.com/

備註

使用完整的連接字串(不只是儀器鍵)來處理區域特定端點並提升效能。

設定 Application Insights

在你的設定檔裡將application-insights新增到runtime.telemetry之下。

{
  "runtime": {
    "telemetry": {
      "application-insights": {
        "enabled": true,
        "connection-string": "@env('app-insights-connection-string')"
      }
    }
  }
}

此配置使用環境變數作為連接字串。 在檔案 .env 中定義它:

app-insights-connection-string="InstrumentationKey=...;IngestionEndpoint=...;LiveEndpoint=..."

警告

千萬不要把連線字串提交給原始碼控制。 一定要用環境變數或 Azure Key Vault。

Command-line

使用dab add-telemetry配置 Application Insights。

Option 說明
--app-insights-enabled 啟用或停用應用程式洞察(true 或 false)。
--app-insights-conn-string 用於應用洞察的連接字串。

啟用 Application Insights

dab add-telemetry \
  --app-insights-enabled true \
  --app-insights-conn-string "@env('app-insights-connection-string')"

停用 Application Insights

dab add-telemetry \
  --app-insights-enabled false

備註

Application Insights 的設定使用 dab add-telemetry,不是 dab configure。

運行 DAB

用你的設定檔啟動 DAB:

dab start

請查看啟動日誌以確認:

Application Insights telemetry is enabled with connection string from config.

運作方式

啟用 Application Insights 時,DAB 會:

  1. 註冊 Application Insights SDK 使用 AddApplicationInsightsTelemetry()。
  2. 註冊一個自訂遙測初始化器,以加入 DAB 專屬屬性來強化所有遙測資料。
  3. 用設定檔裡的連線字串來設定 TelemetryClient 。
  4. 與 ASP.NET Core 日誌整合,擷取主控台日誌作為追蹤。

數據流

DAB Application
    ↓
ILogger (ASP.NET Core)
    ↓
ApplicationInsightsLoggerProvider
    ↓
AppInsightsTelemetryInitializer (adds custom properties)
    ↓
TelemetryClient
    ↓
Application Insights (Azure)

捕獲的內容

遙測類型 來源 範例
請求事項 ASP.NET 核心中介軟體 REST/GraphQL 請求、回應時間、狀態碼
痕跡 ILogger DAB 中的呼叫 啟動日誌、查詢執行日誌、警告
Exceptions 未處理的例外狀況 執行時錯誤、設定錯誤、資料庫錯誤
依賴 資料庫呼叫 SQL 查詢,Azure Cosmos DB 操作,持續時間
效能計數器 執行時間 CPU 使用率、記憶體消耗、請求率

遙測數據增強

DAB 會自動以自訂屬性豐富所有 Application Insights 遙測資料:

房產 說明 範例值
ProductName DAB 使用者代理識別碼 dab-1.2.3
UserAgent 完整的 DAB 使用者代理字串 data-api-builder/1.2.3
Cloud.RoleName DAB 雲端角色名稱 DataApiBuilder
Component.Version DAB 版本 1.2.3
Session.Id 唯一會話識別碼 guid

這些特性有助於在應用洞察中過濾並關聯 DAB 特定的遙測數據。

查詢 Azure 中的遙測資料

追蹤 (記錄)

traces
| where customDimensions["ProductName"] startswith "dab-"
| order by timestamp desc
| project timestamp, message, severityLevel

LogLevel 映射:

LogLevel 嚴重程度 價值觀
追蹤/除錯 詳細資訊 0
資訊 資訊 1
警告 警告 2
錯誤 錯誤 3
危急 危急 4

請求事項

requests
| where customDimensions["ProductName"] startswith "dab-"
| order by timestamp desc
| project timestamp, name, duration, resultCode, success

Application Insights 中查詢資料 API 建構器應用程式請求的結果截圖。

Exceptions

exceptions
| where customDimensions["ProductName"] startswith "dab-"
| order by timestamp desc
| project timestamp, type, outerMessage, details

Application Insights 中查詢 Data API 建構器例外的結果截圖。

依DAB版本篩選

traces
| where customDimensions["Component.Version"] == "1.2.3"
| project timestamp, message, severityLevel

查找緩慢的 GraphQL 查詢

requests
| where name contains "/graphql"
| where duration > 1000
| project timestamp, name, duration, resultCode
| order by duration desc

申請成功率

requests
| where customDimensions["ProductName"] startswith "dab-"
| summarize 
    Total = count(),
    Success = countif(success == true),
    Failed = countif(success == false)
| extend SuccessRate = (Success * 100.0) / Total

最慢速資料庫操作

dependencies
| where type == "SQL" or type == "Azure Cosmos DB"
| top 10 by duration desc
| project timestamp, name, duration, target, data

即時計量

Live Metrics 提供即時監控,延遲 <為 1 秒。 Application Insights 在設定後會自動啟用。

存取即時指標

  1. 在 Azure 入口網站中開啟 Application Insights 資源。
  2. 請在左側選單中進入 即時指標 。
  3. 開始你的DAB申請。
  4. 幾秒鐘內,即時數據便會出現。

Application Insights 中 Data API 建置器資料的即時指標頁面截圖。

你所看到的

計量 說明
收到的請求 REST/GraphQL 每秒請求數
外部請求 每秒資料庫呼叫次數
整體健康狀況 成功率,每秒失敗次數
記憶體 / CPU 資源取用量
例外率 每秒例外數

小提示

在開發過程中使用即時指標,查看 API 請求與資料庫操作的即時回饋。

取樣與資料保存

自適應取樣

Application Insights SDK 在流量大時自動取樣遙測數據,以降低成本並維持速率限制。 取樣率顯示於應用洞察介面中。

預設行為:

  • 低流量:所有遙測資料已發送(100%)
  • 高流量:取樣會自動降低音量
  • 保存代表性資料

資料保留

Plan 預設保存 最大保留率
免費層 90 天 90 天
隨用隨付 90 天 730天(兩年)

設定保留:應用洞察→使用情況及預估成本→資料保留。

效能考量

遙測開銷

Application Insights 所增加的負擔極小:

  • 記憶體:根據流量約 10-50 MB
  • CPU: <正常負載下 1%
  • 延遲: <每個請求 1 毫秒(非同步)

最佳做法

  • 使用環境變數來設定連接字串。
  • 如果不需要,就停用本地開發中的功能。
  • 在生產過程中監控取樣率。
  • 設定適當的資料保留以管理成本。

在開發中停用

{
  "runtime": {
    "telemetry": {
      "application-insights": {
        "enabled": false
      }
    }
  }
}

匯出與視覺化

遙測資料透過 Application Insights SDK 匯出。 SDK 會定期地將資料封包後傳送。

備註

SDK 控制匯出時序。 預設行為是每隔幾秒就批次傳送遙測資料。

警告

臨時貨櫃若迅速關閉,可能會在出口完成前就離開。 設定優雅的關機視窗,避免激烈終止,以確保待處理的遙測資料會被刷新。

連接字串與儀器金鑰

{
  "connection-string": "InstrumentationKey=...;IngestionEndpoint=https://eastus.in.applicationinsights.azure.com/"
}

優點:

  • 區域特定端點(較低延遲)
  • 支援主權雲
  • 具備未來防範性(Microsoft 推薦的做法)

舊版監控密鑰

雖然仍支援,Microsoft 建議新實作使用連線字串。

{
  "connection-string": "InstrumentationKey=00000000-0000-0000-0000-000000000000"
}

備註

如果你只提供一個儀器金鑰,Application Insights 會使用全域擷取端點,這可能會有較高的延遲。

故障排除

錯誤:「若已啟用,Application Insights 連線字串不能為 null 或空字串」

原因: enabled 設定為, true 但 connection-string 缺少或為空。

解決方案:啟用 Application Insights 時提供有效的連接字串,或設 enabled 為 false。

{
  "runtime": {
    "telemetry": {
      "application-insights": {
        "enabled": true,
        "connection-string": "@env('app-insights-connection-string')"
      }
    }
  }
}

DAB 開始啟動,但沒有出現任何遙測數據

請查看啟動日誌中的這些訊息:

dab start --LogLevel Information

成功訊息:

Application Insights telemetry is enabled with connection string from config.

警告訊息:

Logs won't be sent to Application Insights because an Application Insights connection string is not available in the runtime config.
Application Insights are disabled.

錯誤訊息:

Telemetry client is not initialized.

驗證環境變數

echo $app-insights-connection-string

使用直接連接字串進行測試

暫時使用直接連接字串(非環境變數)來驗證字串的有效性:

{
  "connection-string": "InstrumentationKey=...;IngestionEndpoint=..."
}

如果這個測試成功,問題出在環境變數載入。