Application Insights 中的遥测通道Telemetry channels in Application Insights

遥测通道是 Azure Application Insights SDK 不可或缺的组成部分。Telemetry channels are an integral part of the Azure Application Insights SDKs. 它们可以管理缓冲以及将遥测数据传输到 Application Insights 服务的过程。They manage buffering and transmission of telemetry to the Application Insights service. SDK 的 .NET 和 .NET Core 版本包含两个内置的遥测通道:InMemoryChannelServerTelemetryChannelThe .NET and .NET Core versions of the SDKs have two built-in telemetry channels: InMemoryChannel and ServerTelemetryChannel. 本文将详细介绍每个通道,包括如何自定义通道行为。This article describes each channel in detail, including how to customize channel behavior.

什么是遥测通道?What are telemetry channels?

遥测通道负责缓冲遥测项并将其发送到 Application Insights 服务,存储在该服务中的项可用于查询和分析。Telemetry channels are responsible for buffering telemetry items and sending them to the Application Insights service, where they're stored for querying and analysis. 遥测通道是实现 Microsoft.ApplicationInsights.ITelemetryChannel 接口的任何类。A telemetry channel is any class that implements the Microsoft.ApplicationInsights.ITelemetryChannel interface.

遥测信道的 Send(ITelemetry item) 方法在调用所有遥测初始化表达式和遥测处理器之后调用。The Send(ITelemetry item) method of a telemetry channel is called after all telemetry initializers and telemetry processors are called. 因此,遥测处理器删除的任何项不会进入通道。So, any items dropped by a telemetry processor won't reach the channel. 一般情况下,Send() 不会立即将项发送到后端。Send() doesn't typically send the items to the back end instantly. 它通常将这些项缓冲在内存中并分批发送,以提高传输效率。Typically, it buffers them in memory and sends them in batches, for efficient transmission.

实时指标流还包含一个自定义通道用于支持遥测数据的实时流式传输。Live Metrics Stream also has a custom channel that powers the live streaming of telemetry. 此通道独立于常规的遥测通道,本文档对它不适用。This channel is independent of the regular telemetry channel, and this document doesn't apply to it.

内置遥测通道Built-in telemetry channels

Application Insights .NET 和 .NET Core SDK 随附了两个内置通道:The Application Insights .NET and .NET Core SDKs ship with two built-in channels:

  • InMemoryChannel:一个轻型通道,它在内存中将项缓冲到发送为止。InMemoryChannel: A lightweight channel that buffers items in memory until they're sent. 项在内存中缓冲,每隔 30 秒刷新一次,或者每当缓冲了 500 个项时刷新。Items are buffered in memory and flushed once every 30 seconds, or whenever 500 items are buffered. 此通道提供最基本的可靠性保证,因为它在失败后不会重试发送遥测数据。This channel offers minimal reliability guarantees because it doesn't retry sending telemetry after a failure. 此外,此通道不会在磁盘上保留项,因此,在(正常或非正常)关闭应用程序后,未发送的所有项都会永久丢失。This channel also doesn't keep items on disk, so any unsent items are lost permanently upon application shutdown (graceful or not). 此通道实现 Flush() 方法,使用此方法可以强制同步刷新内存中的所有遥测项。This channel implements a Flush() method that can be used to force-flush any in-memory telemetry items synchronously. 此通道非常适合用于短时间运行的、最好是进行同步刷新的应用程序。This channel is well suited for short-running applications where a synchronous flush is ideal.

    此通道随附在较大的 Microsoft.ApplicationInsights NuGet 包中,是未配置任何其他通道时,SDK 使用的默认通道。This channel is part of the larger Microsoft.ApplicationInsights NuGet package and is the default channel that the SDK uses when nothing else is configured.

  • ServerTelemetryChannel:一个更高级的通道,它具有重试策略,并可以在本地磁盘上存储数据。ServerTelemetryChannel: A more advanced channel that has retry policies and the capability to store data on a local disk. 如果发生暂时性错误,此通道会重试发送遥测数据。This channel retries sending telemetry if transient errors occur. 在网络中断或者遥测量较高时,此通道还会使用本地磁盘存储在磁盘上保留项。This channel also uses local disk storage to keep items on disk during network outages or high telemetry volumes. 由于这些重试机制和本地磁盘存储,我们认为此通道更可靠,建议在所有生产方案中使用。Because of these retry mechanisms and local disk storage, this channel is considered more reliable and is recommended for all production scenarios. 此通道是根据官方文档配置的 ASP.NETASP.NET Core 应用程序的默认通道。This channel is the default for ASP.NET and ASP.NET Core applications that are configured according to the official documentation. 此通道已针对长时间运行的服务器方案进行优化。This channel is optimized for server scenarios with long-running processes. 此通道实现的 Flush() 方法不是同步的。The Flush() method that's implemented by this channel isn't synchronous.

    此通道作为 Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel NuGet 包交付,使用 Microsoft.ApplicationInsights.Web 或 Microsoft.ApplicationInsights.AspNetCore NuGet 包时可自动获取它。This channel is shipped as the Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel NuGet package and is acquired automatically when you use either the Microsoft.ApplicationInsights.Web or Microsoft.ApplicationInsights.AspNetCore NuGet package.

配置遥测通道Configure a telemetry channel

可以通过将遥测通道设置为活动的遥测配置来配置该遥测通道。You configure a telemetry channel by setting it to the active telemetry configuration. 对于 ASP.NET 应用程序,配置过程涉及到将遥测通道实例设置为 TelemetryConfiguration.Active,或修改 ApplicationInsights.configFor ASP.NET applications, configuration involves setting the telemetry channel instance to TelemetryConfiguration.Active, or by modifying ApplicationInsights.config. 对于 ASP.NET Core 应用程序,配置过程涉及到将通道添加到依赖项注入容器。For ASP.NET Core applications, configuration involves adding the channel to the Dependency Injection Container.

以下部分演示如何在各种应用程序类型中配置通道的 StorageFolder 设置。The following sections show examples of configuring the StorageFolder setting for the channel in various application types. StorageFolder 只是可配置的设置之一。StorageFolder is just one of the configurable settings. 有关配置设置的完整列表,请参阅本文稍后的设置部分For the full list of configuration settings, see the settings section later in this article.

使用适用于 ASP.NET 应用程序的 ApplicationInsights.Config 进行配置Configuration by using ApplicationInsights.config for ASP.NET applications

ApplicationInsights.config 中的以下节显示了在将 StorageFolder 设置为自定义位置的情况下配置的 ServerTelemetryChannel 通道:The following section from ApplicationInsights.config shows the ServerTelemetryChannel channel configured with StorageFolder set to a custom location:

    <TelemetrySinks>
        <Add Name="default">
            <TelemetryProcessors>
                <!-- Telemetry processors omitted for brevity  -->
            </TelemetryProcessors>
            <TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel">
                <StorageFolder>d:\temp\applicationinsights</StorageFolder>
            </TelemetryChannel>
        </Add>
    </TelemetrySinks>

ASP.NET 应用程序代码中的配置Configuration in code for ASP.NET applications

以下代码在将 StorageFolder 设置为自定义位置的情况下设置“ServerTelemetryChannel”实例。The following code sets up a 'ServerTelemetryChannel' instance with StorageFolder set to a custom location. 请将此代码添加到应用程序的开头,通常是添加到 Global.aspx.cs 中的 Application_Start() 方法内。Add this code at the beginning of the application, typically in Application_Start() method in Global.aspx.cs.

using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
protected void Application_Start()
{
    var serverTelemetryChannel = new ServerTelemetryChannel();
    serverTelemetryChannel.StorageFolder = @"d:\temp\applicationinsights";
    serverTelemetryChannel.Initialize(TelemetryConfiguration.Active);
    TelemetryConfiguration.Active.TelemetryChannel = serverTelemetryChannel;
}

ASP.NET Core 应用程序代码中的配置Configuration in code for ASP.NET Core applications

修改类 Startup.csConfigureServices 方法,如下所示:Modify the ConfigureServices method of the Startup.cs class as shown here:

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

public void ConfigureServices(IServiceCollection services)
{
    // This sets up ServerTelemetryChannel with StorageFolder set to a custom location.
    services.AddSingleton(typeof(ITelemetryChannel), new ServerTelemetryChannel() {StorageFolder = @"d:\temp\applicationinsights" });

    services.AddApplicationInsightsTelemetry();
}

重要

不建议使用 TelemetryConfiguration.Active 配置 ASP.NET Core 应用程序的通道。Configuring the channel by using TelemetryConfiguration.Active is not recommended for ASP.NET Core applications.

.NET/.NET Core 控制台应用程序代码中的配置Configuration in code for .NET/.NET Core console applications

.NET 和 .NET Core 控制台应用的代码相同:For console apps, the code is the same for both .NET and .NET Core:

var serverTelemetryChannel = new ServerTelemetryChannel();
serverTelemetryChannel.StorageFolder = @"d:\temp\applicationinsights";
serverTelemetryChannel.Initialize(TelemetryConfiguration.Active);
TelemetryConfiguration.Active.TelemetryChannel = serverTelemetryChannel;

ServerTelemetryChannel 的操作详细信息Operational details of ServerTelemetryChannel

ServerTelemetryChannel 在内存中缓冲区内存储抵达的项。ServerTelemetryChannel stores arriving items in an in-memory buffer. 每隔 30 秒或每当缓冲了 500 个项时,这些项将序列化、压缩并存储到 Transmission 实例中。The items are serialized, compressed, and stored into a Transmission instance once every 30 seconds, or when 500 items have been buffered. 单个 Transmission 实例最多包含 500 个项,表示通过 Application Insights 服务的单个 HTTPS 调用发送的遥测数据批。A single Transmission instance contains up to 500 items and represents a batch of telemetry that's sent over a single HTTPS call to the Application Insights service.

默认情况下,最多可以并行发送 10 个 Transmission 实例。By default, a maximum of 10 Transmission instances can be sent in parallel. 如果遥测数据以更快的速度抵达,或者网络或 Application Insights 后端速度缓慢,则 Transmission 将存储到内存中。If telemetry is arriving at faster rates, or if the network or the Application Insights back end is slow, Transmission instances are stored in memory. 此内存中 Transmission 缓冲区的默认容量为 5 MB。The default capacity of this in-memory Transmission buffer is 5 MB. 超过内存中容量时,Transmission 实例将存储在本地磁盘上(不超过 50 MB)。When the in-memory capacity has been exceeded, Transmission instances are stored on local disk up to a limit of 50 MB. 出现网络问题时,Transmission 实例也会存储在本地磁盘上。Transmission instances are stored on local disk also when there are network problems. 当应用程序崩溃时,只有存储在本地磁盘中的项才能幸存。Only those items that are stored on a local disk survive an application crash. 每当应用程序再次启动时,将发送这些项。They're sent whenever the application starts again.

通道中的可配置设置Configurable settings in channels

有关每个通道的可配置设置完整列表,请参阅:For the full list of configurable settings for each channel, see:

下面是 ServerTelemetryChannel 的最常用设置:Here are the most commonly used settings for ServerTelemetryChannel:

  1. MaxTransmissionBufferCapacity:用于在内存中缓冲传输内容的通道所用的内存量,以字节为单位。MaxTransmissionBufferCapacity: The maximum amount of memory, in bytes, used by the channel to buffer transmissions in memory. 达到此容量时,新项将直接存储到本地磁盘。When this capacity is reached, new items are stored directly to local disk. 默认值为 5 MB。The default value is 5 MB. 设置更大的值可以减少磁盘用量,但请记住,如果应用程序崩溃,内存中的项将会丢失。Setting a higher value leads to less disk usage, but remember that items in memory will be lost if the application crashes.

  2. MaxTransmissionSenderCapacity:要同时发送到 Application Insights 的最大 Transmission 实例数量。MaxTransmissionSenderCapacity: The maximum number of Transmission instances that will be sent to Application Insights at the same time. 默认值为 10。The default value is 10. 可将此设置配置为更大的数字,生成巨量的遥测数据时建议这样做。This setting can be configured to a higher number, which is recommended when a huge volume of telemetry is generated. 执行负载测试或关闭采样时,往往会出现大量的遥测数据。High volume typically occurs during load testing or when sampling is turned off.

  3. StorageFolder:磁盘上的文件夹,通道根据需要将项存储到其中。StorageFolder: The folder that's used by the channel to store items to disk as needed. 在 Windows 中,如果未显式指定其他路径,则会使用 %LOCALAPPDATA% 或 %TEMP%。In Windows, either %LOCALAPPDATA% or %TEMP% is used if no other path is specified explicitly. 在非 Windows 环境中,必须指定有效的位置,否则遥测数据不会存储到本地磁盘。In environments other than Windows, you must specify a valid location or telemetry won't be stored to local disk.

应使用哪个通道?Which channel should I use?

对于涉及到长时间运行的应用程序的大多数生产方案,建议使用 ServerTelemetryChannelServerTelemetryChannel is recommended for most production scenarios involving long-running applications. ServerTelemetryChannel 实现的 Flush() 方法不是同步的,不保证发送内存或磁盘中所有等待中的项。The Flush() method implemented by ServerTelemetryChannel isn't synchronous, and it also doesn't guarantee sending all pending items from memory or disk. 如果要在应用程序即将关闭的情况下使用此通道,则我们建议在调用 Flush() 后留出一定的延迟。If you use this channel in scenarios where the application is about to shut down, we recommend that you introduce some delay after calling Flush(). 所需的确切延迟时间不可预测。The exact amount of delay that you might require isn't predictable. 这取决于多种因素,例如,有多少个项或 Transmission 实例位于内存中和磁盘中、其中有多少个正在传输到后端,以及该通道是否位于指数退让方案的中间部分。It depends on factors like how many items or Transmission instances are in memory, how many are on disk, how many are being transmitted to the back end, and whether the channel is in the middle of exponential back-off scenarios.

如果需要执行同步刷新,我们建议使用 InMemoryChannelIf you need to do a synchronous flush, we recommend that you use InMemoryChannel.

常见问题Frequently asked questions

Application Insights 通道是否保证传送遥测数据?Does the Application Insights channel guarantee telemetry delivery? 如果不能,在哪些情况下遥测数据可能会丢失?If not, what are the scenarios in which telemetry can be lost?

简单地讲,在向后端传送遥测数据方面,没有任何内置通道能够提供事务类型保证。The short answer is that none of the built-in channels offer a transaction-type guarantee of telemetry delivery to the back end. 在可靠传送方面,ServerTelemetryChannelInMemoryChannel 更先进,但它也只能是尽最大努力来尝试发送遥测数据。ServerTelemetryChannel is more advanced compared with InMemoryChannel for reliable delivery, but it also makes only a best-effort attempt to send telemetry. 在多种情况下,遥测数据仍可能会丢失,常见情况包括:Telemetry can still be lost in several situations, including these common scenarios:

  1. 当应用程序崩溃时,内存中的项就会丢失。Items in memory are lost when the application crashes.

  2. 如果网络问题的持续时间很长,遥测数据将会丢失。Telemetry is lost during extended periods of network problems. 出现网络中断或者 Application Insights 后端问题时,遥测数据将存储到本地磁盘。Telemetry is stored to local disk during network outages or when problems occur with the Application Insights back end. 但是,超过 48 小时的项将被丢弃。However, items older than 48 hours are discarded.

  3. 在 Windows 中,用于存储遥测数据的默认磁盘位置是 %LOCALAPPDATA% 或 %TEMP%。The default disk locations for storing telemetry in Windows are %LOCALAPPDATA% or %TEMP%. 这些位置通常位于计算机本地。These locations are typically local to the machine. 如果以物理方式将应用程序从一个位置迁移到另一个位置,在原始位置存储的所有遥测数据将会丢失。If the application migrates physically from one location to another, any telemetry stored in the original location is lost.

  4. 在 Windows 上的 Web 应用中,默认磁盘存储位置为 D:\local\LocalAppData。In Web Apps on Windows, the default disk-storage location is D:\local\LocalAppData. 此位置不是永久性的。This location isn't persisted. 在应用重启、横向扩展和执行其他此类操作的情况下将被擦除,导致这些位置存储的遥测数据丢失。It's wiped out in app restarts, scale-outs, and other such operations, leading to loss of any telemetry stored there. 可将替代默认位置,并将存储指定为某个永久性位置(例如 D:\home)。You can override the default and specify storage to a persisted location like D:\home. 但是,此类永久性位置由远程存储提供服务,因此运行速度可能很缓慢。However, such persisted locations are served by remote storage and so can be slow.

ServerTelemetryChannel 是否可在非 Windows 系统中工作?Does ServerTelemetryChannel work on systems other than Windows?

尽管该通道的包和命名空间名称包含“WindowsServer”,但非 Windows 系统也支持此通道,不过存在以下例外情况。Although the name of its package and namespace includes "WindowsServer," this channel is supported on systems other than Windows, with the following exception. 在非 Windows 系统中,该通道默认不会创建本地存储文件夹。On systems other than Windows, the channel doesn't create a local storage folder by default. 必须创建本地存储文件夹,并将通道配置为使用该文件夹。You must create a local storage folder and configure the channel to use it. 配置本地存储后,该通道在所有系统中的工作方式相同。After local storage has been configured, the channel works the same way on all systems.

备注

随着 2.15.0-beta3 版的推出,现可为 Linux、Mac 和 Windows 自动创建更大的本地存储。With the release 2.15.0-beta3 and greater local storage is now automatically created for Linux, Mac, and Windows. 对于非 Windows 系统,SDK 将根据以下逻辑自动创建本地存储文件夹:For non Windows systems the SDK will automatically create a local storage folder based on the following logic:

  • ${TMPDIR} - 如果设置了 ${TMPDIR} 环境变量,则使用此位置。${TMPDIR} - if ${TMPDIR} environment variable is set this location is used.
  • /var/tmp - 如果前一个位置不存在,请尝试 /var/tmp/var/tmp - if the previous location does not exist we try /var/tmp.
  • /tmp - 如果前两个位置都不存在,请尝试 tmp/tmp - if both the previous locations do not exist we try tmp.
  • 如果这些位置都不存在,则不会创建本地存储,且仍然需要手动配置。If none of those locations exist local storage is not created and manual configuration is still required. 了解有关实现的完整详细信息For full implementation details.

SDK 是否创建临时本地存储?Does the SDK create temporary local storage? 存储中的数据是否会加密?Is the data encrypted at storage?

出现网络问题或限制时,SDK 会将遥测项存储在本地存储中。The SDK stores telemetry items in local storage during network problems or during throttling. 此数据不会在本地加密。This data isn't encrypted locally.

对于 Windows 系统,SDK 会自动在 %TEMP% 或 %LOCALAPPDATA% 目录中创建临时本地文件夹,并仅限管理员和当前用户访问该文件夹。For Windows systems, the SDK automatically creates a temporary local folder in the %TEMP% or %LOCALAPPDATA% directory, and restricts access to administrators and the current user only.

对于非 Windows 系统,SDK 不会自动创建本地存储,因此默认不会在本地存储数据。For systems other than Windows, no local storage is created automatically by the SDK, and so no data is stored locally by default.

备注

随着 2.15.0-beta3 版的推出,现可为 Linux、Mac 和 Windows 自动创建更大的本地存储。With the release 2.15.0-beta3 and greater local storage is now automatically created for Linux, Mac, and Windows.

你可以自行创建存储目录,并将通道配置为使用该目录。You can create a storage directory yourself and configure the channel to use it. 在这种情况下,你需负责确保该目录受到保护。In this case, you're responsible for ensuring that the directory is secured. 详细了解数据保留和隐私Read more about data protection and privacy.

开源 SDKOpen-source SDK

与 Application Insights 的每个 SDK 一样,通道也是开源的。Like every SDK for Application Insights, channels are open source. 请在官方 GitHub 存储库中阅读和贡献代码,或者报告问题。Read and contribute to the code, or report problems, at the official GitHub repo.

后续步骤Next steps