Worker Service 애플리케이션(비 HTTP 앱)에 대한 Application Insights

Application Insights SDK for Worker Service는 메시징, 백그라운드 작업 및 콘솔 애플리케이션과 같은 비 HTTP 워크로드에 가장 적합한 새 SDK입니다. 이러한 유형의 애플리케이션에는 기존 ASP.NET/ASP.NET Core 웹 애플리케이션과 같이 들어오는 HTTP 요청의 개념이 없습니다. 이러한 이유로 ASP.NET 또는 ASP.NET Core 애플리케이션에 Application Insights 패키지를 사용하는 것은 지원되지 않습니다.

참고 항목

다음 설명서는 Application Insights 클래식 API를 사용합니다. Application Insights에 대한 장기 플랜은 OpenTelemetry를 사용하여 데이터를 수집하는 것입니다. 자세한 내용은 .NET, Node.js, Python 및 Java 애플리케이션에 대해 Azure Monitor OpenTelemetry 사용을 참조하세요.

새 SDK는 자체적으로 원격 분석 컬렉션을 수행하지 않습니다. 대신 DependencyCollector, PerfCounterCollectorApplicationInsightsLoggingProvider와 같은 잘 알려진 기타 Application Insights 자동 수집기를 가져옵니다. 이 SDK는 IServiceCollection에 확장 메서드를 노출하여 원격 분석 수집을 사용하도록 설정하고 구성합니다.

지원되는 시나리오

Worker Service용 Application Insights SDK는 애플리케이션이 실행되는 위치나 방식과 관계없이 비 HTTP 애플리케이션에 가장 적합합니다. 애플리케이션이 실행 중이고 Azure에 네트워크로 연결되어 있는 경우, 원격 분석을 수집할 수 있습니다. Application Insights 모니터링은 .NET Core를 지원하는 모든 위치에서 지원됩니다. 해당 패키지는 새로 도입된 .NET Core Worker Service, ASP.NET Core의 백그라운드 작업, .NET Core 및 .NET Framework와 같은 콘솔 앱에서 사용할 수 있습니다.

필수 조건

유효한 Application Insights 연결 문자열이 있어야 합니다. 이 키는 원격 분석을 Application Insights로 보내는 데 필요합니다. 연결 문자열을 가져오기 위해 새 Application Insights 리소스를 만들어야 하는 경우 연결 문자열을 참조하세요.

참고 항목

2025년 3월 31일에 계측 키 수집에 대한 지원이 종료됩니다. 계측 키 수집은 계속 작동하지만 더 이상 기능에 대한 업데이트 또는 지원을 제공하지 않습니다. 연결 문자열로 전환하여 새로운 기능을 활용합니다.

Worker Service용 Application Insights SDK 사용

  1. 애플리케이션에 Microsoft.ApplicationInsights.WorkerService 패키지를 설치합니다. 다음 코드 조각에서는 프로젝트의 .csproj 파일에 추가해야 하는 변경 내용을 보여줍니다.

        <ItemGroup>
            <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" />
        </ItemGroup>
    
  2. APPLICATIONINSIGHTS_CONNECTION_STRING 환경 변수 또는 구성(appsettings.json)에서 연결 문자열을 구성합니다.

    Screenshot displaying Application Insights overview and connection string.

  3. serviceProvider.GetRequiredService<TelemetryClient>();를 호출하거나 Constructor Injection을 사용하여 ILogger 인스턴스 또는 DI(종속성 주입) 컨테이너의 TelemetryClient 인스턴스를 검색합니다. 이 단계에서는 TelemetryConfiguration 및 자동 수집 모듈을 설정하는 작업을 트리거합니다.

각 애플리케이션 유형에 대한 구체적인 지침은 다음 섹션에서 설명합니다.

.NET Core Worker Service 애플리케이션

전체 예제는 NuGet 웹 사이트에서 공유됩니다.

  1. .NET SDK를 다운로드하여 설치합니다.

  2. Microsoft Visual Studio에서 새 프로젝트 템플릿 또는 명령줄 dotnet new worker를 사용하여 새 Worker Service 프로젝트를 만듭니다.

  3. 애플리케이션에 Microsoft.ApplicationInsights.WorkerService 패키지를 추가합니다.

  4. 다음 예제와 같이 services.AddApplicationInsightsTelemetryWorkerService();Program.cs 클래스의 CreateHostBuilder() 메서드에 추가합니다.

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                    services.AddApplicationInsightsTelemetryWorkerService();
                });
    
  5. 다음 예제에 따라 Worker.cs를 수정합니다.

        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);
                }
            }
        }
    
  6. 연결 문자열을 설정합니다.

    Screenshot that shows Application Insights overview and connection string.

    참고 항목

    구성에서 연결 문자열을 지정하는 것이 좋습니다. 다음 코드 샘플에서는 appsettings.json에서 연결 문자열을 지정하는 방법을 보여줍니다. 게시하는 동안 appsettings.json이 애플리케이션 루트 폴더에 복사되었는지 확인합니다.

        {
            "ApplicationInsights":
            {
                "ConnectionString" : "InstrumentationKey=00000000-0000-0000-0000-000000000000;"
            },
            "Logging":
            {
                "LogLevel":
                {
                    "Default": "Warning"
                }
            }
        }
    

또는 APPLICATIONINSIGHTS_CONNECTION_STRING 환경 변수에 연결 문자열을 지정합니다.

일반적으로 APPLICATIONINSIGHTS_CONNECTION_STRING은 웹 작업으로 웹앱에 배포된 애플리케이션에 대한 연결 문자열을 지정합니다.

참고 항목

코드에 지정된 연결 문자열은 다른 옵션보다 우선하는 환경 변수 APPLICATIONINSIGHTS_CONNECTION_STRING보다 우선합니다.

호스트된 서비스를 활용한 ASP.NET Core 백그라운드 작업

이 문서에서는 ASP.NET Core 애플리케이션에서 백그라운드 작업을 만드는 방법을 설명합니다.

전체 예제는 이 GitHub 페이지에서 공유됩니다.

  1. 애플리케이션에 Microsoft.ApplicationInsights.WorkerService 패키지를 설치합니다.

  2. 다음 예제와 같이 services.AddApplicationInsightsTelemetryWorkerService();ConfigureServices() 메서드에 추가합니다.

        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>();
    
                    // connection string 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에 대한 코드입니다.

        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");
                }
            }
        }
    
  3. 연결 문자열을 설정합니다. 위의 .NET Worker Service 예제에서 동일한 appsettings.json을 사용합니다.

.NET Core/.NET Framework 콘솔 애플리케이션

이 문서의 시작 부분에서 설명한 것처럼 일반 콘솔 애플리케이션에서도 새 패키지를 사용하여 Application Insights 원격 분석을 사용하도록 설정할 수 있습니다. 해당 패키지는 netstandard2.0을 대상으로 하므로 .NET Core 이상의 콘솔 앱 및 .NET Framework 이상의 콘솔 앱에서 사용할 수 있습니다.

전체 예제는 이 GitHub 페이지에서 공유됩니다.

  1. 애플리케이션에 Microsoft.ApplicationInsights.WorkerService 패키지를 설치합니다.

  2. 다음 예제와 같이 Program.cs를 수정합니다.

        using Microsoft.ApplicationInsights;
        using Microsoft.ApplicationInsights.DataContracts;
        using Microsoft.ApplicationInsights.WorkerService;
        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/ connection string 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((ApplicationInsightsServiceOptions options) => options.ConnectionString = "InstrumentationKey=<instrumentation key here>");
    
                    // To pass a connection string
                    // - aiserviceoptions must be created
                    // - set connectionstring on it
                    // - pass it to AddApplicationInsightsTelemetryWorkerService()
    
                    // 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을 사용합니다. 이전 섹션의 예제와 동일한 방식으로 사용자 지정할 수 있습니다.

애플리케이션 실행

애플리케이션을 실행합니다. 앞의 모든 예제의 작업자는 1초마다 bing.com에 HTTP를 호출하고 또한 ILogger를 사용하여 몇 개의 로그를 내보냅니다. 해당 선은 작업을 만드는 데 사용되는 TelemetryClientStartOperation 호출 내에 래핑됩니다. 이 예제에서는 RequestTelemetry의 이름은 "operation"입니다.

Application Insights는 기본적으로 경고 이상의 심각도 및 종속성을 사용하여 이러한 ILogger 로그를 수집합니다. 부모-자식 관계를 통해 RequestTelemetry와 상관 관계가 있습니다. 상관 관계는 프로세스/네트워크 경계 간에도 작동합니다. 예를 들어, 모니터링되는 다른 구성 요소에 대한 호출을 수행하는 경우, 해당 구성 요소의 부모와도 상관 관계가 지정됩니다.

RequestTelemetry의 사용자 지정 작업은 일반적인 웹 애플리케이션에서 들어오는 웹 요청과 동등한 것으로 간주할 수 있습니다. 작업을 사용할 필요는 없지만 Application Insights 상관 관계 데이터 모델에 가장 적합합니다. RequestTelemetry는 부모 작업 역할을 하며, 작업자 반복 내에 생성된 모든 원격 분석은 논리적으로 동일한 작업에 속하는 것으로 처리됩니다.

해당 방법을 사용하면 생성된 모든 원격 분석(자동 및 수동 모두)도 동일하게 operation_id을 포함합니다. 샘플링은 operation_id를 기반으로 하기 때문에 샘플링 알고리즘은 단일 반복에서 모든 원격 분석을 유지하거나 삭제합니다.

다음 섹션은 Application Insights가 자동으로 수집하는 전체 원격 분석을 나열합니다.

라이브 메트릭

라이브 메트릭은 Application Insights 모니터링이 올바르게 구성되었는지 여부를 빠르게 확인하는 데 사용할 수 있습니다. 원격 분석이 포털 및 분석에 표시되는 데 몇 분 정도 걸릴 수 있지만 라이브 메트릭은 실행 중인 프로세스의 CPU 사용량을 거의 실시간으로 표시합니다. 또한 요청, 종속성, 추적 등의 다른 원격 분석 데이터도 표시할 수 있습니다.

ILogger 로그

경고의 심각도 또는 그 이상으로 ILogger를 통해 보내진 로그는 자동으로 캡처됩니다. 이 동작을 변경하려면 다음 코드와 같이 공급자 ApplicationInsights에 대한 로깅 구성을 명시적으로 재정의합니다. 다음 구성을 사용하면 Application Insights에서 Information 로그 및 더 심각한 로그를 모두 캡처할 수 있습니다.

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    },
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Information"
      }
    }
  }
}

다음 예로 인해 Application Insights 공급자가 Information 로그를 캡처하지는 않는다는 점에 주의해야 합니다. 캡처하지 않는 이유는 SDK가 ApplicationInsightsWarning 로그 및 더 심각한 로그만 캡처하도록 지시하는 기본 로깅 필터를 추가하기 때문입니다. Application Insights에는 명시적 재정의가 필요합니다.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  }
}

자세한 내용은 ILogger 문서에 따라 Application Insights에서 캡처하는 로그 수준을 사용자 지정합니다.

종속성

종속성 수집은 기본적으로 사용하도록 설정됩니다. Application Insights의 종속성 추적 문서에서는 자동으로 수집되는 종속성에 대해 설명하고 수동 추적을 수행하는 단계도 포함되어 있습니다.

EventCounter

EventCounterCollectionModule은 기본적으로 사용하도록 설정되며, .NET 앱에서 카운터의 기본 집합을 수집합니다. EventCounter 자습서는 수집된 카운터의 기본 세트를 나열됩니다. 또한 목록을 사용자 지정하는 방법에 대한 지침도 있습니다.

다른 원격 분석 수동 추적

SDK는 설명한 대로 원격 분석 데이터를 자동으로 수집할 때, 대부분의 경우 사용자는 Application Insights에 기타 원격 분석 데이터를 전송해야 합니다. 기타 원격 분석 데이터를 추적하는 데 있어 권장되는 방법은 종속성 삽입에서 TelemetryClient의 인스턴스를 가져온 다음 지원되는 TrackXXX()API 메서드 중 하나를 호출하는 것입니다. 또 다른 일반적 사용 사례는 작업의 사용자 지정 추적입니다. 해당 방법은 이전의 Worker 예제에 설명되어 있습니다.

Application Insights SDK 구성

Worker Service SDK에서 사용하는 기본값 TelemetryConfiguration은 ASP.NET 또는 ASP.NET Core 애플리케이션에서 사용되는 자동 구성과 유사하며, HttpContext의 원격 분석 데이터를 보강하는 데 사용되는 TelemetryInitializers를 제외합니다.

Worker Service에 대한 Application Insights SDK를 사용자 지정하여 기본값 구성을 변경할 수 있습니다. Application Insights ASP.NET Core SDK의 사용자라면 종속성 삽입에 기본 제공된 ASP.NET Core를 사용하여 구성을 변경하는 방법을 이미 숙지하고 있을 것입니다. 또한 Worker Service SDK는 유사한 원칙을 기반으로 합니다. 다음 섹션에 설명된 대로 IServiceCollection에서 적절한 메서드를 호출하여 ConfigureServices() 섹션의 거의 모든 구성 변경을 수행합니다.

참고 항목

해당 SDK를 사용하는 동안 TelemetryConfiguration.Active을 수정하여 구성을 변경하는 것은 지원되지 않으며 변경 내용은 반영되지 않습니다.

ApplicationInsightsServiceOptions 사용

몇 가지 일반적인 설정은 다음 예제와 같이 ApplicationInsightsServiceOptionsAddApplicationInsightsTelemetryWorkerService에 전달하여 수정할 수 있습니다.

using Microsoft.ApplicationInsights.WorkerService;

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

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

이 SDK의 ApplicationInsightsServiceOptions는 ASP.NET Core SDK의 Microsoft.ApplicationInsights.AspNetCore.Extensions와 달리 네임스페이스 Microsoft.ApplicationInsights.WorkerService에 있습니다.

다음 표에는 ApplicationInsightsServiceOptions에서 자주 사용되는 설정이 나열되어 있습니다.

설정 설명 기본값
EnableQuickPulseMetricStream 라이브 메트릭 기능을 사용하거나 사용하지 않도록 설정합니다. True
EnableAdaptiveSampling 적응 샘플링 사용/사용 안 함. True
EnableHeartbeat 하트비트 기능 사용/사용 안 함. 이는 해당하는 경우 런타임 관련 정보(예: .NET 버전, Azure 환경)와 함께 "HeartBeatState"라는 사용자 지정 메트릭을 주기적으로(기본값 15분) 보냅니다. True
AddAutoCollectedMetricExtractor AutoCollectedMetrics 추출기 사용/사용 안 함. 이는 샘플링을 수행하기 전에 요청/종속성에 대해 미리 집계된 메트릭을 보내는 TelemetryProcessor입니다. True
EnableDiagnosticsTelemetryModule DiagnosticsTelemetryModule 사용/사용 안 함. 이 설정을 사용하지 않도록 설정하면 EnableHeartbeat, EnableAzureInstanceMetadataTelemetryModule, EnableAppServicesHeartbeatTelemetryModule 설정이 무시됩니다. True

최신 목록은 ApplicationInsightsServiceOptions의 구성 가능한 설정을 참조하세요.

샘플링

Application Insights SDK for Worker Service는 고정 비율 샘플링적응 샘플링을 모두 지원합니다. 적응 샘플링은 기본적으로 사용하도록 설정됩니다. ApplicationInsightsServiceOptionsEnableAdaptiveSampling 옵션을 사용하여 샘플링 기능을 사용하지 않도록 설정할 수 있습니다.

다른 샘플링 설정을 구성하려면 다음 예제를 사용할 수 있습니다.

using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.ApplicationInsights.Extensibility;

var builder = WebApplication.CreateBuilder(args);

builder.Services.Configure<TelemetryConfiguration>(telemetryConfiguration =>
{
   var telemetryProcessorChainBuilder = telemetryConfiguration.DefaultTelemetrySink.TelemetryProcessorChainBuilder;

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

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

builder.Services.AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions
{
   EnableAdaptiveSampling = false,
});

var app = builder.Build();

자세한 내용은 샘플링 문서를 참조하세요.

원격 분석 이니셜라이저 추가

모든 원격 분석 데이터와 함께 전송되는 속성을 정의하려는 경우, 원격 분석 이니셜라이저를 사용합니다.

DependencyInjection 컨테이너에 새 원격 분석 이니셜라이저를 추가하면 SDK가 이를 자동으로 TelemetryConfiguration에 추가합니다.

    using Microsoft.ApplicationInsights.Extensibility;

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

원격 분석 이니셜라이저 제거

원격 분석 이니셜라이저는 기본적으로 제공됩니다. 모든 또는 특정 원격 분석 이니셜라이저를 제거하려면 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));
   }

원격 분석 프로세서 추가

IServiceCollection에서 확장 메서드 AddApplicationInsightsTelemetryProcessor를 사용하여 사용자 지정 원격 분석 프로세서를 TelemetryConfiguration에 추가할 수 있습니다. 고급 필터링 시나리오에서 원격 분석 프로세서를 사용하여, Application Insights로 보내는 원격 분석 데이터에서 포함되거나 제외되는 항목을 보다 직접적으로 제어할 수 있습니다. 다음 예제를 사용합니다.

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

기본 원격 분석 모듈 구성 또는 제거

Application Insights는 원격 분석 모듈을 사용하여 수동으로 추적할 필요 없이 특정 워크로드에 대한 원격 분석 데이터를 자동으로 수집합니다.

다음 자동 수집 모듈은 기본적으로 사용하도록 설정되어 있습니다. 이러한 자동 수집 모듈은 원격 분석을 자동으로 수집해야 합니다. 자동 수집 모듈을 사용하지 않도록 설정하거나 해당 기본 동작을 변경하도록 구성할 수 있습니다.

  • DependencyTrackingTelemetryModule
  • PerformanceCollectorModule
  • QuickPulseTelemetryModule
  • AppServicesHeartbeatTelemetryModule(현재 이 원격 분석 모듈과 관련된 문제가 있습니다. 임시 해결 방법은 GitHub 문제 1689를 참조하세요.)
  • AzureInstanceMetadataTelemetryModule

기본 원격 분석 모듈을 구성하려면 다음 예제와 같이 IServiceCollection에서 ConfigureTelemetryModule<T> 확장 메서드를 사용합니다.

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

원격 분석 채널 구성

기본 채널은 ServerTelemetryChannel입니다. 이는 다음 예제와 같이 재정의할 수 있습니다.

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

동적으로 원격 분석 사용 안 함

원격 분석을 조건부로, 동적으로 사용하지 않도록 설정하려는 경우 코드의 어느 위치에서나 ASP.NET Core 종속성 삽입 컨테이너를 사용하여 TelemetryConfiguration 인스턴스를 확인하고 이 인스턴스에 DisableTelemetry 플래그를 설정할 수 있습니다.

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

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

자주 묻는 질문

이 섹션에서는 일반적인 질문에 대한 답변을 제공합니다.

어떤 패키지를 사용해야 하나요?

.NET Core 앱 시나리오 Package(패키지)
HostedServices가 없는 경우 WorkerService
HostedServices가 있는 경우 AspNetCore(WorkerService 아님)
HostedServices가 있는 경우, HostedServices만 모니터링 WorkerService(드문 시나리오)

AspNetCore 패키지를 사용하는 .NET Core 앱 내의 HostedServices에 TelemetryClient가 삽입될 수 있나요?

예. 구성은 웹 애플리케이션의 나머지 부분과 공유됩니다.

자동으로 수집되지 않는 원격 분석을 추적하려면 어떻게 해야 하나요?

생성자 삽입을 사용하여 TelemetryClient의 인스턴스를 가져오고, 이 인스턴스에 필요한 TrackXXX() 메서드를 호출합니다. 새로 TelemetryClient 인스턴스를 만드는 것은 권장하지 않습니다. TelemetryClient의 싱글톤 인스턴스는 나머지 원격 분석과 TelemetryConfiguration을 공유하는 DependencyInjection 컨테이너에 이미 등록되어 있습니다. 새 TelemetryClient 인스턴스를 만드는 것은 나머지 원격 분석과 분리된 구성이 필요한 경우에만 권장됩니다.

Visual Studio IDE를 사용하여 Worker Service 프로젝트에 Application Insights를 온보딩할 수 있나요?

Visual Studio IDE의 온보딩은 현재 ASP.NET/ASP.NET Core 애플리케이션에 대해서만 지원하고 있습니다. 이 문서는 Visual Studio에서 Worker Service 애플리케이션에 대한 온보딩을 지원할 때 업데이트될 예정입니다.

Azure Monitor Application Insights Agent(이전의 상태 모니터 v2)와 같은 도구를 사용하여 Application Insights 모니터링을 사용하도록 설정할 수 있나요?

아니요. Azure Monitor Application Insights Agent는 현재 .NET만 지원합니다.

애플리케이션을 Linux에서 실행하는 경우 모든 기능이 지원되나요?

예. 해당 SDK에 대한 기능 지원은 모든 플랫폼에서 동일하지만 다음과 같은 경우는 예외입니다.

  • 성능 카운터는 라이브 메트릭에 표시된 프로세스 CPU/메모리를 제외하고 Windows에서만 지원됩니다.

  • ServerTelemetryChannel을 기본적으로 사용하도록 설정하는 경우에도 애플리케이션이 Linux 또는 macOS에서 실행될 때 네트워크 문제가 있으면 채널에서 원격 분석을 일시적으로 유지하기 위해 로컬 스토리지 폴더를 자동으로 만들지 않습니다. 이 제한으로 인해 일시적인 네트워크 또는 서버 문제가 있으면 원격 분석이 손실됩니다. 이 문제를 해결하려면 다음과 같이 채널에 대한 로컬 폴더를 구성합니다.

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

샘플 애플리케이션

.Net Core 콘솔 애플리케이션: .NET Core(2.0 이상) 또는 .NET Framework(4.7.2 이상)로 작성된 콘솔 애플리케이션을 사용하는 경우, 해당 샘플을 사용합니다.

HostedServices를 통한 ASP.NET Core 백그라운드 작업 ASP.NET Core를 사용하여 공식 지침에 따라 백그라운드 작업을 만드는 경우 이 샘플을 사용합니다.

.Net Core Worker Service: .NET Worker Service 애플리케이션이 있는 경우 공식 지침에 따라 이 샘플을 사용합니다.

오픈 소스 SDK

코드를 읽고 기여합니다.

최신 업데이트 및 버그 수정에 대해서는 릴리스 정보를 참조하세요.

다음 단계