使用 Application Insights 撰寫程式碼來追蹤要求

Application Insights 必須追蹤對應用程式的要求,以在 Azure 入口網站中的 [效能] 頁面上提供應用程式的設定檔。 對於在已檢測的架構 (例如 ASP.NET 和 ASP.NET Core) 上建置的應用程式,Application Insights 可自動追蹤要求。

對於其他應用程式 (例如 Azure 雲端服務背景工作角色和 Azure Service Fabric 無狀態 API),您必須以程式碼告知 Application Insights 何處是您要求的開頭與結尾,藉以追蹤要求。 其後,要求遙測就會傳送至 Application Insights,您可在 [效能] 頁面上加以檢視。 系統會針對這些要求收集設定檔。

若要手動追蹤要求:

  1. 在應用程式存留期早期新增下列程式碼:

    using Microsoft.ApplicationInsights.Extensibility;
    ...
    // Replace with your own Application Insights instrumentation key.
    TelemetryConfiguration.Active.InstrumentationKey = "00000000-0000-0000-0000-000000000000";
    

    如需這個全域檢測金鑰設定的詳細資訊,請參閱搭配 Application Insights 使用 Service Fabric

  2. 針對您想要檢測的任何程式碼片段,在其周圍新增 StartOperation<RequestTelemetry>using 陳述式,如下列範例所示:

    using Microsoft.ApplicationInsights;
    using Microsoft.ApplicationInsights.DataContracts;
    ...
    var client = new TelemetryClient();
    ...
    using (var operation = client.StartOperation<RequestTelemetry>("Insert_Your_Custom_Event_Unique_Name"))
    {
      // ... Code I want to profile.
    }
    

    不支援在另一個 StartOperation<RequestTelemetry> 範圍內呼叫 StartOperation<RequestTelemetry>。 您可以改為在巢狀範圍中使用 StartOperation<DependencyTelemetry>。 例如:

    using (var getDetailsOperation = client.StartOperation<RequestTelemetry>("GetProductDetails"))
    {
    try
    {
      ProductDetail details = new ProductDetail() { Id = productId };
      getDetailsOperation.Telemetry.Properties["ProductId"] = productId.ToString();
    
      // By using DependencyTelemetry, 'GetProductPrice' is correctly linked as part of the 'GetProductDetails' request.
      using (var getPriceOperation = client.StartOperation<DependencyTelemetry>("GetProductPrice"))
      {
          double price = await _priceDataBase.GetAsync(productId);
          if (IsTooCheap(price))
          {
              throw new PriceTooLowException(productId);
          }
          details.Price = price;
      }
    
      // Similarly, note how 'GetProductReviews' doesn't establish another RequestTelemetry.
      using (var getReviewsOperation = client.StartOperation<DependencyTelemetry>("GetProductReviews"))
      {
          details.Reviews = await _reviewDataBase.GetAsync(productId);
      }
    
      getDetailsOperation.Telemetry.Success = true;
      return details;
    }
    catch(Exception ex)
    {
      getDetailsOperation.Telemetry.Success = false;
    
      // This exception gets linked to the 'GetProductDetails' request telemetry.
      client.TrackException(ex);
      throw;
    }
    }
    

注意

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

下一步

Application Insights Profiler 進行疑難排解。