你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

编写代码来使用 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";
    

    有关此全局检测密钥配置的详细信息,请参阅 Use Service Fabric with Application Insights(结合使用 Service Fabric 和 Application Insights)。

  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 进行故障排除。