為 ASP.NET Core 應用程式啟用 Application Insights

本文說明如何為部署為 Azure Web 應用程式的 ASP.NET Core 應用程式啟用 Application Insights。 此實作使用以 SDK 為基礎的方法。 您也可以使用 自動結構方法

Application Insights 可以從 ASP.NET Core 應用程式收集下列遙測:

  • Requests
  • 相依性
  • 例外狀況
  • 效能計數器
  • 活動訊號
  • 記錄

對於範例應用程式,我們將使用以 net6.0 為目標的 ASP.NET Core MVC 應用程式。 不過,您可以將這些指示套用至所有 ASP.NET Core 應用程式。 如果您正在使用背景工作服務,請使用 這裡的指示。

注意

針對檢測金鑰擷取的支援將在 2025 年 3 月 31 日結束。 檢測金鑰擷取將會繼續運作,但我們將不再提供該功能的更新或支援。 轉換至連接字串以利用新功能

支援的案例

ASP.NET Core 的 Application Insights SDK 可以監視應用程式,無論其執行位置或方式為何。 如果您的應用程式正在執行,並與 Azure 有網路連線,Application Insights 就可以從中收集遙測。 支援 .NET Core 的位置都支援 Application Insights 監視。 以下是支援的案例:

  • 作業系統:Windows、Linux 或 Mac
  • 裝載方法:同處理序或跨處理序
  • 部署方法:架構相依或獨立式
  • 網頁伺服器:Internet Information Server (IIS) 或 Kestrel
  • 裝載平台:Azure App Service、Azure VM、Docker、Azure Kubernetes Service (AKS) 等的 Web Apps 功能
  • .NET Core 版本:所有正式支援的 .NET Core 版本都未處於預覽狀態
  • IDE:Visual Studio、Visual Studio Code 或命令列

先決條件

若要完成本教學課程,您需要:

  • Visual Studio 2022
  • 下列 Visual Studio 工作負載:
    • ASP.NET 和 Web 開發
    • 資料儲存與處理
    • Azure 開發
  • .NET 6.0
  • Azure 訂用帳戶和使用者帳戶 (具備建立和刪除資源的能力)

部署 Azure 資源

請依照 指引,從 GitHub 存放庫部署範例應用程式。

為了替資源提供全域唯一的名稱,已指派六字元的尾碼給部分資源。 請記下此尾碼,以供本文後續使用。

Azure 入口網站中已部署的 Azure 資源清單螢幕擷取畫面,其中已醒目提示六字元的尾碼。

建立 Application Insights 資源

  1. Azure 入口網站中,選取 application-insights-azure-cafe 資源群組。

  2. 在頂端工具列功能表中,選取 [+ 建立]。

    Azure 入口網站中 application-insights-azure-cafe 資源群組的螢幕擷取畫面,其中已醒目提示工具列功能表上的 [+ 建立] 按鈕。

  3. 在 [建立資源] 畫面上,從 Marketplace 搜尋文字方塊中搜尋並選取 Application Insights

    在 Azure 入口網站中 [建立資源] 畫面的螢幕擷取畫面。

  4. 在 Application Insights 資源概觀畫面上,選取 [建立]。

    Azure 入口網站中 [Application Insights 概觀] 畫面的螢幕擷取畫面,其中已醒目提示 [建立] 按鈕。

  5. 在 Application Insights 畫面的 [基本] 索引標籤上,使用下列資料表完成表單,然後選取 [檢閱 + 建立] 按鈕。 未指定於下表中的欄位可保留其預設值。

    欄位
    名稱 輸入 azure-cafe-application-insights-{SUFFIX},將 {SUFFIX} 取代為先前記錄的適當尾碼值。
    區域 選取在部署文章資源時選擇的相同區域。
    Log Analytics 工作區 選取 [azure-cafe-log-analytics-workspace]。 或者,您可以建立新的記錄分析工作區。

    Azure 入口網站中 Application Insights 畫面的 [基本] 索引標籤螢幕擷取畫面,其中表單已填入上述值。

  6. 在驗證通過後,選取 [建立] 以部署資源。

    Azure 入口網站中 Application Insights 畫面的螢幕擷取畫面。已醒目提示指出已通過驗證的訊息和 [建立] 按鈕。

  7. 部署資源後,返回 application-insights-azure-cafe 資源群組,然後選取您部署的 Application Insights 資源。

    Azure 入口網站中 application-insights-azure-cafe 資源群組的螢幕擷取畫面,其中已醒目提示 Application Insights 資源。

  8. 在 Application Insights 資源的概觀畫面上,選取 [複製到剪貼簿] 按鈕,以複製連接字串值。 您將在本文的下一節中使用連接字串值。

    Azure 入口網站中 [Application Insights 概觀] 畫面的螢幕擷取畫面。

在 Web App Service 中設定 Application Insights 連接字串應用程式設定

  1. 返回 application-insights-azure-cafe 資源群組,並開啟 azure-cafe-web-{SUFFIX} App Service 資源。

    Azure 入口網站中 application-insights-azure-cafe 資源群組的螢幕擷取畫面,其中醒目提示 azure-cafe-web-{SUFFIX} 資源。

  2. 從左側功能表中的 [設定] 區段下,選取 [設定]。 然後,在 [應用程式設定] 索引標籤的 [應用程式設定] 底下,選取 [+ 新增應用程式設定]。

    在 Azure 入口網站中建立 App Service 的螢幕擷取畫面。

  3. 在 [新增/編輯應用程式] 設定窗格中,完成表單,如下所示,然後選取 [ 確定]。

    欄位
    名称 APPLICATIONINSIGHTS_CONNECTION_STRING
    貼上在上一節複製的 Application Insights 連接字串值。

    [新增/編輯應用程式] 設定窗格的螢幕擷取畫面,其中Azure 入口網站中填入 [名稱] 和 [值] 欄位中的上述值。

  4. 在 [App Service 設定] 畫面上,從工具列功能表中選取 [儲存] 按鈕。 在系統提示您儲存變更時,選取 [繼續]。

    Azure 入口網站中 [App Service 設定] 畫面的螢幕擷取畫面,其中工具列功能表上已醒目提示 [儲存] 按鈕。

安裝 Application Insights NuGet 套件

我們需要設定 ASP.NET Core MVC Web 應用程式以傳送遙測。 此作業可使用適用於 ASP.NET Core Web 應用程式的 Application Insights NuGet 套件來完成。

  1. 在 Visual Studio 中,開啟 1 - Starter Application\src\AzureCafe.sln

  2. 在 [Visual Studio 方案總管] 畫面中,以滑鼠右鍵按一下 AzureCafe 專案檔,然後選取 [管理 NuGet 套件]。

    Visual Studio 方案總管的螢幕擷取畫面,其中醒目提示已選取 Azure Cafe 專案並和 [管理 NuGet 套件] 捷徑功能表項目。

  3. 選取 [瀏覽] 索引標籤,然後搜尋 Microsoft.ApplicationInsights.AspNetCore 並加以選取。 選取 [安裝] 並接受授權條款。 建議您使用最新的穩定版本。 如需 SDK 的完整版本資訊,請參閱開放原始碼 GitHub 存放庫

    Visual Studio 中 NuGet 套件管理員使用者介面的螢幕擷取畫面。

    讓 Visual Studio 保持開啟,以供本文的下一節使用。

啟用 Application Insights 伺服器端遙測

適用於 ASP.NET Core Web 應用程式的 Application Insights NuGet 套件中封裝的功能,可將伺服器端遙測傳送至 Azure 中的 Application Insights 資源。

  1. 從 Visual Studio 方案總管,開啟 Program.cs 檔案。

    Visual Studio 方案總管的螢幕擷取畫面,其中已醒目提示 Program.cs 檔案。

  2. builder.Services.AddControllersWithViews() 陳述式前面插入下列程式碼。 此程式碼會自動從設定中讀取 Application Insights 連接字串值。 AddApplicationInsightsTelemetry 方法會將 ApplicationInsightsLoggerProvider 註冊到內建的相依性插入容器,然後該容器就會用來實現 ILoggerILogger<TCategoryName> 實作要求。

    builder.Services.AddApplicationInsightsTelemetry();
    

    Visual Studio 中程式碼視窗的螢幕擷取畫面,其中已醒目提示上述程式碼片段。

    提示

    深入了解 ASP.NET Core 中的設定選項

啟用 Web 應用程式的用戶端遙測

上述步驟足以協助您開始收集伺服器端遙測。 範例應用程式具有用戶端元件。 遵循後續步驟,以開始收集使用的遙測資料

  1. 在 Visual Studio 方案總管中,開啟 \Views\_ViewImports.cshtml

  2. 在現有檔案的結尾新增下列程式碼。

    @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
    

    Visual Studio 中 _ViewImports.cshtml 檔案的螢幕擷取畫面,其中已醒目提示前一行程式碼。

  3. 若要正確啟用應用程式的用戶端監視,請在 Visual Studio 方案總管 中,開啟 \Views\Shared\_Layout.cshtml,並緊接著在結尾 <\head> 標記之前插入下列程式碼。 您要監視之應用程式的每一頁 <head> 區段中,必須插入此 JavaScript 程式碼片段。

    @Html.Raw(JavaScriptSnippet.FullScript)
    

    Visual Studio 中 _Layout.cshtml 檔案的螢幕擷取畫面,其中已醒目提示檔案前端區段內的前一行程式碼。

    提示

    使用 FullScript 的替代方法是 ScriptBody。 如果您需要控制 <script> 標籤以設定內容安全性原則,請使用 ScriptBody

    <script> // apply custom changes to this script tag.
        @Html.Raw(JavaScriptSnippet.ScriptBody)
    </script>
    

注意

JavaScript 插入提供預設的設定體驗。 如果您需要設定連接字串以外的設定,您必須依照上述說明移除自動插入,並手動新增 JavaScript SDK

啟用資料庫查詢的監視

調查效能降低的原因時,請務必將資料庫呼叫的深入解析納入考量。 您可以藉由設定相依性模組來啟用監視。 依預設會啟用相依性監視,包括 SQL。

遵循下列步驟,以擷取完整的 SQL 查詢文字。

注意

SQL 文字可能包含敏感性資料,例如密碼和 PII。 啟用此功能時請多加留意。

  1. 從 Visual Studio 方案總管,開啟 Program.cs 檔案。

  2. 在檔案頂端新增下列 using 陳述式。

    using Microsoft.ApplicationInsights.DependencyCollector;
    
  3. 若要啟用 SQL 命令文字檢測,請緊接著在 builder.Services.AddApplicationInsightsTelemetry() 程式碼之後,插入下列程式碼。

    builder.Services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) => { module.EnableSqlCommandTextInstrumentation = true; });
    

    Visual Studio 中程式碼視窗的螢幕擷取畫面,其中已醒目提示上述程式碼。

執行 Azure Cafe Web 應用程式

部署 Web 應用程式程式碼之後,遙測將會流向 Application Insights。 Application Insights SDK 會自動收集傳入至應用程式的 Web 要求。

  1. 在 [Visual Studio 方案總管] 中,以滑鼠右鍵按一下 [AzureCafe] 專案,然後從捷徑功能表中,選取 [發佈]。

    Visual Studio 方案總管的螢幕擷取畫面,其中顯示已選取 Azure Cafe 專案並醒目提示 [發佈] 捷徑功能表項目。

  2. 選取 [發佈],將新程式碼升階至 Azure App Service。

    AzureCafe 發行設定檔的螢幕擷取畫面,其中醒目提示 [發佈] 按鈕。

    成功發佈 Azure Cafe Web 應用程式時,新的瀏覽器視窗會開啟至 Azure Cafe Web 應用程式。

    Azure Cafe Web 應用程式的螢幕擷取畫面。

  3. 若要產生一些遙測資料,請遵循 Web 應用程式中的下列步驟來新增檢閱。

    1. 若要檢視餐館的菜單和評論,請選取餐館旁的 [詳細資料]。

      Azure Cafe Web 應用程式中部分 Azure Cafe 清單的螢幕擷取畫面,其中醒目提示 [詳細資料] 按鈕。

    2. 若要檢視並新增評論,請在 [餐館] 畫面上選取 [評論] 索引標籤。選取 [新增評論] 按鈕以新增評論。

      螢幕擷取畫面:Azure Cafe Web 應用程式中的 [餐館詳細資料] 畫面,其中醒目提示 [新增評論] 按鈕。

    3. 在 [建立評價] 對話方塊中,為評價輸入名稱、評等、評論,並上傳相片。 完成之後,選取 [新增評論]。

      Azure Cafe Web 應用程式中 [建立評論] 對話方塊的螢幕擷取畫面。

    4. 如果您需要產生其他遙測,請新增其他評論。

即時計量

您可以使用即時計量,以快速驗證 Application Insights 監視是否設定正確。 即時計量會顯示近即時執行中處理序的 CPU 使用量。 其也可以顯示其他遙測,例如要求、相依性、追蹤等。 請注意,遙測資料可能需要幾分鐘,才會出現在入口網站和分析中。

檢視應用程式對應

範例應用程式會呼叫多項 Azure 資源,包括 Azure SQL、Azure Blob 儲存體和 Azure 語言服務 (用以評價情感分析)。

此圖顯示 Azure Cafe 範例 Web 應用程式的架構。

Application Insights 會檢查傳入的遙測資料,並且能夠為偵測到的系統整合產生視覺化對應。

  1. 登入 Azure 入口網站

  2. 開啟範例應用程式的資源群組,也就是 application-insights-azure-cafe

  3. 從資源清單中,選取 azure-cafe-insights-{SUFFIX} Application Insights 資源。

  4. 在左側功能表的 [調查] 標題底下,選取 [應用程式對應]。 觀察產生的應用程式對應。

    Azure 入口網站中 [Application Insights 應用程式對應] 畫面的螢幕擷取畫面。

檢視 HTTP 呼叫和資料庫 SQL 命令文字

  1. 在 Azure 入口網站中開啟 Application Insights 資源。

  2. 在左側功能表的 [調查] 標頭底下,選取 [效能]。

  3. [作業] 索引標籤包含應用程式所接收之 HTTP 呼叫的詳細資料。 若要在 [伺服器] 和 [瀏覽器] (用戶端) 檢視之間切換資料,請使用 [伺服器/瀏覽器] 切換。

    Azure 入口網站中 [效能] 畫面的螢幕擷取畫面。

  4. 從資料表中選取 [作業],然後選擇鑽研至要求的範例。

    Azure 入口網站中 [ Application Insights 效能] 畫面的螢幕擷取畫面,其中醒目提示列出的作業和範例作業。

    所選要求的端對端交易隨即顯示。 在此案例中,已建立評論 (包含影像),因此其包含對 Azure 儲存體、語言服務 (適用於情感分析) 的呼叫。 它也包含對 SQL Azure 的資料庫呼叫,以保存檢閱。 在此範例中,第一個選取的事件會顯示與 HTTP POST 呼叫相關的資訊。

    Azure 入口網站中端對端交易的螢幕擷取畫面,其中已選取 HTTP Post 呼叫。

  5. 選取 SQL 項目以檢閱對資料庫發出的 SQL 命令文字。

    Azure 入口網站中端對端交易的螢幕擷取畫面,其中包含 SQL 命令詳細資料。

  6. 選擇性地選取對 Azure 儲存體或語言服務的相依性 (傳出) 要求。

  7. 返回 [效能] 畫面,然後選取 [相依性] 索引標籤,以調查對外部資源的呼叫。 請注意,作業資料表包含對情感分析、Blob 儲存體和 Azure SQL 的呼叫。

    Azure 入口網站中 Application Insights 效能畫面的螢幕擷取畫面,其中已選取 [相依性] 索引標籤並醒目提示作業資料表。

使用 Application Insights 進行應用程式記錄

記錄概觀

Application Insights 是一種記錄提供者,在已安裝 ASP.NET Core 的 Application Insights NuGet 套件,且已啟用伺服器端遙測收集時,可供 ASP.NET Core 應用程式使用。

提醒您,Program.cs 中的下列程式碼會將 ApplicationInsightsLoggerProvider 註冊至內建的相依性插入容器。

builder.Services.AddApplicationInsightsTelemetry();

ApplicationInsightsLoggerProvider 註冊為記錄提供者後,應用程式即可藉由使用建構函式插入搭配 ILogger 或泛型類型替代 ILogger<TCategoryName>,以登入 Application Insights。

注意

根據預設,記錄提供者會設為自動擷取嚴重性為 LogLevel.Warning 或更高的記錄事件。

請考慮下列範例控制器。 其示範使用註冊至相依性插入容器的 ApplicationInsightsLoggerProvider 進行解析的 ILogger 插入,請加以考量。 觀察記錄資訊、警告和錯誤訊息的 Get 方法。

注意

依預設不會記錄資訊層級追蹤。 只會擷取警告和更高層級的訊息。

using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly ILogger _logger;

    public ValuesController(ILogger<ValuesController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        //Info level traces are not captured by default
        _logger.LogInformation("An example of an Info trace..");
        _logger.LogWarning("An example of a Warning trace..");
        _logger.LogError("An example of an Error level message");

        return new string[] { "value1", "value2" };
    }
}

如需詳細資訊,請參閱 ASP.NET Core 中的記錄

在 Application Insights 中檢視記錄

上述 ValuesController 是以範例應用程式部署的,位於專案的 Controllers 資料夾中。

  1. 使用網際網路瀏覽器,開啟範例應用程式。 在位址列中附加 /api/Values,然後按 Enter 鍵。

    瀏覽器視窗的螢幕擷取畫面,其中包含附加至位址列中 URL 的 /api/Values。

  2. Azure 入口網站中,稍後片刻,然後選取 azure-cafe-insights-{SUFFIX} Application Insights 資源。

    Azure 入口網站中 application-insights-azure-cafe 資源群組的螢幕擷取畫面,其中已醒目提示 Application Insights 資源。

  3. 在 Application Insights 資源的左側功能表中,從 [監視] 區段下方選取 [記錄]。

  4. 在 [資料表] 窗格的 Application Insights 樹狀目錄下,連按兩下追蹤資料表。

  5. 依照下列方式修改查詢以擷取 [值] 控制器的追蹤,然後選取 [執行] 以篩選結果。

    traces 
    | where operation_Name == "GET Values/Get"
    

    結果會顯示控制器中存在的記錄訊息。 記錄嚴重性為 2 表示警告層級,記錄嚴重性為 3 則表示錯誤層級。

  6. 或者,您也可以撰寫查詢,以根據記錄的類別擷取結果。 根據預設,類別是插入 ILogger 之類別的完整名稱。 在此情況下,類別名稱為 ValuesController (如果有與類別相關聯的命名空間,該名稱前面會加上命名空間)。 重新寫入並執行下列查詢,以根據類別擷取結果。

    traces 
    | where customDimensions.CategoryName == "ValuesController"
    

控制傳送至 Application Insights 的記錄層級

ILogger 實作有內建機制可套用記錄篩選。 此篩選可讓您控制傳送給每個已註冊提供者的記錄,包括 Application Insights 提供者。 您可以在設定 (使用 appsettings.json 檔案) 或程式碼中使用篩選。 如需記錄層級的詳細資訊和適當使用方法的指引,請參閱記錄層級文件。

下列範例說明如何將篩選規則套用至 ApplicationInsightsLoggerProvider,以控制傳送至 Application Insights 的記錄層級。

透過設定建立篩選規則

ApplicationInsightsLoggerProvider 在設定中會具有別名 ApplicationInsightsappsettings.json 檔案的下列區段會將所有提供者的預設記錄層級設定為 LogLevel.Warning。 以 "ValuesController" 開頭的類別專用的 ApplicationInsights 提供者設定,會將此預設值覆寫為 LogLevel.Error 或更高。

{
  //... additional code removed for brevity
  "Logging": {
    "LogLevel": { // No provider, LogLevel applies to all the enabled providers.
      "Default": "Warning"
    },
    "ApplicationInsights": { // Specific to the provider, LogLevel applies to the Application Insights provider.
      "LogLevel": {
        "ValuesController": "Error" //Log Level for the "ValuesController" category
      }
    }
  }
}

使用 appsettings.json 中的上述程式碼部署範例應用程式,只會產生在與 ValuesController 互動時傳送至 Application Insights 的錯誤追蹤。 這是因為 ValuesController 類別的 LogLevel 設定為 [錯誤]。 因此,會隱藏 [警告]追蹤。

關閉 Application Insights 的記錄

若要使用設定來停用記錄,請將所有 LogLevel 值設定為 [無]。

{
  //... additional code removed for brevity
  "Logging": {
    "LogLevel": { // No provider, LogLevel applies to all the enabled providers.
      "Default": "None"
    },
    "ApplicationInsights": { // Specific to the provider, LogLevel applies to the Application Insights provider.
      "LogLevel": {
        "ValuesController": "None" //Log Level for the "ValuesController" category
      }
    }
  }
}

同樣地,在程式碼中,將 ApplicationInsightsLoggerProvider 的預設層級和任何後續的記錄層級設定為 [無]。

var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.None);
builder.Logging.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>("ValuesController", LogLevel.None);

開放原始碼 SDK

如需最新的更新和 Bug 修正,請參閱版本資訊

下一步