啟用適用於 .NET、Node.js、Python 和 Java 應用程式的 Azure 監視器 OpenTelemetry (部分機器翻譯)

本文說明如何在 Application Insights 內啟用和設定以 OpenTelemetry 為基礎的資料收集。 Azure 監視器 OpenTelemetry 發行版本:

  • 提供 OpenTelemetry 發行版本,其中包含 Azure 監視器的特定功能支援。
  • 藉由包含 OpenTelemetry 檢測程式庫來收集追蹤、計量、記錄和例外狀況,以啟用自動遙測。
  • 允許收集自訂遙測。
  • 支援即時計量以監視及收集來自即時、生產階段 Web 應用程式的更多遙測。

如需使用 Azure 監視器 OpenTelemetry 發行版本的優點相關資訊,請參閱為何應該使用 Azure 監視器 OpenTelemetry 發行版本

若要深入了解如何使用 OpenTelemetry 收集資料,請參閱資料收集基本概念OpenTelemetry 常見問題集

OpenTelemetry 發行狀態

OpenTelemetry 供應項目適用於 .NET、Node.js、Python 和 Java 應用程式。 如需各種功能版本狀態,請參閱常見問題 (部分機器翻譯)。

使用 Application Insights 啟用 OpenTelemetry

請遵循本節中的步驟,使用 OpenTelemetry 檢測您的應用程式。 選取索引標籤以取得特定語言的指示。

注意

.NET 涵蓋多個案例,包括傳統 ASP.NET、主控台應用程式、Windows Forms (WinForms) 等等。

必要條件

提示

如果您正從 Application Insights Classic API 遷移,請參閱我們的移轉文件

安裝用戶端程式庫

安裝最新的 Azure.Monitor.OpenTelemetry.AspNetCore NuGet 套件

dotnet add package Azure.Monitor.OpenTelemetry.AspNetCore 

修改您的應用程式

匯入 Azure.Monitor.OpenTelemetry.AspNetCore 命名空間、新增 OpenTelemetry,並將其設定為在 program.cs 類別中使用 Azure 監視器:

// Import the Azure.Monitor.OpenTelemetry.AspNetCore namespace.
using Azure.Monitor.OpenTelemetry.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

// Add OpenTelemetry and configure it to use Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();

var app = builder.Build();

app.Run();

從 Application Insights 資源複製連接字串

連接字串是唯一的,並指定 Azure 監視器 OpenTelemetry 發行版本傳送其收集的遙測的位置。

提示

如果您還沒有可以使用的 Application Insights 資源,請遵循本指南建立資源。 建議您建立新的資源,而不是使用現有的資源

若要複製連接字串:

  1. 移至 Application Insights 資源的 [概觀] 窗格。
  2. 尋找您的連接字串
  3. 暫留在連接字串上,選取「複製到剪貼簿」圖示。

此螢幕擷取畫面顯示 Application Insights 概觀和連接字串。

在您的環境中貼上連接字串

若要貼上連接字串,請從下列選項中進行選取:

重要

建議您只在本機開發和測試環境中透過程式碼設定連接字串。

針對生產環境,請使用環境變數或組態檔 (僅限 JAVA)。

  • 透過環境變數設定 - 建議

    使用您的連接字串取代下列命令中的 <Your connection string>

    APPLICATIONINSIGHTS_CONNECTION_STRING=<Your connection string>
    
  • 透過組態檔設定 - 僅限 JAVA

    建立名為 applicationinsights.json 的組態檔,並將其置於具有與 applicationinsights-agent-3.6.0.jar 下列內容的相同目錄下:

    {
      "connectionString": "<Your connection string>"
    }
    

    將上述 JSON 中的 <Your connection string> 取代為您的唯一連接字串

  • 透過程式碼設定 - 僅限 ASP.NET Core、Node.js 和 Python

    如需透過程式碼設定連接字串的範例,請參閱連接字串組態

注意

如果您在多個位置設定連接字串,則環境變數會依下列順序排列優先順序:

  1. 代碼
  2. 環境變數
  3. 組態檔

確認資料正在流動

執行您的應用程式,然後在 Azure 入口網站中開啟 Application Insights。 資料可能需要幾分鐘的時間才會顯示。

此螢幕擷取畫面顯示 Application Insights 的 [概觀] 索引標籤,其中醒目提示伺服器要求和伺服器回應時間。

Application Insights 現在已為您的應用程式啟用。 下列步驟是選擇性的,並允許進一步自訂。

重要

如果您有兩個以上的服務將遙測發出至相同的 Application Insights 資源,則必須設定雲端角色名稱,才能在應用程式對應上正確地代表服務。

在使用 Application Insights 檢測的過程中,我們會收集診斷資料並且傳送給 Microsoft。 此資料可協助我們執行及改善 Application Insights。 若要深入了解,請參閱在 Azure Application Insights 中的 Statsbeat

範例應用程式

Azure 監視器 OpenTelemetry 範例應用程式適用於所有支援的語言:

下一步