教學課程:使用 Application Insights 監視和診斷 Service Fabric 上的 ASP.NET Core 應用程式

本教學課程是一個系列的第五部分。 其中會逐步說明設定步驟,以使用 Application Insights 來監視和診斷 Service Fabric 叢集上執行的 ASP.NET Core 應用程式。 我們將從教學課程第一部分建置 .NET Service Fabric 應用程式中所開發的應用程式收集遙測資料。

在教學課程系列的第四部分,您將了解如何:

  • 設定應用程式的 Application Insights
  • 收集回應遙測資料以追蹤服務之間以 HTTP 為基礎的通訊
  • 使用 Application Insights 中的應用程式對應功能
  • 使用 Application Insights API 新增自訂事件

在本教學課程系列中,您將了解如何:

必要條件

開始進行本教學課程之前:

下載投票應用程式範例

如果您未在本教學課程系列的第一部分中建置投票應用程式範例,可以下載它。 在命令視窗或終端機中,執行下列命令,將範例應用程式存放庫複製到本機電腦。

git clone https://github.com/Azure-Samples/service-fabric-dotnet-quickstart

設定 Application Insights 資源

Application Insights 是 Azure 的應用程式效能管理平台,也是 Service Fabric 建議的應用程式監視和診斷平台。

若要建立 Application Insights 資源,請瀏覽至 Azure 入口網站。 在左導覽功能表上選取 [建立資源],以開啟 Azure Marketplace。 選取 [監視 + 管理],然後按一下 [Application Insights]

Create new AI resource

現在,針對要建立之資源的屬性,您需要填寫必要資訊。 輸入適當的 [名稱]、[資源群組] 和 [訂用帳戶]。 設定未來部署 Service Fabric 叢集的目標 [位置]。 在本教學課程中,我們會將應用程式部署到本機叢集,因此 [位置] 欄位無關緊要。 [應用程式類型] 應該保留為「ASP.NET Web 應用程式」。

AI resource attributes

填寫必要資訊之後,請選取 [建立] 來佈建資源 - 需要大約一分鐘。

將 Application Insights 新增至應用程式的服務

以滑鼠右鍵按一下 [開始] 功能表中的 Visual Studio 圖示,然後選擇 [以系統管理員身分執行],使用較高的權限啟動 Visual Studio 2019。 選取 [檔案]>[開啟]>[專案/方案],並瀏覽至投票應用程式 (在教學課程的第一部分中建立,或透過 git 複製)。 開啟 Voting.sln。 如果系統提示您還原應用程式的 NuGet 套件,請選取 [是]

請遵循下列步驟來設定 VotingWeb 和 VotingData 服務的 Application Insights:

  1. 以滑鼠右鍵按一下服務名稱,然後選取 [新增] > [已連線的服務] > [使用 Application Insights 監視]

    Configure AI

注意

視專案類型而定,當您以滑鼠右鍵選取服務名稱時,您可能需要按一下 [新增] -> [Application Insights 遙測...]

  1. 選取開始使用

  2. 登入用於 Azure 訂用帳戶的帳戶,並選取您在其中建立 Application Insights 資源的訂用帳戶。 從 [資源] 下拉式清單中,在 [現有的 Application Insights 資源] 下尋找資源。 選取 [註冊] 將 Application Insights 新增至您的服務。

    Register AI

  3. 當快顯對話方塊完成動作後,按一下 [完成]

注意

務必對應用程式中的兩個服務都執行上述步驟,以完成設定應用程式的 Application Insights。 兩個服務都使用相同的 Application Insights 資源,以便查看服務之間的傳入和傳出要求和通訊。

將 Microsoft.ApplicationInsights.ServiceFabric.Native NuGet 新增至服務

Application Insights 有兩個 Service Fabric 特定的 NuGet,可依情節來使用。 其中一個用於 Service Fabric 的原生服務,另一個用於容器和客體可執行檔。 在此案例中,我們將使用 Microsoft.ApplicationInsights.ServiceFabric.Native NuGet 以深入了解它所提供的服務內容。 若要深入了解 Application Insights SDK 及 Service Fabric 特定的 NuGet 套件,請參閱 Microsoft Application Insights for Service Fabric

設定 NuGet 套件的步驟如下:

  1. 以滑鼠右鍵按一下 [方案總管] 頂端的 [方案 'Voting'],然後選取 [管理方案的 NuGet 套件...]
  2. 在 [NuGet - 方案] 視窗的頂端導覽功能表上,選取 [瀏覽],並勾選搜尋列旁邊的 [包含發行前版本] 方塊。

注意

如果在安裝 Application Insights 套件之前未預先安裝 Microsoft.ServiceFabric.Diagnostics.Internal 套件,您可能需要以類似方式安裝該套件

  1. 搜尋 Microsoft.ApplicationInsights.ServiceFabric.Native,然後選取適當的 NuGet 套件。

  2. 在右側,選取應用程式中兩個服務 (VotingWebVotingData) 旁邊的兩個核取方塊,然後選取 [安裝]AI sdk Nuget

  3. 選取所顯示 [檢閱變更] 對話方塊上的 [確定],然後選擇 [接受授權]。 這會完成將 NuGet 新增至服務。

  4. 您現在需要在兩個服務中設定遙測初始設定式。 若要這麼做,請開啟 VotingWeb.cs 和 VotingData.cs。 對這兩者執行下列兩個步驟:

    1. 在每個 <ServiceName>.cs 的頂端,於現有 using 陳述式之後新增下列兩個 using 陳述式:
    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.ApplicationInsights.ServiceFabric;
    
    1. 在兩個檔案中,於 CreateServiceInstanceListeners()CreateServiceReplicaListeners() 的巢狀 return 陳述式中,在宣告另一個單例服務的 ConfigureServices>services 之下,新增:
    .AddSingleton<ITelemetryInitializer>((serviceProvider) => FabricTelemetryInitializerExtension.CreateFabricTelemetryInitializer(serviceContext))
    

    這會將「服務內容」新增至您的遙測資料,讓您更充分了解 Application Insights 中的遙測資料來源。 VotingWeb.cs中的巢狀 return 陳述式看起來應該像這樣:

    return new WebHostBuilder()
        .UseKestrel()
        .ConfigureServices(
            services => services
                .AddSingleton<HttpClient>(new HttpClient())
                .AddSingleton<FabricClient>(new FabricClient())
                .AddSingleton<StatelessServiceContext>(serviceContext)
                .AddSingleton<ITelemetryInitializer>((serviceProvider) => FabricTelemetryInitializerExtension.CreateFabricTelemetryInitializer(serviceContext)))
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
        .UseUrls(url)
        .Build();
    

    同樣地,在 VotingData.cs 中,您應該會有:

    return new WebHostBuilder()
        .UseKestrel()
        .ConfigureServices(
            services => services
                .AddSingleton<StatefulServiceContext>(serviceContext)
                .AddSingleton<IReliableStateManager>(this.StateManager)
                .AddSingleton<ITelemetryInitializer>((serviceProvider) => FabricTelemetryInitializerExtension.CreateFabricTelemetryInitializer(serviceContext)))
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.UseUniqueServiceUrl)
        .UseUrls(url)
        .Build();
    

再次確認已在 VotingWeb.cs 和 VotingData.cs 中呼叫 UseApplicationInsights() 方法,如上所述。

注意

此範例應用程式會使用 HTTP 進行服務的通訊。 如果您使用服務遠端處理第 2 版開發應用程式,則您也必須依照前述作法,在相同的位置加入以下幾行程式碼

ConfigureServices(services => services
    ...
    .AddSingleton<ITelemetryModule>(new ServiceRemotingDependencyTrackingTelemetryModule())
    .AddSingleton<ITelemetryModule>(new ServiceRemotingRequestTrackingTelemetryModule())
)

此時,您已經準備好要部署應用程式。 選取頂端的 [開始] \(或 F5),Visual Studio 會建置並封裝應用程式、設定本機叢集,然後將應用程式部署到此叢集。

注意

如果您未安裝最新版的 .NET Core SDK,則可能收到建置錯誤。

完成應用程式部署後,請移至 localhost:8080,您應該可以看到「投票範例」單一頁面應用程式。 票選您喜歡的幾個不同項目,以建立一些樣本資料和遙測資料 - 我去吃甜點了!

AI sample votes

投下幾票之後,也請隨意「移除」一些投票選項。

在 Application Insights 中檢視遙測資料和應用程式對應

在 Azure 入口網站中瀏覽至您的 Application Insights 資源。

選取 [概觀],以回到資源的登陸頁面。 然後選取頂端的 [搜尋],可看到追蹤開始湧入。 經過幾分鐘,追蹤就會出現在 Application Insights 中。 如果沒有看到任何追蹤,請稍候片刻,然後按一下頂端的 [重新整理] 按鈕。 AI see traces

在 [搜尋] 視窗中向下捲動,就會看到 Application Insights 傳入的所有立即可用的遙測資料。 針對您在投票應用程式中執行的每個動作,應該會有一個從 VotingWeb 傳出的 PUT 要求 (PUT Votes/Put [name])、一個從 VotingData 傳入的 PUT 要求 (PUT VoteData/Put [name]),後面接著一對 GET 要求來重新整理所顯示的資料。 因為這些是 HTTP 要求,所以 localhost 上也會有 HTTP 的相依性追蹤。 以下是如何新增一張選票的範例畫面:

AI sample request trace

您可以選取其中一個追蹤,以檢視更多詳細資料。 關於 Application Insights 提供的要求,有一些很有用的資訊,包括「回應時間」和「要求 URL」。 此外,因為您已新增 Service Fabric 特定的 NuGet,在下方的「自訂資料」區段中,您也會看到應用程式在 Service Fabric 叢集環境中的相關資料。 這包括服務內容,可讓您查看要求來源的 PartitionIDReplicaId,在診斷應用程式的錯誤時更準確查明問題所在。

AI trace details

此外,您可以在 [概觀] 頁面的左側功能表上選取 [應用程式對應],或選取 [應用程式對應] 圖示,以導向至會顯示兩個連線服務的 [應用程式對應]。

Screenshot that highlights Application map in the left menu.

「應用程式對應」可協助您更充分了解應用程式拓撲,特別是當您開始新增多個一起運作的不同服務時。 另外也提供要求成功率的基本資料,還可協助您診斷失敗的要求,以查明可能出錯的地方。 若要深入了解使用應用程式對應,請參閱 Application Insights 中的應用程式對應

將自訂檢測新增至應用程式

雖然 Application Insights 提供許多立即可用的遙測資料,但建議您新增進一步的自訂檢測。 這可能是基於業務需求,或在應用程式出錯時為了改善診斷。 Application Insights 有一個 API 可內嵌自訂事件和計量,您可以在這裡深入了解此 API。

讓我們將一些自訂事件新增至 VoteDataController.cs (在 VotingData>Controllers 下),以追蹤基礎 votesDictionary 中何時新增和刪除選票。

  1. 在其他 using 陳述式的結尾新增 using Microsoft.ApplicationInsights;
  2. 在類別開頭,在建立 IReliableStateManager 下方宣告新的 TelemetryClientprivate TelemetryClient telemetry = new TelemetryClient();
  3. Put() 函式中,新增事件來確認已新增選票。 在交易完成之後,緊鄰在傳回的 OkResult 陳述式前面新增 telemetry.TrackEvent($"Added a vote for {name}");
  4. delete () 中,有一個 "if/else" 是以 votesDictionary 包含給定投票選項的選票為條件。
    1. if 陳述式中,在 await tx.CommitAsync() 後面新增事件來確認刪除選票:telemetry.TrackEvent($"Deleted votes for {name}");
    2. else 陳述式中,在 return 陳述式前面新增事件來指出刪除未發生:telemetry.TrackEvent($"Unable to delete votes for {name}, voting option not found");

以下示範 Put()Delete() 函式在新增事件之後可能的樣子:

// PUT api/VoteData/name
[HttpPut("{name}")]
public async Task<IActionResult> Put(string name)
{
    var votesDictionary = await this.stateManager.GetOrAddAsync<IReliableDictionary<string, int>>("counts");

    using (ITransaction tx = this.stateManager.CreateTransaction())
    {
        await votesDictionary.AddOrUpdateAsync(tx, name, 1, (key, oldvalue) => oldvalue + 1);
        await tx.CommitAsync();
    }

    telemetry.TrackEvent($"Added a vote for {name}");
    return new OkResult();
}

// DELETE api/VoteData/name
[HttpDelete("{name}")]
public async Task<IActionResult> Delete(string name)
{
    var votesDictionary = await this.stateManager.GetOrAddAsync<IReliableDictionary<string, int>>("counts");

    using (ITransaction tx = this.stateManager.CreateTransaction())
    {
        if (await votesDictionary.ContainsKeyAsync(tx, name))
        {
            await votesDictionary.TryRemoveAsync(tx, name);
            await tx.CommitAsync();
            telemetry.TrackEvent($"Deleted votes for {name}");
            return new OkResult();
        }
        else
        {
            telemetry.TrackEvent($"Unable to delete votes for {name}, voting option not found");
            return new NotFoundResult();
        }
    }
}

完成這些變更之後,請啟動應用程式,以建置和部署最新版本。 應用程式部署完成之後,請移至 localhost:8080,並新增和刪除一些投票選項。 然後,回到 Application Insights 資源,以查看最後一次執行的追蹤 (同樣地,追蹤需要 1-2 分鐘,才會出現在 Application Insights 中)。 針對您新增和刪除的所有選票,您現在應該會看到「自訂事件」\*及所有回應遙測資料。

custom events

下一步

在本教學課程中,您已了解如何:

  • 設定應用程式的 Application Insights
  • 收集回應遙測資料以追蹤服務之間以 HTTP 為基礎的通訊
  • 使用 Application Insights 中的應用程式對應功能
  • 使用 Application Insights API 新增自訂事件

現在您已設定好 ASP.NET 應用程式的監視和診斷,接著請嘗試: