您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

在 Application Insights 中采样Sampling in Application Insights

采样是 Azure Application Insights 中的一项功能。Sampling is a feature in Azure Application Insights. 建议用于降低遥测流量和存储,同时保留采用统计方式的应用程序数据的正确分析。It is the recommended way to reduce telemetry traffic and storage, while preserving a statistically correct analysis of application data. 筛选器会选择相关项,以便可以在执行诊断调查时在不同项之间导航。The filter selects items that are related, so that you can navigate between items when you are doing diagnostic investigations. 当指标计数显示在门户中时,它们会重新规范化以考虑到采样。When metric counts are presented in the portal, they are renormalized to take into account sampling. 这样可以尽量减轻对统计的影响。Doing so minimizes any effect on the statistics.

采样可以降低流量和数据成本,并可帮助用户避免限制。Sampling reduces traffic and data costs, and helps you avoid throttling.

简单地说:In brief:

  • 采样会保留 n 条记录中的 1 条并丢弃其余记录。Sampling retains 1 in n records and discards the rest. 例如,它可能会保留 5 个事件中的 1 个,采样率为 20%。For example, it might retain one in five events, a sampling rate of 20%.
  • 默认情况下,已在所有最新版本的 ASP.NET 和 ASP.NET Core 软件开发工具包 (SDK) 中启用自适应采样。Adaptive Sampling is enabled by default in all the latest version of ASP.NET and ASP.NET Core Software Development Kits (SDKs).
  • 也可以手动设置采样。You can also set sampling manually. 可以在门户中的“用量和估算费用页”上、在 ASP.NET SDK 的 ApplicationInsights.config 中、在 ASP.NET Core SDK 中通过代码,或者在 Java SDK 的 ApplicationInsights.xml 文件中进行相关的配置。 This can be configured in the portal on the Usage and estimated costs page, in the ASP.NET SDK in the ApplicationInsights.config file, in the ASP.NET Core SDK via code or in the Java SDK in the ApplicationInsights.xml file.
  • 如果记录自定义事件,并需要确保事件集一同保留或一同丢弃,则事件必须具有相同的 OperationId 值。If you log custom events and need to ensure that a set of events is retained or discarded together, the events must have the same OperationId value.
  • 采样除数 n 会在每个记录的属性 itemCount 中报告,在“搜索”中它出现在友好名称“请求计数”或“事件计数”下。The sampling divisor n is reported in each record in the property itemCount, which in Search appears under the friendly name "request count" or "event count". 如果采样未运行,则 itemCount==1itemCount==1when sampling is not in operation.
  • 如果要编写分析查询,应考虑采样If you write Analytics queries, you should take account of sampling. 特别是,应使用 summarize sum(itemCount),而不是仅对记录进行计数。In particular, instead of simply counting records, you should use summarize sum(itemCount).

采样类型Types of sampling

有三种备用采样方法:There are three alternative sampling methods:

  • 自适应采样自动调整从 ASP.NET/ASP.NET Core 应用的 SDK 所发送的遥测量。Adaptive sampling automatically adjusts the volume of telemetry sent from the SDK in your ASP.NET/ASP.NET Core app. 这是 ASP.NET Web SDK v 2.0.0-beta3 及更高版本和 Microsoft.ApplicationInsights.AspNetCore SDK v 2.2.0-beta1 及更高版本的默认采样方法。This is the default sampling from ASP.NET Web SDK v 2.0.0-beta3 onwards and Microsoft.ApplicationInsights.AspNetCore SDK v 2.2.0-beta1 onwards. 自适应采样目前仅适用于 ASP.NET 服务器端遥测。Adaptive sampling is currently only available for ASP.NET server-side telemetry.

  • 固定速率采样会减少从 ASP.NET、ASP.NET Core 或 Java 服务器和用户浏览器发送的遥测量。Fixed-rate sampling reduces the volume of telemetry sent from both your ASP.NET or ASP.NET Core or Java server and from your users' browsers. 用户设定速率。You set the rate. 客户端和服务器将同步其采样,以便在“搜索”中可以在多个相关页面视图和请求之间导航。The client and server will synchronize their sampling so that, in Search, you can navigate between related page views and requests.

  • 引入采样在 Azure 门户中正常工作。Ingestion sampling Works in the Azure portal. 它会以设置的采样率丢弃一些来自应用的遥测数据。It discards some of the telemetry that arrives from your app, at a sampling rate that you set. 它不会减少应用发送的遥测流量,但可帮助保持在每月配额内。It doesn't reduce telemetry traffic sent from your app, but helps you keep within your monthly quota. 引入采样的大优点是,无需重新部署应用就可设置它。The main advantage of ingestion sampling is that you can set the sampling rate without redeploying your app. 引入采样统一适用于所有服务器和客户端。Ingestion sampling works uniformly for all servers and clients.

如果自适应采样或固定速率采样正在运行,将禁用引入采样。If Adaptive or Fixed rate sampling are in operation, Ingestion sampling is disabled.

ASP.NET/ASP.NET Core Web 应用程序中的自适应采样Adaptive sampling in your ASP.NET/ASP.NET Core Web Applications

自适应采样适用于 Application Insights SDK for ASP.NET v 2.0.0-beta3 及更高版本、Microsoft.ApplicationInsights.AspNetCore SDK v 2.2.0-beta1 及更高版本,默认已启用。Adaptive sampling is available for the Application Insights SDK for ASP.NET v 2.0.0-beta3 and later, Microsoft.ApplicationInsights.AspNetCore SDK v 2.2.0-beta1 and later, and is enabled by default.

自适应采样会影响从 Web 服务器应用发送至 Application Insights 服务终结点的遥测量。Adaptive sampling affects the volume of telemetry sent from your web server app to the Application Insights service endpoint. 遥测量会自动调整以保持在指定的最大流量率,可通过 MaxTelemetryItemsPerSecond 设置对其进行控制。The volume is adjusted automatically to keep within a specified maximum rate of traffic, and is controlled via the setting MaxTelemetryItemsPerSecond. 如果应用程序将生成较低的遥测数,如调试时由于低使用率,项不会删除或采样处理器,只要卷低于MaxTelemetryItemsPerSecondIf the application produces a low amount of telemetry, such as when debugging or due to low usage, items won't be dropped by the sampling processor as long as volume is below MaxTelemetryItemsPerSecond. 随着遥测数据量的增加,采样率将会调整以实现目标量。As the volume of telemetry increases, sampling rate is adjusted so as to achieve the target volume.

为了实现目标量,一些生成的遥测会被丢弃。To achieve the target volume, some of the generated telemetry is discarded. 但与其他类型的采样一样,该算法会保留相关的遥测项。But like other types of sampling, the algorithm retains related telemetry items. 例如,在“搜索”中检查遥测数据时,可以查找与特定异常相关的请求。For example, when you're inspecting the telemetry in Search, you'll be able to find the request related to a particular exception.

诸如请求速率和异常率等指标计数将进行调整以补偿采样率,以便它们在指标资源管理器中能够显示大约正确的值。Metric counts such as request rate and exception rate are adjusted to compensate for the sampling rate, so that they show approximately correct values in Metric Explorer.

配置 ASP.NET 应用程序的自适应采样Configuring adaptive sampling for ASP.NET Applications

了解如何配置 ASP.NET Core 应用程序的自适应采样。Learn about configuring adaptive sampling for ASP.NET Core Applications.

ApplicationInsights.config 中,可以调整 AdaptiveSamplingTelemetryProcessor 节点中的多个参数。In ApplicationInsights.config, you can adjust several parameters in the AdaptiveSamplingTelemetryProcessor node. 显示的数字是默认值:The figures shown are the default values:

  • <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>

    自适应算法的目标速率旨在针对每个服务器主机The target rate that the adaptive algorithm aims for on each server host. 如果在多台主机上运行 Web 应用,应减小此值以保留在 Application Insights 门户的目标流量速率以内。If your web app runs on many hosts, reduce this value so as to remain within your target rate of traffic at the Application Insights portal.

  • <EvaluationInterval>00:00:15</EvaluationInterval>

    会重新评估当前遥测速率的间隔。The interval at which the current rate of telemetry is reevaluated. 评估以移动平均线形式进行执行。Evaluation is performed as a moving average. 可能想要缩短此间隔(如果遥测很容易就激增)。You might want to shorten this interval if your telemetry is liable to sudden bursts.

  • <SamplingPercentageDecreaseTimeout>00:02:00</SamplingPercentageDecreaseTimeout>

    当采样百分比值更改时,多久后我们可以再次降低采样百分比以便捕获更少数据。When sampling percentage value changes, how soon after are we allowed to lower sampling percentage again to capture less data.

  • <SamplingPercentageIncreaseTimeout>00:15:00</SamplingPercentageIncreaseTimeout>

    当采样百分比值更改时,多久后我们可以再次增加采样百分比以便捕获更多数据。When sampling percentage value changes, how soon after are we allowed to increase sampling percentage again to capture more data.

  • <MinSamplingPercentage>0.1</MinSamplingPercentage>

    随着采样百分比的变化,我们可以设置的最小值是多少。As sampling percentage varies, what is the minimum value we're allowed to set.

  • <MaxSamplingPercentage>100.0</MaxSamplingPercentage>

    随着采样百分比的变化,我们可以设置的最大值是多少。As sampling percentage varies, what is the maximum value we're allowed to set.

  • <MovingAverageRatio>0.25</MovingAverageRatio>

    在移动平均线的计算中,权重分配给最新的值。In the calculation of the moving average, the weight assigned to the most recent value. 使用等于或小于 1 的值。Use a value equal to or less than 1. 较小的值会使算法不易受突然的更改影响。Smaller values make the algorithm less reactive to sudden changes.

  • <InitialSamplingPercentage>100</InitialSamplingPercentage>

    当应用已启动时分配的值。The value assigned when the app has just started. 不要在调试时减小值。Don't reduce value while you're debugging.

  • <ExcludedTypes>Trace;Exception</ExcludedTypes>

    不要采样的分号分隔类型列表。A semi-colon delimited list of types that you do not want to be sampled. 已识别的类型包括:Dependency、Event、Exception、PageView、Request、Trace。Recognized types are: Dependency, Event, Exception, PageView, Request, Trace. 指定类型的所有实例都会传输;对未指定的类型进行采样。All instances of the specified types are transmitted; the types that are not specified are sampled.

  • <IncludedTypes>Request;Dependency</IncludedTypes>

    要采样的分号分隔类型列表。A semi-colon delimited list of types that you want to be sampled. 已识别的类型包括:Dependency、Event、Exception、PageView、Request、Trace。Recognized types are: Dependency, Event, Exception, PageView, Request, Trace. 将对指定的类型进行采样;其他类型的所有实例始终都会传输。The specified types are sampled; all instances of the other types will always be transmitted.

若要关闭自适应采样,请从 applicationinsights-config 中删除 AdaptiveSamplingTelemetryProcessor 节点。To switch off adaptive sampling, remove the AdaptiveSamplingTelemetryProcessor node(s) from applicationinsights-config.

备选: 在代码中配置自适应采样Alternative: configure adaptive sampling in code

除了在 .config 文件中设置采样参数以外,还可以编程方式设置这些值。Instead of setting the sampling parameter in the .config file, you can programmatically set these values.

  1. 从 .config 文件中删除所有 AdaptiveSamplingTelemetryProcessor 节点。Remove all the AdaptiveSamplingTelemetryProcessor node(s) from the .config file.
  2. 使用以下代码片段来配置自适应采样。Use the following snippet to configure Adaptive Sampling.

C#C#


    using Microsoft.ApplicationInsights;
    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.ApplicationInsights.WindowsServer.Channel.Implementation;
    using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
    ...

    var builder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder;
    // If you are on ApplicationInsights SDK v 2.8.0-beta2 or higher, use the following line instead
    // var builder = TelemetryConfiguration.Active.DefaultTelemetrySink.TelemetryProcessorChainBuilder;

    // Enable AdaptiveSampling so as to keep overall telemetry volume to 5 items per second.
    builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5);

    // If you have other telemetry processors:
    builder.Use((next) => new AnotherProcessor(next));

    builder.Build();

了解遥测处理器。)(Learn about telemetry processors.)

也可以单独调整每个遥测类型的采样率,甚至可以完全排除特定类型的采取。You can also adjust the sampling rate for each Telemetry type individually, or can even exclude certain types from being sampled at all.

C#C#

    // The following configures adaptive sampling with 5 items per second, and also excludes DependencyTelemetry from being subject to sampling.
    builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5, excludedTypes: "Dependency");

配置 ASP.NET Core 应用程序的自适应采样。Configuring adaptive sampling for ASP.NET Core Applications.

ASP.NET Core 应用程序没有 ApplicationInsights.Config,因此每项配置都是通过代码完成的。There is no ApplicationInsights.Config for ASP.NET Core Applications, so every configuration is done via code. 默认情况下会为所有 ASP.NET Core 应用程序启用自适应采样。Adaptive sampling is enabled by default for all ASP.NET Core applications. 你可以禁用或自定义采样行为。You can disable or customize the sampling behavior.

禁用自适应采样Turning off Adaptive Sampling

添加 Application Insights 服务时,可以在 Startup.cs 文件中的方法 ConfigureServices 内使用 ApplicationInsightsServiceOptions 来禁用默认采样功能:The default sampling feature can be disabled while adding Application Insights service, in the method ConfigureServices, using ApplicationInsightsServiceOptions within the Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    // ...

    var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();
    aiOptions.EnableAdaptiveSampling = false;
    services.AddApplicationInsightsTelemetry(aiOptions);
    //...
}

上面的代码将禁用采样功能。The above code will disable sampling feature. 可以执行以下步骤使用更多自定义选项来添加采样。Follow the steps below to add sampling with more customization options.

配置采样设置Configure Sampling settings

如下所示使用 TelemetryProcessorChainBuilder 的扩展方法来自定义采样行为。Use extension methods of TelemetryProcessorChainBuilder as shown below to customize sampling behavior.

重要

如果使用此方法来配置采样,请确保将 aiOptions.EnableAdaptiveSampling = false; 设置与 AddApplicationInsightsTelemetry() 配合使用。If you use this method to configure sampling, please make sure to use aiOptions.EnableAdaptiveSampling = false; settings with AddApplicationInsightsTelemetry().

public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelemetryConfiguration configuration)
{
    var builder = configuration.TelemetryProcessorChainBuilder;
    // version 2.5.0-beta2 and above should use the following line instead of above. (https://github.com/Microsoft/ApplicationInsights-aspnetcore/blob/develop/CHANGELOG.md#version-250-beta2)
    // var builder = configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder;

    // Using adaptive sampling
    builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5);

    // Alternately, the following configures adaptive sampling with 5 items per second, and also excludes DependencyTelemetry from being subject to sampling.
    // builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5, excludedTypes: "Dependency");

    builder.Build();

    // If you have other telemetry processors:
    builder.Use((next) => new AnotherProcessor(next));
    // ...
}

如果使用上面的方法来配置采样,请确保将 aiOptions.EnableAdaptiveSampling = false; 设置与 AddApplicationInsightsTelemetry() 配合使用。If using the above method to configure sampling, make sure to use aiOptions.EnableAdaptiveSampling = false; settings with AddApplicationInsightsTelemetry().

ASP.NET、ASP.NET Core 和 Java 网站的固定速率采样Fixed-rate sampling for ASP.NET, ASP.NET Core, and Java websites

固定速率采样会减少从 Web 服务器和 Web 浏览器发送的流量。Fixed rate sampling reduces the traffic sent from your web server and web browsers. 与自适应采样不同,它会按用户确定的固定速率来降低遥测。Unlike adaptive sampling, it reduces telemetry at a fixed rate decided by you. 它还将同步客户端和服务器采样,以便保留相关项,例如,如果在“搜索”中查看页面视图,可以查找其相关的请求。It also synchronizes the client and server sampling so that related items are retained - for example, when you look at a page view in Search, you can find its related request.

与其他采样方法一样,此方法也会保留相关的项。Like other sampling techniques, this also retains related items. 对于每个 HTTP 请求事件,请求和相关的事件会一起被丢弃或传输。For each HTTP request event, the request and its related events are either discarded or transmitted together.

在指标资源管理器中,诸如请求和异常计数等速率将乘以某个系数来补偿采样率,以便它们大致正确。In Metrics Explorer, rates such as request and exception counts are multiplied by a factor to compensate for the sampling rate, so that they are approximately correct.

使用 ASP.NET 配置固定速率采样Configuring fixed-rate sampling in ASP.NET

  1. 禁用自适应采样:在 ApplicationInsights.config 中,删除或注释掉 AdaptiveSamplingTelemetryProcessor 节点。Disable adaptive sampling: In ApplicationInsights.config, remove or comment out the AdaptiveSamplingTelemetryProcessor node.

    
    <TelemetryProcessors>
    
    <!-- Disabled adaptive sampling:
      <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
        <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
      </Add>
    -->
    
  2. 启用固定速率采样模块。Enable the fixed-rate sampling module. 将以下片段添加到 ApplicationInsights.configAdd this snippet to ApplicationInsights.config:

    
    <TelemetryProcessors>
     <Add  Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.SamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
    
      <!-- Set a percentage close to 100/N where N is an integer. -->
     <!-- E.g. 50 (=100/2), 33.33 (=100/3), 25 (=100/4), 20, 1 (=100/100), 0.1 (=100/1000) -->
      <SamplingPercentage>10</SamplingPercentage>
      </Add>
    </TelemetryProcessors>
    
    

    备选:启用服务器代码中的固定速率采样Alternative: enable fixed-rate sampling in your server code

    除了在 .config 文件中设置采样参数以外,还可以编程方式设置这些值。Instead of setting the sampling parameter in the .config file, you can programmatically set these values.

C#C#


    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
    ...

    var builder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder;
    // If you are on ApplicationInsights SDK v 2.8.0-beta2 or higher, use the following line instead
    // var builder = TelemetryConfiguration.Active.DefaultTelemetrySink.TelemetryProcessorChainBuilder;

    builder.UseSampling(10.0); // percentage

    // If you have other telemetry processors:
    builder.Use((next) => new AnotherProcessor(next));

    builder.Build();

了解遥测处理器。)(Learn about telemetry processors.)

在 ASP.NET Core 中配置固定速率采样Configuring fixed-rate sampling in ASP.NET Core

  1. 禁用自适应采样:可以在 ConfigureServices 方法中使用 ApplicationInsightsServiceOptions 进行更改:Disable adaptive sampling: Changes can be made in the method ConfigureServices, using ApplicationInsightsServiceOptions:

    public void ConfigureServices(IServiceCollection services)
    {
    // ...
    
        var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions();
        aiOptions.EnableAdaptiveSampling = false;
        services.AddApplicationInsightsTelemetry(aiOptions);
    //...
    }
    
  2. 启用固定速率采样模块。Enable the fixed-rate sampling module. 可以在方法 Configure 中进行更改,如以下代码片段中所示:Changes can be made in the method Configure as shown in below snippet:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        var configuration = app.ApplicationServices.GetService<TelemetryConfiguration>();
    
        var builder = configuration.TelemetryProcessorChainBuilder;
        // version 2.5.0-beta2 and above should use the following line instead of above. (https://github.com/Microsoft/ApplicationInsights-aspnetcore/blob/develop/CHANGELOG.md#version-250-beta2)
        // var builder = configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder;
    
        // Using fixed rate sampling   
        double fixedSamplingPercentage = 10;
        builder.UseSampling(fixedSamplingPercentage);
    
        builder.Build();
    
        // ...
    }
    
    

使用 JAVA 配置固定速率采样Configuring fixed-rate sampling in JAVA

  1. 使用最新的 Application Insights Java SDK下载并配置 Web 应用程序Download and configure your web application with latest application insights java SDK

  2. 通过将下面的代码片段添加到 ApplicationInsights.xml 文件,启用固定速率采样模块 。Enable the fixed-rate sampling module by adding the following snippet to ApplicationInsights.xml file.

        <TelemetryProcessors>
            <BuiltInProcessors>
                <Processor type = "FixedRateSamplingTelemetryProcessor">
                    <!-- Set a percentage close to 100/N where N is an integer. -->
                    <!-- E.g. 50 (=100/2), 33.33 (=100/3), 25 (=100/4), 20, 1 (=100/100), 0.1 (=100/1000) -->
                    <Add name = "SamplingPercentage" value = "50" />
                </Processor>
            </BuiltInProcessors>
        </TelemetryProcessors>
    
  3. 可以使用处理器标记“FixedRateSamplingTelemetryProcessor”中的以下标记,在采样中包括或排除特定类型的遥测You can Include or Exclude specific types of telemetry from Sampling using the following tags inside the Processor tag "FixedRateSamplingTelemetryProcessor"

        <ExcludedTypes>
            <ExcludedType>Request</ExcludedType>
        </ExcludedTypes>
    
        <IncludedTypes>
            <IncludedType>Exception</IncludedType>
        </IncludedTypes>
    

可以在采样中包含或排除的遥测类型是:Dependency、Event、Exception、PageView、Request 和 Trace。The telemetry types that can be included or excluded from sampling are: Dependency, Event, Exception, PageView, Request, and Trace.

备注

对于采样百分比,请选择一个接近于 100/N 的百分比,其中 N 是整数。For the sampling percentage, choose a percentage that is close to 100/N where N is an integer. 当前采样不支持其他值。Currently sampling doesn't support other values.

引入采样Ingestion sampling

当来自 Web 服务器、浏览器和设备的遥测达到 Application Insights 服务终结点时,将运行此采样形式。This form of sampling operates at the point where the telemetry from your web server, browsers, and devices reaches the Application Insights service endpoint. 尽管它未减少从应用发送的遥测流量,但它确实减少了由 Application Insights 处理和保留(并收费)的遥测量。Although it doesn't reduce the telemetry traffic sent from your app, it does reduce the amount processed and retained (and charged for) by Application Insights.

如果应用经常超过其每月配额,且没有使用任一种基于 SDK 的采样类型的选项,请使用此种类型的采样。Use this type of sampling if your app often goes over its monthly quota and you don't have the option of using either of the SDK-based types of sampling.

在“使用情况和预估成本”页面中设置采样率:Set the sampling rate in the Usage and estimated costs page:

从应用程序“概述”边栏选项卡中,依次单击“设置”、“配额”、“示例”,选择采样率,并单击“更新”。

与其他类型的采样一样,该算法会保留相关的遥测项。Like other types of sampling, the algorithm retains related telemetry items. 例如,在“搜索”中检查遥测数据时,可以查找与特定异常相关的请求。For example, when you're inspecting the telemetry in Search, you'll be able to find the request related to a particular exception. 诸如请求速率和异常率等指标计数会正确保留。Metric counts such as request rate and exception rate are correctly retained.

被采样丢弃的数据点将无法在任何 Application Insights 功能(如连续导出)中使用。Data points that are discarded by sampling are not available in any Application Insights feature such as Continuous Export.

当运行基于 SDK 的自适应采样或固定速率采样时,不会运行引入采样。Ingestion sampling doesn't operate while SDK-based adaptive or fixed-rate sampling is in operation. 如果在 Visual Studio 或 Azure Web 应用扩展中或者使用状态监视器启用了 ASP.NET/ASP.NET Core SDK 并且禁用了引入采样,则默认会启用自适应采样。Adaptive sampling is enabled by default when ASP.NET/ASP.NET Core SDK is enabled in Visual Studio or enabled in Azure Web App extensions or by using Status Monitor, and ingestion sampling is disabled. 如果 SDK 中的采样率小于 100%(即If the sampling rate at the SDK is less than 100% (i.e 正在对项采样),则忽略设置的引入采样率。items are being sampled) then the ingestion sampling rate that you set is ignored.

警告

磁贴上显示的值指示为引入采样所设定的值。The value shown on the tile indicates the value that you set for ingestion sampling. 如果 SDK 采样不在运行,它并不表示实际采样率。It doesn't represent the actual sampling rate if SDK sampling is in operation.

使用 JavaScript 的网页采样Sampling for web pages with JavaScript

可以针对任何服务器中的固定速率采样配置网页。You can configure web pages for fixed-rate sampling from any server.

为 Application Insights 配置网页时,修改从 Application Insights 门户获取的 JavaScript 代码片段。When you configure the web pages for Application Insights, modify the JavaScript snippet that you get from the Application Insights portal. (在 ASP.NET 应用中,代码段通常出现在 _Layout.cshtml 中。)在检测密钥前插入类似于 samplingPercentage: 10, 的行:(In ASP.NET apps, the snippet typically goes in _Layout.cshtml.) Insert a line like samplingPercentage: 10, before the instrumentation key:

<script>
var appInsights= ... 
}({ 


// Value must be 100/N where N is an integer.
// Valid examples: 50, 25, 20, 10, 5, 1, 0.1, ...
samplingPercentage: 10, 

instrumentationKey:...
}); 

window.appInsights=appInsights; 
appInsights.trackPageView(); 
</script> 

对于采样百分比,请选择一个接近于 100/N 的百分比,其中 N 是整数。For the sampling percentage, choose a percentage that is close to 100/N where N is an integer. 当前采样不支持其他值。Currently sampling doesn't support other values.

如果还在服务器上启用了固定速率采样,客户端和服务器将同步,以便在“搜索”中可以在多个相关页面视图和请求之间导航。If you also enable fixed-rate sampling at the server, the clients and server will synchronize so that, in Search, you can navigate between related page views and requests.

何时使用采样?When to use sampling?

最新的 .NET 和.NET Core SDK 中已自动启用自适应采样。Adaptive sampling is automatically enabled in latest .NET and .NET Core SDKs. 无论使用何种 SDK 版本,都可以启用引入采样,以允许 Application Insights 对收集的数据采样。Regardless of which version of the SDK you use, you can enable ingestion sampling to allow Application Insights to sample the collected data.

默认情况下,Java SDK 中不启用任何采样。By default no sampling is enabled in Java SDK. 目前,它仅支持固定速率采样。Currently, it only supports Fixed Rate Sampling. Java SDK 不支持自适应采样。Adaptive Sampling is not supported in Java SDK.

一般情况下,对于大多数小型和中型应用程序,不需要采样。In general, for most small and medium size applications you don’t need sampling. 通过收集所有用户活动的数据,获取最有用的诊断信息和最准确的统计。The most useful diagnostic information and most accurate statistics are obtained by collecting data on all your user activities.

采样的主要优势在于:The main advantages of sampling are:

  • 当应用以短时间间隔发送速率很高的遥测时,Application Insights 服务会删除(“限制”)数据点。Application Insights service drops ("throttles") data points when your app sends a very high rate of telemetry in short time interval.
  • 保持在定价层的数据点配额以内。To keep within the quota of data points for your pricing tier.
  • 减少遥测集合中的网络流量。To reduce network traffic from the collection of telemetry.

应该使用哪种类型的采样?Which type of sampling should I use?

在以下情况下使用引入采样:Use ingestion sampling if:

  • 遥测经常超出每月配额。You often go through your monthly quota of telemetry.
  • 使用的 SDK 版本不支持采样,例如版本早于 2 的 ASP.NET 版本。You're using a version of the SDK that doesn't support sampling - for example ASP.NET versions earlier than 2.
  • 收到来自用户 Web 浏览器的大量遥测数据。You're getting too much telemetry from your users' web browsers.

在以下情况下使用固定速率采样:Use fixed-rate sampling if:

  • 使用 Application Insights SDK for ASP.NET Web 服务版本 2.0.0 或更高版本或者 Java SDK v2.0.1 或更高版本,并且You're using the Application Insights SDK for ASP.NET web services version 2.0.0 or later or Java SDK v2.0.1 or later, and
  • 希望同步客户端和服务器之间的采样,因此,调查 搜索 中的事件时,可以在客户端和服务器上的相关事件之间导航,例如页面视图和 http 请求。You want synchronized sampling between client and server, so that, when you're investigating events in Search, you can navigate between related events on the client and server, such as page views and http requests.
  • 对应用的适当采样百分比有信心。You are confident of the appropriate sampling percentage for your app. 它应该足够高以获取准确指标,但应低于超出定价配额和限制的速率。It should be high enough to get accurate metrics, but below the rate that exceeds your pricing quota and the throttling limits.

使用自适应采样:Use adaptive sampling:

如果使用其他采样格式的条件不适用,我们建议使用自适应采样。If the conditions to use the other forms of sampling do not apply, we recommend adaptive sampling. ASP.NET/ASP.NET Core 服务器 SDK 中默认已启用此设置。This setting is enabled by default in the ASP.NET/ASP.NET Core server SDK. 它不会将流量减少到特定最低速率,因此不会影响使用率较低的站点。It will not reduce traffic until a certain minimum rate is reached, therefore, low-use sites will not be affected.

如何知道采样是否在运行?How do I know whether sampling is in operation?

若要查找实际采样率(无论是否已应用),请使用如下所示的分析查询To discover the actual sampling rate no matter where it has been applied, use an Analytics query such as this:

union requests,dependencies,pageViews,browserTimings,exceptions,traces
| where timestamp > ago(1d)
| summarize RetainedPercentage = 100/avg(itemCount) by bin(timestamp, 1h), itemType

如果任一类型的 RetainedPercentage 小于 100,则表示正在对该项采样。If RetainedPercentage for any type is less than 100, then that item is being sampled.

Application Insights 不会使用上述任何采样方法对会话、指标和性能计数器遥测类型采样。这些类型始终会排除在采样之外,因为精度下降可能会给这些遥测类型造成很大的不利Application Insights does not sample session, metrics and performance counters telemetry types in any sampling techniques described above. These types are always excluded from sampling as reduction in precision can be highly undesirable for these telemetry types

采样如何运行?How does sampling work?

ASP.NET 版本 2.0.0 和 Java SDK 版本 2.0.1 及以上版本中 SDK 的固定速率采样功能。Fixed-rate sampling feature of the SDK in ASP.NET versions from 2.0.0 and Java SDK version 2.0.1 and onwards. 自适应采样是 ASP.NET 版本(从 2.0.0 开始)中 SDK 的一项功能。Adaptive sampling is a feature of SDK in ASP.NET versions from 2.0.0 onwards. 引入采样是 Application Insights 服务的一项功能,并且可以在 SDK 未执行采样时运行。Ingestion sampling is a feature of the Application Insights service, and can be in operation if the SDK is not performing sampling.

采样算法决定要删除哪些遥测项,以及要保留哪些遥测项(无论它是在 SDK 中还是在 Application Insights 服务中)。The sampling algorithm decides which telemetry items to drop, and which ones to keep (whether it's in the SDK or in the Application Insights service). 采样决策取决于多个规则,目标是保留所有相互关联的数据点不变,同时在 Application Insights 中保持可操作和可靠而且即使有精简数据集的诊断体验。The sampling decision is based on several rules that aim to preserve all interrelated data points intact, maintaining a diagnostic experience in Application Insights that is actionable and reliable even with a reduced data set. 例如,如果有失败的请求,应用汇发送其他遥测项(例如此请求记录的异常和跟踪),采样将不会拆分此请求和其他遥测数据。For example, if for a failed request your app sends additional telemetry items (such as exception and traces logged from this request), sampling will not split this request and other telemetry. 采样会将它们一起保留或删除。It either keeps or drops them all together. 因此,在 Application Insights 中查看请求详细信息时,始终可以看到请求以及其关联的遥测项。As a result, when you look at the request details in Application Insights, you can always see the request along with its associated telemetry items.

采样决定取决于请求的操作 ID,这意味着属于特定操作的所有遥测项不是被保留就是被删除。The sampling decision is based on the operation ID of the request, which means that all telemetry items belonging to a particular operation is either preserved or dropped. 对于未设定操作 ID 的遥测项(例如,异步线程报告的且没有 http 上下文的遥测项),采样仅捕获每个类型的遥测项百分比。For the telemetry items that do not have operation ID set (for example telemetry items reported from asynchronous threads with no http context) sampling simply captures a percentage of telemetry items of each type. 对于 .NET SDK 的 2.5.0-beta2 之前版本以及 ASP.NET Core SDK 的 2.2.0-beta3 之前版本,采样决定基于定义“用户”的应用程序用户 ID 的哈希代码(即最典型 Web 应用程序)。Prior to 2.5.0-beta2 of .NET SDK, and 2.2.0-beta3 of ASP.NET Core SDK, the sampling decision was based on the hash of the user ID for applications that define "user" (that is, most typical web applications). 对于未定义用户的应用程序类型(如 Web 服务),采样决定取决于请求的操作 ID。For the types of applications that didn't define users (such as web services) the sampling decision was based on the operation ID of the request.

当遥测发回给用户时,Application Insights 服务会以收集时所使用的同一采样百分比来调整指标,以补偿缺失的数据点。When presenting telemetry back to you, the Application Insights service adjusts the metrics by the same sampling percentage that was used at the time of collection, to compensate for the missing data points. 因此,当用户在 Application Insights 中查看遥测数据,会看到统计的正确近似值非常接近于实际值。Hence, when looking at the telemetry in Application Insights, the users are seeing statistically correct approximations that are very close to the real numbers.

近似值的准确性很大程度上取决于配置的采样百分比。The accuracy of the approximation largely depends on the configured sampling percentage. 此外,对于处理通常来自大量用户的类似请求的较大量的应用程序,准确性也会提升。Also, the accuracy increases for applications that handle a large volume of generally similar requests from lots of users. 相反,对于不处理大量负载的应用程序,不需要采样,因为这些应用程序通常可以发送其所有遥测的同时保持在配额以内,而不会因限制而造成数据丢失。On the other hand, for applications that don't work with a significant load, sampling is not needed as these applications can usually send all their telemetry while staying within the quota, without causing data loss from throttling.

警告

Application Insights 不会对指标和会话遥测类型采样。Application Insights does not sample metrics and sessions telemetry types. 对于这些遥测类型,可能非常有必要降低精度。Reduction in the precision can be highly undesirable for these telemetry types.

自适应采样Adaptive sampling

自适应采样添加用于监视当前 SDK 的传输速率的组件,并调整采样百分比,以便尝试保持在目标最大速率以内。Adaptive sampling adds a component that monitors the current rate of transmission from the SDK, and adjusts the sampling percentage to try to stay within the target maximum rate. 调整会定期重新计算,计算依据是传出的传输速率的移动平均线。The adjustment is recalculated at regular intervals, and is based on a moving average of the outgoing transmission rate.

采样和 JavaScript SDKSampling and the JavaScript SDK

客户端 (JavaScript) SDK 与服务器端 SDK 一同参与固定速率采样。The client-side (JavaScript) SDK participates in fixed-rate sampling in conjunction with the server-side SDK. 检测到的页面将仅从服务器端决定“纳入采样”的相同用户发送客户端遥测。The instrumented pages will only send client-side telemetry from the same users for which the server-side made its decision to "sample in." 此逻辑的设计目的是维护跨客户端和服务器端的用户会话的完整性。This logic is designed to maintain integrity of user session across client- and server-sides. 因此,通过 Application Insights 中的任何特定遥测项,可查找此用户或会话的所有其他遥测项。As a result, from any particular telemetry item in Application Insights you can find all other telemetry items for this user or session.

我的客户端和服务器端遥测未显示上面描述的协调示例。My client and server-side telemetry don't show coordinated samples as you describe above.

  • 确认已在服务器和客户端上启用固定速率采样。Verify that you enabled fixed-rate sampling both on server and client.
  • 确保 SDK 版本是 2.0 或更高版本。Make sure that the SDK version is 2.0 or above.
  • 检查在客户端和服务器上设置的采样百分比相同。Check that you set the same sampling percentage in both the client and server.

常见问题Frequently Asked Questions

ASP.NET 和 ASP.NET Core SDK 中的默认采样行为是什么? What is the default sampling behavior in ASP.NET and ASP.NET Core SDK?

  • 如果使用上述 SDK 的某个最新版本,则默认会启用自适应采样:每秒采样 5 个遥测项。If you are using one of the latest versions of the above SDK, Adaptive Sampling is enabled by default with five telemetry items per second. 默认会添加 2 个 AdaptiveSamplingTelemetryProcessor,其中一个在采样中包含事件类型,另一个从采样中排除事件类型。There are 2 AdaptiveSamplingTelemetryProcessors added by default, and one includes Event type in sampling, and the other excludes Event type from sampling. 这种配置意味着 SDK 会尝试将遥测项限制为事件类型的 5 个遥测项以及所有其他类型的 5 个遥测项,因此确保独立于其他遥测类型对事件进行采样。This configuration means that the SDK will try to limit telemetry items to five telemetry items of Event types, and five telemetry items of all other types combined, thereby ensuring that Events are sampled separately from other Telemetry types. 事件通常用于业务遥测,在大多数情况下不应受到诊断遥测量的影响。Events are typically used for business telemetry, and most likely should not be affected by diagnostic telemetry volumes.

    下面显示了生成的默认 ApplicationInsights.Config 文件。The following shows the default ApplicationInsights.Config file generated. 如前所述,会添加两个独立的 AdaptiveSamplingTelemetryProcessor 节点,其中一个节点排除事件类型,另一个节省包含事件类型。As described, there are two separate AdaptiveSamplingTelemetryProcessor nodes added, one excluding Event types, and another including it. 在 ASP.NET Core 中,代码中会启用完全相同的默认行为。In ASP.NET Core, exact same default behavior is enabled in code. 可使用本文档前面部分中的示例更改此默认行为。Use the examples in the earlier section of the document to change this default behavior.

    <TelemetryProcessors>
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
            <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
            <ExcludedTypes>Event</ExcludedTypes>
        </Add>
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
            <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
            <IncludedTypes>Event</IncludedTypes>
        </Add>
    </TelemetryProcessors>
    

是否可以对遥测数据进行多次采样? Can telemetry be sampled more than once?

  • 不。No. 如果项已采样,则 SamplingTelemetryProcessor 将不考虑项的采样。SamplingTelemetryProcessors ignore items from sampling considerations if the item is already sampled. 对于引入采样也是如此,对于已在 SDK 本身中采样的项,它不会应用采样。The same is true for Ingestion sampling as well, which won't apply sampling to those items already sampled in the SDK itself.'

为何不采样简单“收集每个遥测类型 %X”?Why isn't sampling a simple "collect X percent of each telemetry type"?

  • 虽然此采样方法提供极高精度的指标近似值,但它会破坏每个用户、会话和请求关联诊断数据的能力,而这对于诊断而言很关键。While this sampling approach would provide with a high level of precision in metric approximations, it would break ability to correlate diagnostic data per user, session, and request, which is critical for diagnostics. 因此,对于“收集 %X 应用用户的所有遥测项”或“收集 %X 应用请求的所有遥测”逻辑,采样的效果更佳。Therefore, sampling works better with "collect all telemetry items for X percent of app users", or "collect all telemetry for X percent of app requests" logic. 对于与请求不关联的遥测项(如后台异步处理),回退为“收集每个遥测类型 %X 的所有项”。For the telemetry items not associated with the requests (such as background asynchronous processing), the fallback is to "collect X percent of all items for each telemetry type."

采样百分比是否随时间变化?Can the sampling percentage change over time?

  • 是,自适应采样会根据当前观察到的遥测量,逐渐更改采样百分比。Yes, adaptive sampling gradually changes the sampling percentage, based on the currently observed volume of the telemetry.

如果我使用固定速率采样,如何知道哪一个才样百分比最适合我的应用?If I use fixed-rate sampling, how do I know which sampling percentage will work the best for my app?

  • 一种方法是从自适应采样开始,了解应用选定的速率(请参阅上述问题),然后使用该速率切换到固定速率采样。One way is to start with adaptive sampling, find out what rate it settles on (see the above question), and then switch to fixed-rate sampling using that rate.

    否则,就必须猜测。Otherwise, you have to guess. 分析 Application Insights 中当前遥测使用量、观察出现的任何限制,并估计所收集的遥测量。Analyze your current telemetry usage in Application Insights, observe any throttling that is occurring, and estimate the volume of the collected telemetry. 这三个输入以及所选的定价层暗示你可能想要减少收集的遥测的数量。These three inputs, together with your selected pricing tier, suggest how much you might want to reduce the volume of the collected telemetry. 但是,用户数量的增加或遥测量中的某些其他变化可能导致估计无效。However, an increase in the number of your users or some other shift in the volume of telemetry might invalidate your estimate.

如果我配置的采样百分比过低,会发生什么情况?What happens if I configure sampling percentage too low?

  • 当 Application Insights 尝试补偿数据量减少的数据可视化效果时,过低的采样百分比(过度采样)会降低近似值的准确性。Excessively low sampling percentage (over-aggressive sampling) reduces the accuracy of the approximations, when Application Insights attempts to compensate the visualization of the data for the data volume reduction. 此外,诊断体验可能会受到负面影响,由于可能会采样某些很少出现的请求或缓慢请求。Also, diagnostic experience might be negatively impacted, as some of the infrequently failing or slow requests may be sampled out.

如果我配置的采样百分比过高,会发生什么情况?What happens if I configure sampling percentage too high?

  • 将配置过高的采样百分比(力度不够)会导致收集的遥测量减少不够。Configuring too high sampling percentage (not aggressive enough) results in an insufficient reduction in the volume of the collected telemetry. 仍可能会遇到与限制相关的遥测数据丢失,而使用 Application Insights 的成本可能因过高费用而超出预算。You may still experience telemetry data loss related to throttling, and the cost of using Application Insights might be higher than you planned due to overage charges.

可以在哪些平台上使用采样?On what platforms can I use sampling?

  • 如果 SDK 未执行采样,则对于过于特定量的任何遥测,自动运行引入采样。Ingestion sampling can occur automatically for any telemetry above a certain volume, if the SDK is not performing sampling. 例如,如果使用的是较旧版本的 ASP.NET SDK 或以前版本的 Java SDK(1.0.10 或更早版本),则此配置可正常运行。This configuration would work, for example, if you are using an older version of the ASP.NET SDK or previous version of Java SDK(1.0.10 or before).
  • 如果使用的是 ASP.NET SDK 2.0.0 及更高版本或 ASP.NET CORE SDK 2.2.0 及更高版本(托管在 Azure 中或者自己的服务器上),默认运行自适应采样,不过可以切换到固定速率(如上所述)。If you're using ASP.NET SDK versions 2.0.0 and above or ASP.NET CORE SDK version 2.2.0 and above (hosted either in Azure or on your own server), you get adaptive sampling by default, but you can switch to fixed-rate as described above. 使用固定速率采样,浏览器 SDK 会自动同步到示例相关的事件。With fixed-rate sampling, the browser SDK automatically synchronizes to sample related events.
  • 如果使用的是 Java SDK 版本 2.0.1 或更高版本,则可以配置 ApplicationInsights.xml 以打开固定速率采样。If you're using Java SDK version 2.0.1 or above, you can configure ApplicationInsights.xml to turn on Fixed Rate Sampling. 默认情况下,采样处于关闭状态。Sampling is turned off by default. 使用固定速率采样,浏览器 SDK 会自动同步到示例相关的事件。With fixed-rate sampling, the browser SDK automatically synchronizes to sample related events.

我总是想要查看某些罕见的事件。如何让它们通过采样模块?There are certain rare events I always want to see. How can I get them past the sampling module?

  • 为此,最佳方法是编写一个自定义的 TelemetryProcessor,以便在想要保留的遥测项中将 SamplingPercentage 设置为 100,如下所示。The best way to achieve this is to write a custom TelemetryProcessor, which sets the SamplingPercentage to 100 on the telemetry item you want retained, as shown below. 这可以确保所有采样方法都不会在任何采样中考虑此项。This ensures that all sampling techniques will ignore this item from any sampling considerations.
    if(somecondition)
    {
        ((ISupportSampling)item).SamplingPercentage = 100;
    }

后续步骤Next steps