编写代码以使用适用于 .NET 的 Application Insights Profiler 跟踪请求

Application Insights Profiler for .NET 仅捕获由 Application Insights 跟踪的请求的性能分析数据。 如果未跟踪请求,Profiler 将没有任何数据可以分析,并且Azure门户中的“性能”页上不会显示任何数据。

基于已检测的框架(如 ASP.NET 和 ASP.NET Core自动跟踪请求)构建的应用程序,因此不需要额外的代码。 其他应用程序(如Azure Service Fabric无状态 API)不会自行跟踪请求,因此必须手动检测它们,以便告知 Application Insights 每个请求的开始和结束位置。

本文介绍如何配置连接字符串、创建 RequestTelemetry 操作用于跟踪请求,以及使用 DependencyTelemetry 表示嵌套工作。

在代码中手动跟踪请求

若要在应用程序代码中手动跟踪请求,请执行以下操作:

  1. 在应用程序生命周期的早期添加以下代码:

    using Microsoft.ApplicationInsights.Extensibility;
    ...
    // Replace with your own Application Insights connection string.
    TelemetryConfiguration.Active.ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://<region>.in.applicationinsights.azure.cn/";
    

    有关此全局连接字符串配置的详细信息,请参阅 将 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<RequestTelemetry> 跟踪外部范围,并跟踪每个嵌套操作 StartOperation<DependencyTelemetry> ,以便嵌套操作正确链接到父请求。

在下面的示例中, GetProductDetails 建立请求遥测,而嵌套 GetProductPriceGetProductReviews 操作则使用 DependencyTelemetryTrackException 将任何异常链接到 GetProductDetails 请求:

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;
    }
}

后续步骤