适用于辅助角色服务应用程序(非 HTTP 应用)的 Application InsightsApplication Insights for Worker Service applications (non-HTTP applications)

Application Insights 正在发布名为 Microsoft.ApplicationInsights.WorkerService 的新 SDK,该 SDK 最适合用于消息传递、后台任务、控制台应用程序等非 HTTP 工作负荷。此类应用程序不像传统 ASP.NET/ASP.NET Core Web 应用程序那样具有传入 HTTP 请求的概念,因此,不支持对 ASP.NETASP.NET Core 应用程序使用 Application Insights 包。Application Insights is releasing a new SDK, called Microsoft.ApplicationInsights.WorkerService, which is best suited for non-HTTP workloads like messaging, background tasks, console applications etc. These types of applications don't have the notion of an incoming HTTP request like a traditional ASP.NET/ASP.NET Core Web Application, and hence using Application Insights packages for ASP.NET or ASP.NET Core applications is not supported.

新 SDK 本身不执行任何遥测收集,The new SDK does not do any telemetry collection by itself. 而是引入了其他众所周知的 Application Insights 自动收集器,例如 DependencyCollectorPerfCounterCollectorApplicationInsightsLoggingProvider 等。此 SDK 公开 IServiceCollection 中的扩展方法用于启用和配置遥测收集。Instead, it brings in other well known Application Insights auto collectors like DependencyCollector, PerfCounterCollector, ApplicationInsightsLoggingProvider etc. This SDK exposes extension methods on IServiceCollection to enable and configure telemetry collection.

支持的方案Supported scenarios

适用于辅助角色服务的 Application Insights SDK 最适合用于非 HTTP 应用程序,无论这些应用程序在何处或者如何运行。The Application Insights SDK for Worker Service is best suited for non-HTTP applications no matter where or how they run. 如果应用程序正在运行并与 Azure 建立了网络连接,则可以收集遥测数据。If your application is running and has network connectivity to Azure, telemetry can be collected. 只要支持 .NET Core,就能支持 Application Insights 监视。Application Insights monitoring is supported everywhere .NET Core is supported. 此包可在新引入的 .NET Core 3.0 辅助角色服务Asp.Net Core 2.1/2.2 中的后台任务、控制台应用 (.NET Core/ .NET Framework) 等工作负荷中使用。This package can be used in the newly introduced .NET Core 3.0 Worker Service, background tasks in Asp.Net Core 2.1/2.2, Console apps (.NET Core/ .NET Framework), etc.

先决条件Prerequisites

有效的 Application Insights 检测密钥。A valid Application Insights instrumentation key. 将任何遥测数据发送到 Application Insights 都需要使用此密钥。This key is required to send any telemetry to Application Insights. 如果需要创建新的 Application Insights 资源来获取检测密钥,请参阅创建 Application Insights 资源If you need to create a new Application Insights resource to get an instrumentation key, see Create an Application Insights resource.

使用适用于辅助角色服务的 Application Insights SDKUsing Application Insights SDK for Worker Services

  1. Microsoft.ApplicationInsights.WorkerService 包安装到应用程序。Install the Microsoft.ApplicationInsights.WorkerService package to the application. 以下代码片段演示了需要添加到项目的 .csproj 文件中的更改。The following snippet shows the changes that need to be added to your project's .csproj file.
    <ItemGroup>
        <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.13.1" />
    </ItemGroup>
  1. 调用 IServiceCollection 中的 AddApplicationInsightsTelemetryWorkerService(string instrumentationKey) 扩展方法并提供检测密钥。Call AddApplicationInsightsTelemetryWorkerService(string instrumentationKey) extension method on IServiceCollection, providing the instrumentation key. 应在应用程序的开头调用此方法。This method should be called at the beginning of the application. 具体位置取决于应用程序的类型。The exact location depends on the type of application.

  2. 通过调用 serviceProvider.GetRequiredService<TelemetryClient>(); 或使用构造函数注入,从依赖项注入 (DI) 容器中检索 ILogger 实例或 TelemetryClient 实例。Retrieve an ILogger instance or TelemetryClient instance from the Dependency Injection (DI) container by calling serviceProvider.GetRequiredService<TelemetryClient>(); or using Constructor Injection. 此步骤将触发 TelemetryConfiguration 和自动收集模块的设置。This step will trigger setting up of TelemetryConfiguration and auto collection modules.

以下部分提供了适用于每种应用程序的具体说明。Specific instructions for each type of application is described in the following sections.

.NET Core 3.0 辅助角色服务应用程序.NET Core 3.0 worker service application

此处分享了完整示例Full example is shared here

  1. 下载并安装 .NET Core 3.0Download and install .NET Core 3.0

  2. 使用 Visual Studio 的新建项目模板或命令行 dotnet new worker 创建新的辅助角色服务项目Create a new Worker Service project either by using Visual Studio new project template or command line dotnet new worker

  3. Microsoft.ApplicationInsights.WorkerService 包安装到应用程序。Install the Microsoft.ApplicationInsights.WorkerService package to the application.

  4. services.AddApplicationInsightsTelemetryWorkerService(); 添加到 Program.cs 类中的 CreateHostBuilder() 方法,如以下示例所示:Add services.AddApplicationInsightsTelemetryWorkerService(); to the CreateHostBuilder() method in your Program.cs class, as in this example:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
                services.AddApplicationInsightsTelemetryWorkerService();
            });
  1. 按以下示例修改 Worker.csModify your Worker.cs as per below example.
    using Microsoft.ApplicationInsights;
    using Microsoft.ApplicationInsights.DataContracts;

    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
        private TelemetryClient _telemetryClient;
        private static HttpClient _httpClient = new HttpClient();

        public Worker(ILogger<Worker> logger, TelemetryClient tc)
        {
            _logger = logger;
            _telemetryClient = tc;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

                using (_telemetryClient.StartOperation<RequestTelemetry>("operation"))
                {
                    _logger.LogWarning("A sample warning message. By default, logs with severity Warning or higher is captured by Application Insights");
                    _logger.LogInformation("Calling bing.com");
                    var res = await _httpClient.GetAsync("https://bing.com");
                    _logger.LogInformation("Calling bing completed with status:" + res.StatusCode);
                    _telemetryClient.TrackEvent("Bing call event completed");
                }

                await Task.Delay(1000, stoppingToken);
            }
        }
    }
  1. 设置检测密钥。Set up the instrumentation key.

    尽管可将检测密钥作为参数提供给 AddApplicationInsightsTelemetryWorkerService,但我们建议在配置中指定检测密钥。Although you can provide the instrumentation key as an argument to AddApplicationInsightsTelemetryWorkerService, we recommend that you specify the instrumentation key in configuration. 以下代码示例演示如何在 appsettings.json 中指定检测密钥。The following code sample shows how to specify an instrumentation key in appsettings.json. 在发布期间,请确保将 appsettings.json 复制到应用程序根文件夹。Make sure appsettings.json is copied to the application root folder during publishing.

    {
        "ApplicationInsights":
            {
            "InstrumentationKey": "putinstrumentationkeyhere"
            },
        "Logging":
        {
            "LogLevel":
            {
                "Default": "Warning"
            }
        }
    }

或者,在以下任一环境变量中指定检测密钥。Alternatively, specify the instrumentation key in either of the following environment variables. APPINSIGHTS_INSTRUMENTATIONKEYApplicationInsights:InstrumentationKeyAPPINSIGHTS_INSTRUMENTATIONKEY or ApplicationInsights:InstrumentationKey

例如: SET ApplicationInsights:InstrumentationKey=putinstrumentationkeyhereFor example: SET ApplicationInsights:InstrumentationKey=putinstrumentationkeyhere 或者 SET APPINSIGHTS_INSTRUMENTATIONKEY=putinstrumentationkeyhereOR SET APPINSIGHTS_INSTRUMENTATIONKEY=putinstrumentationkeyhere

通常,APPINSIGHTS_INSTRUMENTATIONKEY 指定要作为 Web 作业部署到 Web 应用的应用程序的检测密钥。Typically, APPINSIGHTS_INSTRUMENTATIONKEY specifies the instrumentation key for applications deployed to Web Apps as Web Jobs.

备注

在代码中指定的检测密钥优先于环境变量 APPINSIGHTS_INSTRUMENTATIONKEY,而后者又优先于其他选项。An instrumentation key specified in code wins over the environment variable APPINSIGHTS_INSTRUMENTATIONKEY, which wins over other options.

使用托管服务的 ASP.NET Core 后台任务ASP.NET Core background tasks with hosted services

此文档介绍了如何在 ASP.NET Core 2.1/2.2 应用程序中创建后台任务。This document describes how to create backgrounds tasks in ASP.NET Core 2.1/2.2 application.

此处分享了完整示例Full example is shared here

  1. 将 Microsoft.ApplicationInsights.WorkerService(https://www.nuget.org/packages/Microsoft.ApplicationInsights.WorkerService) 包安装到应用程序。Install the Microsoft.ApplicationInsights.WorkerService(https://www.nuget.org/packages/Microsoft.ApplicationInsights.WorkerService) package to the application.
  2. services.AddApplicationInsightsTelemetryWorkerService(); 添加到 ConfigureServices() 方法,如以下示例所示:Add services.AddApplicationInsightsTelemetryWorkerService(); to the ConfigureServices() method, as in this example:
    public static async Task Main(string[] args)
    {
        var host = new HostBuilder()
            .ConfigureAppConfiguration((hostContext, config) =>
            {
                config.AddJsonFile("appsettings.json", optional: true);
            })
            .ConfigureServices((hostContext, services) =>
            {
                services.AddLogging();
                services.AddHostedService<TimedHostedService>();

                // instrumentation key is read automatically from appsettings.json
                services.AddApplicationInsightsTelemetryWorkerService();
            })
            .UseConsoleLifetime()
            .Build();

        using (host)
        {
            // Start the host
            await host.StartAsync();

            // Wait for the host to shutdown
            await host.WaitForShutdownAsync();
        }
    }

下面是后台任务逻辑所在的 TimedHostedService 的代码。Following is the code for TimedHostedService where the background task logic resides.

    using Microsoft.ApplicationInsights;
    using Microsoft.ApplicationInsights.DataContracts;

    public class TimedHostedService : IHostedService, IDisposable
    {
        private readonly ILogger _logger;
        private Timer _timer;
        private TelemetryClient _telemetryClient;
        private static HttpClient httpClient = new HttpClient();

        public TimedHostedService(ILogger<TimedHostedService> logger, TelemetryClient tc)
        {
            _logger = logger;
            this._telemetryClient = tc;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is starting.");

            _timer = new Timer(DoWork, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(1));

            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

            using (_telemetryClient.StartOperation<RequestTelemetry>("operation"))
            {
                _logger.LogWarning("A sample warning message. By default, logs with severity Warning or higher is captured by Application Insights");
                _logger.LogInformation("Calling bing.com");
                var res = httpClient.GetAsync("https://bing.com").GetAwaiter().GetResult();
                _logger.LogInformation("Calling bing completed with status:" + res.StatusCode);
                _telemetryClient.TrackEvent("Bing call event completed");
            }
        }
    }
  1. 设置检测密钥。Set up the instrumentation key. 使用上述 .NET Core 3.0 辅助角色服务示例中的相同 appsettings.jsonUse the same appsettings.json from the .NET Core 3.0 Worker Service example above.

.NET Core/.NET Framework 控制台应用程序.NET Core/.NET Framework Console application

如本文开头所述,甚至可以使用新包从普通的控制台应用程序启用 Application Insights 遥测。As mentioned in the beginning of this article, the new package can be used to enable Application Insights Telemetry from even a regular console application. 此包针对 NetStandard2.0,因此可用于 .NET Core 2.0 或更高版本,以及 .NET Framework 4.7.2 或更高版本中的控制台应用。This package targets NetStandard2.0, and hence can be used for console apps in .NET Core 2.0 or higher, and .NET Framework 4.7.2 or higher.

此处分享了完整示例Full example is shared here

  1. 将 Microsoft.ApplicationInsights.WorkerService(https://www.nuget.org/packages/Microsoft.ApplicationInsights.WorkerService) 包安装到应用程序。Install the Microsoft.ApplicationInsights.WorkerService(https://www.nuget.org/packages/Microsoft.ApplicationInsights.WorkerService) package to the application.

  2. 按以下示例所示修改 Program.cs。Modify Program.cs as below example.

    using Microsoft.ApplicationInsights;
    using Microsoft.ApplicationInsights.DataContracts;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using System;
    using System.Net.Http;
    using System.Threading.Tasks;

    namespace WorkerSDKOnConsole
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                // Create the DI container.
                IServiceCollection services = new ServiceCollection();

                // Being a regular console app, there is no appsettings.json or configuration providers enabled by default.
                // Hence instrumentation key and any changes to default logging level must be specified here.
                services.AddLogging(loggingBuilder => loggingBuilder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>("Category", LogLevel.Information));
                services.AddApplicationInsightsTelemetryWorkerService("instrumentationkeyhere");

                // Build ServiceProvider.
                IServiceProvider serviceProvider = services.BuildServiceProvider();

                // Obtain logger instance from DI.
                ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();

                // Obtain TelemetryClient instance from DI, for additional manual tracking or to flush.
                var telemetryClient = serviceProvider.GetRequiredService<TelemetryClient>();

                var httpClient = new HttpClient();

                while (true) // This app runs indefinitely. replace with actual application termination logic.
                {
                    logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

                    // Replace with a name which makes sense for this operation.
                    using (telemetryClient.StartOperation<RequestTelemetry>("operation"))
                    {
                        logger.LogWarning("A sample warning message. By default, logs with severity Warning or higher is captured by Application Insights");
                        logger.LogInformation("Calling bing.com");                    
                        var res = await httpClient.GetAsync("https://bing.com");
                        logger.LogInformation("Calling bing completed with status:" + res.StatusCode);
                        telemetryClient.TrackEvent("Bing call event completed");
                    }

                    await Task.Delay(1000);
                }

                // Explicitly call Flush() followed by sleep is required in Console Apps.
                // This is to ensure that even if application terminates, telemetry is sent to the back-end.
                telemetryClient.Flush();
                Task.Delay(5000).Wait();
            }
        }
    }

此控制台应用程序也使用相同的默认 TelemetryConfiguration,可按前面部分中的示例所示的相同方式对其进行自定义。This console application also uses the same default TelemetryConfiguration, and it can be customized in the same way as the examples in earlier section.

运行应用程序Run your application

运行应用程序。Run your application. 上述所有示例中的示例辅助角色每秒对 bing.com 发出 http 调用,并使用 ILogger 发出几个日志。The example workers from all of the above above makes an http call every second to bing.com, and also emits few logs using ILogger. 这些行包装在用于创建操作的 TelemetryClientStartOperation 调用内部(在此示例中,RequestTelemetry 名为“operation”)。These lines are wrapped inside StartOperation call of TelemetryClient, which is used to create an operation (in this example RequestTelemetry named "operation"). Application Insights 将收集这些 ILogger 日志(默认为警告或更高级别)和依赖项,这些日志将通过父子关系关联到 RequestTelemetryApplication Insights will collect these ILogger logs (warning or above by default) and dependencies, and they will be correlated to the RequestTelemetry with parent-child relationship. 这种关联也会跨进程/网络边界发生。The correlation also works cross process/network boundary. 例如,如果对另一个受监视组件发出调用,则该组件也会关联到此父级。For example, if the call was made to another monitored component, then it will be correlated to this parent as well.

可将 RequestTelemetry 的此自定义操作视为等效于典型 Web 应用程序中的传入 Web 请求。This custom operation of RequestTelemetry can be thought of as the equivalent of an incoming web request in a typical Web Application. 尽管不一定要使用操作,但操作最适合 Application Insights 关联数据模型 - RequestTelemetry 充当父操作,在辅助角色迭代中生成的每个遥测数据被视为在逻辑上属于同一操作。While it is not necessary to use an Operation, it fits best with the Application Insights correlation data model - with RequestTelemetry acting as the parent operation, and every telemetry generated inside the worker iteration being treated as logically belonging to the same operation. 此方法还确保生成的所有遥测数据(自动和手动)具有相同的 operation_idThis approach also ensures all the telemetry generated (automatic and manual) will have the same operation_id. 由于采样基于 operation_id,因此采样算法会在单个迭代中保留或删除所有遥测数据。As sampling is based on operation_id, sampling algorithm either keeps or drops all of the telemetry from a single iteration.

下面列出了 Application Insights 自动收集的整个遥测数据。The following lists the full telemetry automatically collected by Application Insights.

实时指标Live Metrics

实时指标可用于快速验证是否正确配置了 Application Insights 监视。Live Metrics can be used to quickly verify if Application Insights monitoring is configured correctly. 尽管可能需要在几分钟时间后遥测数据才开始显示在门户和分析结果中,但实时指标能够近实时地显示正在运行的进程的 CPU 使用率。While it might take a few minutes before telemetry starts appearing in the portal and analytics, Live Metrics would show CPU usage of the running process in near real-time. 它还可以显示其他遥测数据,例如请求、依赖项、跟踪等。It can also show other telemetry like Requests, Dependencies, Traces etc.

ILogger 日志ILogger logs

自动捕获通过 Warning 或更高严重性的 ILogger 发出的日志。Logs emitted via ILogger of severity Warning or greater are automatically captured. 遵循 ILogger 文档自定义 Application Insights 捕获的日志级别。Follow ILogger docs to customize which log levels are captured by Application Insights.

依赖项Dependencies

默认情况已启用依赖项收集。Dependency collection is enabled by default. 此文介绍了自动收集的依赖项,并提供了执行手动跟踪的步骤。This article explains the dependencies that are automatically collected, and also contain steps to do manual tracking.

EventCounterEventCounter

EventCounterCollectionModule 默认已启用,它会从 .NET Core 3.0 应用收集默认的计数器集。EventCounterCollectionModule is enabled by default, and it will collect a default set of counters from .NET Core 3.0 apps. EventCounter 教程列出了收集的默认计数器集。The EventCounter tutorial lists the default set of counters collected. 它还包含有关自定义列表的说明。It also has instructions on customizing the list.

手动跟踪附加遥测数据Manually tracking additional telemetry

尽管 SDK 会按如上所述自动收集遥测数据,但在大多数情况下,用户需要将附加遥测数据发送到 Application Insights 服务。While the SDK automatically collects telemetry as explained above, in most cases user will need to send additional telemetry to Application Insights service. 跟踪附加遥测数据的建议方法是从依赖项注入获取 TelemetryClient 的实例,然后对其调用某个受支持的 TrackXXX() API 方法。The recommended way to track additional telemetry is by obtaining an instance of TelemetryClient from Dependency Injection, and then calling one of the supported TrackXXX() API methods on it. 另一种典型用例是操作的自定义跟踪Another typical use case is custom tracking of operations. 以上辅助角色示例演示了此方法。This approach is demonstrated in the Worker examples above.

配置 Application Insights SDKConfigure the Application Insights SDK

辅助角色服务 SDK 使用的默认 TelemetryConfiguration 类似于 ASP.NET 或 ASP.NET Core 应用程序中使用的自动配置,但不包括用于从 HttpContext 中扩充遥测的 TelemetryInitializers。The default TelemetryConfiguration used by the worker service SDK is similar to the automatic configuration used in a ASP.NET or ASP.NET Core application, minus the TelemetryInitializers used to enrich telemetry from HttpContext.

可以自定义适用于辅助角色服务的 Application Insights SDK 来更改默认配置。You can customize the Application Insights SDK for Worker Service to change the default configuration. Application Insights ASP.NET Core SDK 的用户可以使用 ASP.NET Core 的内置依赖项注入来熟悉配置更改。Users of the Application Insights ASP.NET Core SDK might be familiar with changing configuration by using ASP.NET Core built-in dependency injection. WorkerService SDK 也基于类似的原则。The WorkerService SDK is also based on similar principles. 几乎所有的配置更改都是通过调用 IServiceCollection 中的相应方法在 ConfigureServices() 节中进行的,下面对此做了详述。Make almost all configuration changes in the ConfigureServices() section by calling appropriate methods on IServiceCollection, as detailed below.

备注

使用此 SDK 时,不支持通过修改 TelemetryConfiguration.Active 来更改配置,并且不会反映更改。While using this SDK, changing configuration by modifying TelemetryConfiguration.Active isn't supported, and changes will not be reflected.

使用 ApplicationInsightsServiceOptionsUsing ApplicationInsightsServiceOptions

可以通过向 AddApplicationInsightsTelemetryWorkerService 传递 ApplicationInsightsServiceOptions 来修改一些通用设置,如以下示例所示:You can modify a few common settings by passing ApplicationInsightsServiceOptions to AddApplicationInsightsTelemetryWorkerService, as in this example:

    using Microsoft.ApplicationInsights.WorkerService;

    public void ConfigureServices(IServiceCollection services)
    {
        Microsoft.ApplicationInsights.WorkerService.ApplicationInsightsServiceOptions aiOptions
                    = new Microsoft.ApplicationInsights.WorkerService.ApplicationInsightsServiceOptions();
        // Disables adaptive sampling.
        aiOptions.EnableAdaptiveSampling = false;

        // Disables QuickPulse (Live Metrics stream).
        aiOptions.EnableQuickPulseMetricStream = false;
        services.AddApplicationInsightsTelemetryWorkerService(aiOptions);
    }

请注意,此 SDK 中的 ApplicationInsightsServiceOptions 位于命名空间 Microsoft.ApplicationInsights.WorkerService 中,而不是像 ASP.NET Core SDK 那样位于 Microsoft.ApplicationInsights.AspNetCore.Extensions 中。Note that ApplicationInsightsServiceOptions in this SDK is in the namespace Microsoft.ApplicationInsights.WorkerService as opposed to Microsoft.ApplicationInsights.AspNetCore.Extensions in the ASP.NET Core SDK.

ApplicationInsightsServiceOptions 中的常用设置Commonly used settings in ApplicationInsightsServiceOptions

设置Setting 说明Description 默认Default
EnableQuickPulseMetricStreamEnableQuickPulseMetricStream Enable/Disable LiveMetrics featureEnable/Disable LiveMetrics feature true
EnableAdaptiveSamplingEnableAdaptiveSampling 启用/禁用自适应采样Enable/Disable Adaptive Sampling true
EnableHeartbeatEnableHeartbeat 启用/禁用检测信号功能,该功能定期(默认间隔为 15 分钟)发送名为“HeartBeatState”的自定义指标,其中包含有关运行时等的信息,例如 .NET 版本、Azure 环境信息(如果适用)等。Enable/Disable Heartbeats feature, which periodically (15-min default) sends a custom metric named 'HeartBeatState' with information about the runtime like .NET Version, Azure Environment information, if applicable, etc. true
AddAutoCollectedMetricExtractorAddAutoCollectedMetricExtractor 启用/禁用 AutoCollectedMetrics 提取程序 - 一个 TelemetryProcessor,在采样发生之前发送有关请求/依赖项的聚合前指标。Enable/Disable AutoCollectedMetrics extractor, which is a TelemetryProcessor that sends pre-aggregated metrics about Requests/Dependencies before sampling takes place. true

有关最新列表,请参阅 ApplicationInsightsServiceOptions 中的可配置设置See the configurable settings in ApplicationInsightsServiceOptions for the most up-to-date list.

采样Sampling

适用于辅助角色服务的 Application Insights SDK 支持固定速率采样和自适应采样。The Application Insights SDK for Worker Service supports both fixed-rate and adaptive sampling. 自适应采样默认已启用。Adaptive sampling is enabled by default. 为辅助角色服务配置采样的方式与对 ASP.NET Core 应用程序使用的方式相同。Configuring sampling for Worker Service is done the same way as for ASP.NET Core Applications.

添加 TelemetryInitializerAdding TelemetryInitializers

若要定义连同所有遥测数据一起发送的属性,请使用遥测初始化表达式Use telemetry initializers when you want to define properties that are sent with all telemetry.

将任何新的 TelemetryInitializer 添加到 DependencyInjection 容器,SDK 会自动将其添加到 TelemetryConfigurationAdd any new TelemetryInitializer to the DependencyInjection container and SDK will automatically add them to the TelemetryConfiguration.

    using Microsoft.ApplicationInsights.Extensibility;

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<ITelemetryInitializer, MyCustomTelemetryInitializer>();
        services.AddApplicationInsightsTelemetryWorkerService();
    }

删除 TelemetryInitializerRemoving TelemetryInitializers

默认已提供遥测初始化表达式。Telemetry initializers are present by default. 若要删除所有或特定的遥测初始化表达式,请在调用 AddApplicationInsightsTelemetryWorkerService() 之后使用以下示例代码。To remove all or specific telemetry initializers, use the following sample code after you call AddApplicationInsightsTelemetryWorkerService().

   public void ConfigureServices(IServiceCollection services)
   {
        services.AddApplicationInsightsTelemetryWorkerService();
        // Remove a specific built-in telemetry initializer
        var tiToRemove = services.FirstOrDefault<ServiceDescriptor>
                            (t => t.ImplementationType == typeof(AspNetCoreEnvironmentTelemetryInitializer));
        if (tiToRemove != null)
        {
            services.Remove(tiToRemove);
        }

        // Remove all initializers
        // This requires importing namespace by using Microsoft.Extensions.DependencyInjection.Extensions;
        services.RemoveAll(typeof(ITelemetryInitializer));
   }

添加遥测处理程序Adding telemetry processors

可以使用 IServiceCollection 中的扩展方法 AddApplicationInsightsTelemetryProcessor 将自定义遥测处理程序添加到 TelemetryConfigurationYou can add custom telemetry processors to TelemetryConfiguration by using the extension method AddApplicationInsightsTelemetryProcessor on IServiceCollection. 使用高级筛选方案中的遥测处理程序可以更直接地控制要在发送到 Application Insights 服务的遥测数据中包含或排除哪些内容。You use telemetry processors in advanced filtering scenarios to allow for more direct control over what's included or excluded from the telemetry you send to the Application Insights service. 使用以下示例。Use the following example.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        services.AddApplicationInsightsTelemetryProcessor<MyFirstCustomTelemetryProcessor>();
        // If you have more processors:
        services.AddApplicationInsightsTelemetryProcessor<MySecondCustomTelemetryProcessor>();
    }

配置或删除默认的 TelemetryModuleConfiguring or removing default TelemetryModules

Application Insights 使用遥测模块自动收集有关特定工作负荷的遥测数据,无需手动跟踪。Application Insights uses telemetry modules to automatically collect telemetry about specific workloads without requiring manual tracking.

默认已启用以下自动收集模块。The following automatic-collection modules are enabled by default. 这些模块负责自动收集遥测数据。These modules are responsible for automatically collecting telemetry. 可以禁用或配置这些模块,以改变其默认行为。You can disable or configure them to alter their default behavior.

  • DependencyTrackingTelemetryModule
  • PerformanceCollectorModule
  • QuickPulseTelemetryModule
  • AppServicesHeartbeatTelemetryModule -(关于此遥测模块,目前存在问题。AppServicesHeartbeatTelemetryModule - (There is currently an issue involving this telemetry module. 有关临时解决方法,请参阅 GitHub 问题 1689。)For a temporary workaround see GitHub Issue 1689.)
  • AzureInstanceMetadataTelemetryModule

若要配置任何默认的 TelemetryModule,请按以下示例中所示使用 IServiceCollection 中的扩展方法 ConfigureTelemetryModule<T>To configure any default TelemetryModule, use the extension method ConfigureTelemetryModule<T> on IServiceCollection, as shown in the following example.

    using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
    using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector;

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetryWorkerService();

            // The following configures QuickPulseTelemetryModule.
            // Similarly, any other default modules can be configured.
            services.ConfigureTelemetryModule<QuickPulseTelemetryModule>((module, o) =>
            {
                module.AuthenticationApiKey = "keyhere";
            });

            // The following removes PerformanceCollectorModule to disable perf-counter collection.
            // Similarly, any other default modules can be removed.
            var performanceCounterService = services.FirstOrDefault<ServiceDescriptor>
                                        (t => t.ImplementationType == typeof(PerformanceCollectorModule));
            if (performanceCounterService != null)
            {
                services.Remove(performanceCounterService);
            }
    }

配置遥测通道Configuring telemetry channel

默认通道为 ServerTelemetryChannelThe default channel is ServerTelemetryChannel. 可按以下示例所示替代该通道。You can override it as the following example shows.

using Microsoft.ApplicationInsights.Channel;

    public void ConfigureServices(IServiceCollection services)
    {
        // Use the following to replace the default channel with InMemoryChannel.
        // This can also be applied to ServerTelemetryChannel.
        services.AddSingleton(typeof(ITelemetryChannel), new InMemoryChannel() {MaxTelemetryBufferCapacity = 19898 });

        services.AddApplicationInsightsTelemetryWorkerService();
    }

动态禁用遥测Disable telemetry dynamically

如果要有条件和动态地禁用遥测,可以在代码中的任何位置使用 ASP.NET Core 依赖项注入容器解析 TelemetryConfiguration 实例,并在其上设置 DisableTelemetry 标志。If you want to disable telemetry conditionally and dynamically, you may resolve TelemetryConfiguration instance with ASP.NET Core dependency injection container anywhere in your code and set DisableTelemetry flag on it.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetryWorkerService();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelemetryConfiguration configuration)
    {
        configuration.DisableTelemetry = true;
        ...
    }

常见问题Frequently asked questions

如何跟踪不会自动收集的遥测数据?How can I track telemetry that's not automatically collected?

使用构造函数注入获取 TelemetryClient 的实例,然后对其调用所需的 TrackXXX() 方法。Get an instance of TelemetryClient by using constructor injection, and call the required TrackXXX() method on it. 不建议创建新的 TelemetryClient 实例。We don't recommend creating new TelemetryClient instances. DependencyInjection 容器中已注册了 TelemetryClient 的单一实例,该实例与剩余的遥测功能共享 TelemetryConfigurationA singleton instance of TelemetryClient is already registered in the DependencyInjection container, which shares TelemetryConfiguration with rest of the telemetry. 仅当需要与剩余的遥测功能使用不同的配置时,才建议创建新的 TelemetryClient 实例。Creating a new TelemetryClient instance is recommended only if it needs a configuration that's separate from the rest of the telemetry.

是否可以使用 Visual Studio IDE 将 Application Insights 加入辅助角色服务项目?Can I use Visual Studio IDE to onboard Application Insights to a Worker Service project?

目前只有 ASP.NET/ASP.NET Core 应用程序支持 Visual Studio IDE 加入。Visual Studio IDE onboarding is currently supported only for ASP.NET/ASP.NET Core Applications. 当 Visual Studio 支持加入辅助角色服务应用程序时,本文档将会更新。This document will be updated when Visual Studio ships support for onboarding Worker service applications.

是否可以使用状态监视器之类的工具来启用 Application Insights 监视?Can I enable Application Insights monitoring by using tools like Status Monitor?

否。No. 状态监视器状态监视器 v2 目前仅支持 ASP.NET 4.x。Status Monitor and Status Monitor v2 currently support ASP.NET 4.x only.

如果在 Linux 中运行应用程序,是否支持所有功能?If I run my application in Linux, are all features supported?

是的。Yes. 此 SDK 的功能支持在所有平台中是相同的,不过存在以下例外情况:Feature support for this SDK is the same in all platforms, with the following exceptions:

  • 性能计数器仅在 Windows 中受支持,但“实时指标”中所示的进程 CPU/内存除外。Performance counters are supported only in Windows with the exception of Process CPU/Memory shown in Live Metrics.
  • 尽管默认已启用 ServerTelemetryChannel,但如果应用程序在 Linux 或 MacOS 中运行,出现网络问题时,通道不会自动创建本地存储文件夹来暂时保留遥测数据。Even though ServerTelemetryChannel is enabled by default, if the application is running in Linux or MacOS, the channel doesn't automatically create a local storage folder to keep telemetry temporarily if there are network issues. 由于这种限制,在出现暂时性的网络或服务器时,遥测数据将会丢失。Because of this limitation, telemetry is lost when there are temporary network or server issues. 若要解决此问题,请为通道配置一个本地文件夹:To work around this issue, configure a local folder for the channel:
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;

    public void ConfigureServices(IServiceCollection services)
    {
        // The following will configure the channel to use the given folder to temporarily
        // store telemetry items during network or Application Insights server issues.
        // User should ensure that the given folder already exists
        // and that the application has read/write permissions.
        services.AddSingleton(typeof(ITelemetryChannel),
                                new ServerTelemetryChannel () {StorageFolder = "/tmp/myfolder"});
        services.AddApplicationInsightsTelemetryWorkerService();
    }

示例应用程序Sample applications

.NET Core 控制台应用程序 如果使用的控制台应用程序是以 .NET Core(2.0 或更高版本)或 .NET Framework(4.7.2 或更高版本)编写的,请使用此示例.NET Core Console Application Use this sample if you are using a Console Application written in either .NET Core (2.0 or higher) or .NET Framework (4.7.2 or higher)

使用 HostedServices 的 ASP .NET Core 后台任务 如果在 Asp.Net Core 2.1/2.2 中操作,并根据此处的官方指南创建后台任务,请使用此示例ASP .NET Core background tasks with HostedServices Use this sample if you are in Asp.Net Core 2.1/2.2, and creating background tasks as per official guidance here

.NET Core 3.0 辅助角色服务 如果根据此处的官方指南创建了 .NET Core 3.0 辅助角色服务应用程序,请使用此示例.NET Core 3.0 Worker Service Use this sample if you have a .NET Core 3.0 Worker Service application as per official guidance here

开源 SDKOpen-source SDK

阅读代码或为其做出贡献Read and contribute to the code.

后续步骤Next steps