.NET 콘솔 애플리케이션용 Application Insights

Application Insights를 사용하여 웹 애플리케이션의 가용성, 성능 및 사용량을 모니터링할 수 있습니다.

시작

  • Azure Portal Application Insights 리소스를 만듭니다.

  • 연결 문자열의 복사본을 가져옵니다. 만든 새 리소스의 필수 드롭다운에서 연결 문자열을 찾습니다.

  • 최신 Microsoft.ApplicationInsights 패키지를 설치합니다.

  • 원격 분석을 추적하기 전에(또는 APPLICATIONINSIGHTS_CONNECTION_STRING 환경 변수를 설정하기 전에) 코드에서 연결 문자열을 설정합니다. 그런 다음, 수동으로 원격 분석을 추적하고 Azure Portal에서 확인할 수 있습니다.

    // You may use different options to create configuration as shown later in this article
    TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
    configuration.ConnectionString = <Copy connection string from Application Insights Resource Overview>;
    var telemetryClient = new TelemetryClient(configuration);
    telemetryClient.TrackTrace("Hello World!");
    

    참고

    원격 분석은 즉시 전송되지 않습니다. 항목은 일괄 처리되어 ApplicationInsights SDK에 의해 전송됩니다. 콘솔 앱은 Track() 메서드를 호출한 후 종료됩니다.

    이 문서 뒷부분의 전체 예에 표시된 것처럼 앱이 종료되기 전에 Flush()Sleep/Delay가 완료되지 않으면 원격 분석이 전송되지 않을 수 있습니다. InMemoryChannel을 사용하는 경우 Sleep은 필요하지 않습니다.

  • 최신 버전의 Microsoft.ApplicationInsights.DependencyCollector 패키지를 설치합니다. HTTP, SQL 또는 기타 외부 의존 관계 호출을 자동으로 추적합니다.

코드에서 또는 ApplicationInsights.config 파일을 사용하여 Application Insights를 초기화하고 구성할 수 있습니다. 가능한 한 조기에 초기화를 수행해야 합니다.

참고

ApplicationInsights.config는 .NET Core 애플리케이션에서 지원되지 않습니다.

구성 파일 사용

.NET Framework 기반 애플리케이션의 경우 기본적으로 Application Insights SDK는 TelemetryConfiguration이 만들어질 때 작업 디렉터리에서 ApplicationInsights.config 파일을 찾습니다. 구성 파일 읽기는 .NET Core에서 지원되지 않습니다.

TelemetryConfiguration config = TelemetryConfiguration.Active; // Reads ApplicationInsights.config file if present

구성 파일의 경로를 지정할 수도 있습니다.

using System.IO;
TelemetryConfiguration configuration = TelemetryConfiguration.CreateFromConfiguration(File.ReadAllText("C:\\ApplicationInsights.config"));
var telemetryClient = new TelemetryClient(configuration);

최신 버전의 Microsoft.ApplicationInsights.WindowsServer 패키지를 설치하여 구성 파일의 전체 예를 가져올 수 있습니다. 다음은 코드 예와 동일한 종속 컬렉션의 최소 구성입니다.

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
  <ConnectionString>"Copy connection string from Application Insights Resource Overview"</ConnectionString>
  <TelemetryInitializers>
    <Add Type="Microsoft.ApplicationInsights.DependencyCollector.HttpDependenciesParsingTelemetryInitializer, Microsoft.AI.DependencyCollector"/>
  </TelemetryInitializers>
  <TelemetryModules>
    <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
      <ExcludeComponentCorrelationHttpHeadersOnDomains>
        <Add>core.windows.net</Add>
        <Add>core.chinacloudapi.cn</Add>
        <Add>core.cloudapi.de</Add>
        <Add>core.usgovcloudapi.net</Add>
        <Add>localhost</Add>
        <Add>127.0.0.1</Add>
      </ExcludeComponentCorrelationHttpHeadersOnDomains>
      <IncludeDiagnosticSourceActivities>
        <Add>Microsoft.Azure.ServiceBus</Add>
        <Add>Microsoft.Azure.EventHubs</Add>
      </IncludeDiagnosticSourceActivities>
    </Add>
  </TelemetryModules>
  <TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel"/>
</ApplicationInsights>

코드에서 원격 분석 컬렉션 구성

참고

구성 파일 읽기는 .NET Core에서 지원되지 않습니다.

  • 애플리케이션 시작 중에 DependencyTrackingTelemetryModule 인스턴스를 만들고 구성합니다. 단일 데이터베이스여야 하며 애플리케이션 수명 동안 보존되어야 합니다.

    var module = new DependencyTrackingTelemetryModule();
    
    // prevent Correlation Id to be sent to certain endpoints. You may add other domains as needed.
    module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");
    //...
    
    // enable known dependency tracking, note that in future versions, we will extend this list. 
    // please check default settings in https://github.com/Microsoft/ApplicationInsights-dotnet-server/blob/develop/Src/DependencyCollector/DependencyCollector/ApplicationInsights.config.install.xdt
    
    module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus");
    module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs");
    //....
    
    // initialize the module
    module.Initialize(configuration);
    
  • 공용 원격 분석 이니셜라이저 추가

    // ensures proper DependencyTelemetry.Type is set for Azure RESTful API calls
    configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());
    

    일반 TelemetryConfiguration() 생성자를 사용하여 구성을 만든 경우 상관 관계 지원을 추가로 사용하도록 설정해야 합니다. 파일에서 구성을 읽거나 TelemetryConfiguration.CreateDefault() 또는 TelemetryConfiguration.Active를 사용한 경우 필요하지 않습니다.

    configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
    
  • 이 웹 사이트에 설명된 대로 성능 카운터 수집기 모듈을 설치하고 초기화하는 것도 좋습니다.

전체 예제

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DependencyCollector;
using Microsoft.ApplicationInsights.Extensibility;
using System.Net.Http;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();

            configuration.ConnectionString = "removed";
            configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());

            var telemetryClient = new TelemetryClient(configuration);
            using (InitializeDependencyTracking(configuration))
            {
                // run app...

                telemetryClient.TrackTrace("Hello World!");

                using (var httpClient = new HttpClient())
                {
                    // Http dependency is automatically tracked!
                    httpClient.GetAsync("https://microsoft.com").Wait();
                }

            }

            // before exit, flush the remaining data
            telemetryClient.Flush();

            // Console apps should use the WorkerService package.
            // This uses ServerTelemetryChannel which does not have synchronous flushing.
            // For this reason we add a short 5s delay in this sample.
            
            Task.Delay(5000).Wait();

            // If you're using InMemoryChannel, Flush() is synchronous and the short delay is not required.

        }

        static DependencyTrackingTelemetryModule InitializeDependencyTracking(TelemetryConfiguration configuration)
        {
            var module = new DependencyTrackingTelemetryModule();

            // prevent Correlation Id to be sent to certain endpoints. You may add other domains as needed.
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.chinacloudapi.cn");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.cloudapi.de");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.usgovcloudapi.net");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("localhost");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("127.0.0.1");

            // enable known dependency tracking, note that in future versions, we will extend this list. 
            // please check default settings in https://github.com/microsoft/ApplicationInsights-dotnet-server/blob/develop/WEB/Src/DependencyCollector/DependencyCollector/ApplicationInsights.config.install.xdt

            module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus");
            module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs");

            // initialize the module
            module.Initialize(configuration);

            return module;
        }
    }
}