다음을 통해 공유


ASP.NET 및 ASP.NET Core 애플리케이션용 Application Insights

주의

새 애플리케이션 또는 고객이 Azure Monitor Application Insights에 전원을 공급하려면 Azure Monitor OpenTelemetry Distro를 사용하는 것이 좋습니다. Azure Monitor OpenTelemetry Distro는 Application Insights SDK와 유사한 기능과 환경을 제공합니다. .NET, Node.jsPython에 대한 마이그레이션 가이드를 사용하여 Application Insights SDK에서 마이그레이션할 수 있지만 이전 버전과의 호환성을 위해 몇 가지 기능을 더 추가하기 위해 노력하고 있습니다.

이 문서에서는 ASP.NET 및 ASP.NET Core 애플리케이션에 대해 Application Insights를 사용하도록 설정하고 구성하는 방법을 설명합니다. 이 절차에서는 Application Insights에 원격 분석을 보내도록 애플리케이션을 구성합니다.

Application Insights는 ASP.NET 및 ASP.NET Core 애플리케이션에서 다음 원격 분석을 수집할 수 있습니다.

  • 요청
  • 종속성
  • 예외
  • 성능 계수기
  • 추적(로그)
  • 하트비트
  • 사용자 지정 이벤트 및 메트릭 (수동 계측 필요)
  • 페이지 보기 (웹 페이지에 JavaScript SDK 필요)
  • 가용성 테스트(가용성 테스트를 수동으로 설정해야 합니다.)

지원되는 시나리오

참고

ASP.NET Core용 Application Insights SDK는 실행되는 위치 또는 방법에 관계없이 애플리케이션을 모니터링할 수 있습니다. 애플리케이션이 실행 중이고 Azure에 네트워크로 연결되어 있는 경우 원격 분석을 수집할 수 있습니다. Application Insights 모니터링은 .NET Core를 지원하는 모든 위치에서 지원됩니다.

지원됨 ASP.NET ASP.NET Core
운영 체제 윈도우즈 Windows, Linux 또는 Mac
호스팅 방법 프로세스 내(IIS 또는 IIS Express) 프로세스 내부 또는 프로세스 외부
배포 방법 웹 배포, MSI 또는 수동 파일 복사 프레임워크 종속 또는 자체 포함
웹 서버 IIS(인터넷 정보 서비스) IIS(인터넷 정보 서버) 또는 Kestrel
호스팅 플랫폼 Azure App Service(Windows), Azure Virtual Machines 또는 온-프레미스 서버 Azure App Service, Azure Virtual Machines, Docker 및 AKS(Azure Kubernetes Service)의 Web Apps 기능
.NET 버전 .NET Framework 4.6.1 이상 미리 보기에 없는 모든 공식적으로 지원되는 .NET 버전
IDE 비주얼 스튜디오 Visual Studio, Visual Studio Code 또는 명령줄

필수 조건

기본 웹앱 만들기

MVC 애플리케이션 예를 사용합니다. 작업자 서비스를 사용하는 경우 작업자 서비스 애플리케이션에 대한 Application Insights의 지침을 따릅니다.

  1. Visual Studio를 엽니다.
  2. 새 프로젝트 만들기를 선택합니다.
  3. C#으로 ASP.NET 웹 애플리케이션(.NET Framework)을 선택하고 다음을 선택합니다.
  4. 프로젝트 이름을 입력한 다음 만들기를 선택합니다.
  5. MVC를 선택한 다음 만들기를 선택합니다.

Application Insights 자동 추가(Visual Studio)

이 섹션에서는 템플릿 기반 웹앱에 Application Insights를 자동으로 추가하는 방법을 안내합니다.

참고

ASP.NET 애플리케이션에 독립 실행형 ILogger 공급자를 사용하려면 Microsoft.Extensions.Logging.ApplicationInsight를 사용합니다.

Visual Studio의 ASP.NET 웹앱 프로젝트 내에서:

  1. 프로젝트>Application Insights 원격 분석 추가>Application Insights Sdk(로컬)>다음>완료>닫기를 선택합니다.

  2. ApplicationInsights.config 파일을 엽니다.

  3. 닫는 </ApplicationInsights> 태그 앞에 Application Insights 리소스에 대한 연결 문자열이 포함된 선을 추가합니다. 새로 만든 Application Insights 리소스의 개요 창에서 연결 문자열을 찾습니다.

    <ConnectionString>Copy connection string from Application Insights Resource Overview</ConnectionString>
    
  4. 프로젝트>NuGet 패키지 관리>업데이트를 선택합니다. 그런 다음, 각 Microsoft.ApplicationInsights NuGet 패키지를 안정적인 최신 릴리스로 업데이트합니다.

  5. IIS Express를 선택하여 애플리케이션을 실행합니다. 기본 ASP.NET 앱이 열립니다. 사이트의 페이지를 탐색할 때 원격 분석 데이터가 Application Insights로 전송됩니다.

Application Insights를 수동으로 추가(Visual Studio 없음)

이 섹션에서는 템플릿 기반 웹앱에 Application Insights를 수동으로 추가하는 방법을 안내합니다.

  1. 다음 NuGet 패키지 및 해당 종속성을 프로젝트에 추가합니다.

  2. 경우에 따라 ApplicationInsights.config 파일이 자동으로 만들어집니다. 파일이 이미 있는 경우 4단계로 건너뜁니다.

    없으면 직접 만들어라. ASP.NET 애플리케이션의 루트 디렉터리에서 ApplicationInsights.config라는 새 파일을 만듭니다.

  3. 다음 XML 구성을 새로 만든 파일에 복사합니다.

    <?xml version="1.0" encoding="utf-8"?>
    <ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
      <TelemetryInitializers>
        <Add Type="Microsoft.ApplicationInsights.DependencyCollector.HttpDependenciesParsingTelemetryInitializer, Microsoft.AI.DependencyCollector" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.BuildInfoConfigComponentVersionTelemetryInitializer, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.Web.WebTestTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.SyntheticUserAgentTelemetryInitializer, Microsoft.AI.Web">
          <!-- Extended list of bots:
                search|spider|crawl|Bot|Monitor|BrowserMob|BingPreview|PagePeeker|WebThumb|URL2PNG|ZooShot|GomezA|Google SketchUp|Read Later|KTXN|KHTE|Keynote|Pingdom|AlwaysOn|zao|borg|oegp|silk|Xenu|zeal|NING|htdig|lycos|slurp|teoma|voila|yahoo|Sogou|CiBra|Nutch|Java|JNLP|Daumoa|Genieo|ichiro|larbin|pompos|Scrapy|snappy|speedy|vortex|favicon|indexer|Riddler|scooter|scraper|scrubby|WhatWeb|WinHTTP|voyager|archiver|Icarus6j|mogimogi|Netvibes|altavista|charlotte|findlinks|Retreiver|TLSProber|WordPress|wsr-agent|http client|Python-urllib|AppEngine-Google|semanticdiscovery|facebookexternalhit|web/snippet|Google-HTTP-Java-Client-->
          <Filters>search|spider|crawl|Bot|Monitor|AlwaysOn</Filters>
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Web.ClientIpHeaderTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.AzureAppServiceRoleNameFromHostNameHeaderInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.OperationNameTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.OperationCorrelationTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.UserTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.AuthenticatedUserIdTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.AccountIdTelemetryInitializer, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.SessionTelemetryInitializer, Microsoft.AI.Web" />
      </TelemetryInitializers>
      <TelemetryModules>
        <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
          <ExcludeComponentCorrelationHttpHeadersOnDomains>
            <!-- 
            Requests to the following hostnames will not be modified by adding correlation headers.
            Add entries here to exclude additional hostnames.
            NOTE: this configuration will be lost upon NuGet upgrade.
            -->
            <Add>core.windows.net</Add>
            <Add>core.chinacloudapi.cn</Add>
            <Add>core.cloudapi.de</Add>
            <Add>core.usgovcloudapi.net</Add>
          </ExcludeComponentCorrelationHttpHeadersOnDomains>
          <IncludeDiagnosticSourceActivities>
            <Add>Microsoft.Azure.EventHubs</Add>
            <Add>Azure.Messaging.ServiceBus</Add>
          </IncludeDiagnosticSourceActivities>
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector">
          <!--
          Use the following syntax here to collect additional performance counters:
    
          <Counters>
            <Add PerformanceCounter="\Process(??APP_WIN32_PROC??)\Handle Count" ReportAs="Process handle count" />
            ...
          </Counters>
    
          PerformanceCounter must be either \CategoryName(InstanceName)\CounterName or \CategoryName\CounterName
    
          NOTE: performance counters configuration will be lost upon NuGet upgrade.
    
          The following placeholders are supported as InstanceName:
            ??APP_WIN32_PROC?? - instance name of the application process  for Win32 counters.
            ??APP_W3SVC_PROC?? - instance name of the application IIS worker process for IIS/ASP.NET counters.
            ??APP_CLR_PROC?? - instance name of the application CLR process for .NET counters.
          -->
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryModule, Microsoft.AI.PerfCounterCollector" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.AppServicesHeartbeatTelemetryModule, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureInstanceMetadataTelemetryModule, Microsoft.AI.WindowsServer">
          <!--
          Remove individual fields collected here by adding them to the ApplicationInsighs.HeartbeatProvider
          with the following syntax:
    
          <Add Type="Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule, Microsoft.ApplicationInsights">
            <ExcludedHeartbeatProperties>
              <Add>osType</Add>
              <Add>___location</Add>
              <Add>name</Add>
              <Add>offer</Add>
              <Add>platformFaultDomain</Add>
              <Add>platformUpdateDomain</Add>
              <Add>publisher</Add>
              <Add>sku</Add>
              <Add>version</Add>
              <Add>vmId</Add>
              <Add>vmSize</Add>
              <Add>subscriptionId</Add>
              <Add>resourceGroupName</Add>
              <Add>placementGroupId</Add>
              <Add>tags</Add>
              <Add>vmScaleSetName</Add>
            </ExcludedHeartbeatProperties>
          </Add>
    
          NOTE: exclusions will be lost upon upgrade.
          -->
        </Add>
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule, Microsoft.AI.WindowsServer" />
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule, Microsoft.AI.WindowsServer">
          <!--</Add>
        <Add Type="Microsoft.ApplicationInsights.WindowsServer.FirstChanceExceptionStatisticsTelemetryModule, Microsoft.AI.WindowsServer">-->
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule, Microsoft.AI.Web">
          <Handlers>
            <!-- 
            Add entries here to filter out additional handlers:
    
            NOTE: handler configuration will be lost upon NuGet upgrade.
            -->
            <Add>Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler</Add>
            <Add>System.Web.StaticFileHandler</Add>
            <Add>System.Web.Handlers.AssemblyResourceLoader</Add>
            <Add>System.Web.Optimization.BundleHandler</Add>
            <Add>System.Web.Script.Services.ScriptHandlerFactory</Add>
            <Add>System.Web.Handlers.TraceHandler</Add>
            <Add>System.Web.Services.Discovery.DiscoveryRequestHandler</Add>
            <Add>System.Web.HttpDebugHandler</Add>
          </Handlers>
        </Add>
        <Add Type="Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule, Microsoft.AI.Web" />
        <Add Type="Microsoft.ApplicationInsights.Web.AspNetDiagnosticTelemetryModule, Microsoft.AI.Web" />
      </TelemetryModules>
      <ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights" />
      <TelemetrySinks>
        <Add Name="default">
          <TelemetryProcessors>
            <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryProcessor, Microsoft.AI.PerfCounterCollector" />
            <Add Type="Microsoft.ApplicationInsights.Extensibility.AutocollectedMetricsExtractor, Microsoft.ApplicationInsights" />
            <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>
            <!--
              Adjust the include and exclude examples to specify the desired semicolon-delimited types. (Dependency, Event, Exception, PageView, Request, Trace)
            -->
          </TelemetryProcessors>
          <TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel" />
        </Add>
      </TelemetrySinks>
      <!-- 
        Learn more about Application Insights configuration with ApplicationInsights.config here:
        http://go.microsoft.com/fwlink/?LinkID=513840
      -->
      <ConnectionString>Copy the connection string from your Application Insights resource</ConnectionString>
    </ApplicationInsights>
    
  4. 두 가지 방법으로 수행할 수 있는 연결 문자열 추가합니다.

    • (권장) 구성에서 연결 문자열 설정합니다.

      </ApplicationInsights> 파일의 마지막 태그 앞에 Application Insights 리소스의 연결 문자열을 추가하십시오. 새로 만든 Application Insights 리소스의 개요 창에서 연결 문자열을 찾습니다.

      <ConnectionString>Copy the connection string from your Application Insights resource</ConnectionString>
      
    • 코드에서 연결 문자열 설정합니다.

      program.cs 클래스에 연결 문자열 제공합니다.

      var configuration = new TelemetryConfiguration
      {
          ConnectionString = "Copy the connection string from your Application Insights resource"
      };
      
  5. ApplicationInsights.config 파일과 동일한 프로젝트 수준에서 AiHandleErrorAttribute.cs라는 새 C# 파일이 있는 ErrorHandler라는 폴더를 만듭니다. 파일의 콘텐츠는 다음과 같습니다.

    using System;
    using System.Web.Mvc;
    using Microsoft.ApplicationInsights;
    
    namespace WebApplication10.ErrorHandler //namespace will vary based on your project name
    {
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
        public class AiHandleErrorAttribute : HandleErrorAttribute
        {
            public override void OnException(ExceptionContext filterContext)
            {
                if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
                {
                    //If customError is Off, then AI HTTPModule will report the exception
                    if (filterContext.HttpContext.IsCustomErrorEnabled)
                    {   
                        var ai = new TelemetryClient();
                        ai.TrackException(filterContext.Exception);
                    } 
                }
                base.OnException(filterContext);
            }
        }
    }
    
  6. App_Start 폴더에서 FilterConfig.cs 파일을 열어 샘플과 일치하도록 변경합니다.

    using System.Web;
    using System.Web.Mvc;
    
    namespace WebApplication10 //Namespace will vary based on project name
    {
        public class FilterConfig
        {
            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new ErrorHandler.AiHandleErrorAttribute());
            }
        }
    }
    
  7. Web.config가 이미 업데이트된 경우 이 단계를 건너뜁니다. 그러지 않으면 파일을 다음과 같이 업데이트합니다.

    <?xml version="1.0" encoding="utf-8"?>
    <!--
      For more information on how to configure your ASP.NET application, please visit
      https://go.microsoft.com/fwlink/?LinkId=301880
      -->
    <configuration>
      <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
      </appSettings>
      <system.web>
        <compilation debug="true" targetFramework="4.7.2" />
        <httpRuntime targetFramework="4.7.2" />
        <!-- Code added for Application Insights start -->
        <httpModules>
          <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" />
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
        </httpModules>
        <!-- Code added for Application Insights end -->
      </system.web>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
            <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
            <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
          </dependentAssembly>
          <!-- Code added for Application Insights start -->
          <dependentAssembly>
            <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.1" />
          </dependentAssembly>
          <!-- Code added for Application Insights end -->
        </assemblyBinding>
      </runtime>
      <system.codedom>
        <compilers>
          <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
          <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
        </compilers>
      </system.codedom>
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <!-- Code added for Application Insights start -->
        <modules>
          <remove name="TelemetryCorrelationHttpModule" />
          <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="managedHandler" />
          <remove name="ApplicationInsightsWebTracking" />
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
        </modules>
        <!-- Code added for Application Insights end -->
      </system.webServer>
    </configuration>
    

이제 서버 쪽 애플리케이션 모니터링을 성공적으로 구성했습니다. 웹앱을 실행하면 텔레메트리 데이터가 Application Insights에서 수집되기 시작합니다.

애플리케이션 실행

애플리케이션을 실행하고 이에 대한 요청을 수행합니다. 이제 원격 분석이 Application Insights로 이동합니다. Application Insights SDK는 다음 원격 분석과 함께 애플리케이션에 대한 들어오는 웹 요청을 자동으로 수집합니다.

라이브 메트릭

라이브 메트릭을 사용하면 Application Insights를 통한 애플리케이션 모니터링이 올바르게 구성되었는지 신속하게 확인할 수 있습니다. 원격 분석이 Azure Portal에 표시되는 데 몇 분 정도 걸릴 수 있지만 라이브 메트릭 창에는 실행 중인 프로세스의 CPU 사용량이 거의 실시간으로 표시됩니다. 또한 요청, 종속성, 추적 등의 다른 원격 분석 데이터도 표시할 수 있습니다.

참고

라이브 메트릭은 .NET 애플리케이션에 권장되는 지침을 사용하여 온보딩할 때 기본적으로 사용하도록 설정됩니다.

모든 .NET 애플리케이션에 대해 코드를 사용하여 라이브 메트릭 사용

수동으로 라이브 메트릭을 구성하려면 다음을 수행합니다.

  1. NuGet 패키지 Microsoft.ApplicationInsights.PerfCounterCollector를 설치합니다.

  2. 다음 샘플 콘솔 앱 코드는 라이브 메트릭을 설정하는 방법을 보여 줍니다.

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
using System;
using System.Threading.Tasks;

namespace LiveMetricsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a TelemetryConfiguration instance.
            TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
            config.InstrumentationKey = "INSTRUMENTATION-KEY-HERE";
            QuickPulseTelemetryProcessor quickPulseProcessor = null;
            config.DefaultTelemetrySink.TelemetryProcessorChainBuilder
                .Use((next) =>
                {
                    quickPulseProcessor = new QuickPulseTelemetryProcessor(next);
                    return quickPulseProcessor;
                })
                .Build();

            var quickPulseModule = new QuickPulseTelemetryModule();

            // Secure the control channel.
            // This is optional, but recommended.
            quickPulseModule.AuthenticationApiKey = "YOUR-API-KEY-HERE";
            quickPulseModule.Initialize(config);
            quickPulseModule.RegisterTelemetryProcessor(quickPulseProcessor);

            // Create a TelemetryClient instance. It is important
            // to use the same TelemetryConfiguration here as the one
            // used to set up live metrics.
            TelemetryClient client = new TelemetryClient(config);

            // This sample runs indefinitely. Replace with actual application logic.
            while (true)
            {
                // Send dependency and request telemetry.
                // These will be shown in live metrics.
                // CPU/Memory Performance counter is also shown
                // automatically without any additional steps.
                client.TrackDependency("My dependency", "target", "http://sample",
                    DateTimeOffset.Now, TimeSpan.FromMilliseconds(300), true);
                client.TrackRequest("My Request", DateTimeOffset.Now,
                    TimeSpan.FromMilliseconds(230), "200", true);
                Task.Delay(1000).Wait();
            }
        }
    }
}

ILogger 로그

기본 구성은 ILoggerWarning 로그 및 더 심각한 로그를 수집합니다. 자세한 내용은 ILogger 로그 컬렉션을 사용자 지정하려면 어떻게 해야 하나요?를 참조하세요.

종속성

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

성능 계수기

ASP.NET 성능 카운터를 완벽하게 지원하지만 ASP.NET Core는 SDK 버전 및 호스팅 환경에 따라 제한된 지원을 제공합니다. 자세한 내용은 Application Insights의 .NET용 카운터를 참조하세요.

이벤트 카운터

Application Insights는 ASP.NET Core에서 기본적으로 사용하도록 설정된 EventCounterCollectionModule를 통해 EventCounters 수집을 지원합니다. 수집할 카운터 목록을 구성하는 방법을 알아보려면 Application Insights에서 .NET용 카운터를 참조하세요.

HTTP를 통해 데이터 보강

var requestTelemetry = HttpContext.Current?.Items["Microsoft.ApplicationInsights.RequestTelemetry"] as RequestTelemetry;

if (requestTelemetry != null)
{
    requestTelemetry.Properties["myProp"] = "someData";
}

Application Insights SDK 구성

ASP.NET 및 ASP.NET Core용 Application Insights SDK를 사용자 지정하여 기본 구성을 변경할 수 있습니다.

ASP.NET 애플리케이션에 대해 Application Insights SDK를 구성하는 방법을 알아보려면 ApplicationInsights.config 또는 .xml사용하여 Application Insights SDK 구성 을 참조하세요.

샘플링

ASP.NET 애플리케이션에 대한 샘플링을 구성하는 방법을 알아보려면 Application Insights의 샘플링을 참조하세요.

원격 분석 이니셜라이저

추가 정보로 원격 분석을 보강하거나 표준 원격 분석 모듈에서 설정한 원격 분석 속성을 재정의하려면 원격 분석 이니셜라이저를 사용합니다.

ASP.NET 애플리케이션에서 원격 분석 이니셜라이저를 사용하는 방법을 알아보려면 Application Insights SDK에서 원격 분석 필터링 및 전처리를 참조하세요.

원격 분석 프로세서

ASP.NET 애플리케이션에서 원격 분석 프로세서를 사용하는 방법을 알아보려면 Application Insights SDK에서 원격 분석 필터링 및 전처리를 참조하세요.

기본 TelemetryModules 구성 또는 제거

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

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

  • RequestTrackingTelemetryModule: 들어오는 웹 요청에서 RequestTelemetry를 수집합니다.
  • DependencyTrackingTelemetryModule: 발신 HTTP 호출 및 SQL 호출에서 DependencyTelemetry를 수집합니다.
  • PerformanceCollectorModule: Windows PerformanceCounters를 수집합니다.
  • QuickPulseTelemetryModule: 라이브 메트릭 창에 표시할 원격 분석을 수집합니다.
  • AppServicesHeartbeatTelemetryModule: 애플리케이션이 호스트되는 App Service 환경에 대한 하트비트(사용자 지정 메트릭으로 전송됨)를 수집합니다.
  • AzureInstanceMetadataTelemetryModule: 애플리케이션이 호스트되는 Azure VM 환경에 대한 하트비트(사용자 지정 메트릭으로 전송됨)를 수집합니다.
  • EventCounterCollectionModule: EventCounters를 수집합니다. 이 모듈은 새로운 기능이며, SDK 버전 2.8.0 이상에서 사용할 수 있습니다.

ASP.NET 애플리케이션에 대한 원격 분석 모듈을 구성하거나 제거하는 방법을 알아보려면 ApplicationInsights.config 또는 .xml사용하여 Application Insights SDK 구성 을 참조하세요.

클라이언트쪽 모니터링을 추가 합니다.

이전 섹션에서는 서버 쪽 모니터링을 자동 및 수동으로 구성하는 방법에 대한 지침을 제공했습니다. 클라이언트 쪽 모니터링을 추가하려면 클라이언트 쪽 JavaScript SDK를 사용합니다. 페이지 HTML의 닫는 태그 앞에 JavaScript(웹) SDK 로더 스크립트를 추가하여 웹 페이지의 클라이언트 측 트랜잭션을 모니터링할 수 있습니다.

각 HTML 페이지의 헤더에 JavaScript(웹) SDK 로더 스크립트를 수동으로 추가할 수 있지만 대신 기본 페이지에 JavaScript(웹) SDK 로더 스크립트를 추가하는 것이 좋습니다. 해당 작업은 JavaScript(웹) SDK 로더 스크립트를 사이트의 모든 페이지에 삽입합니다.

이 문서에서 템플릿 기반 ASP.NET MVC 앱의 경우 _Layout.cshtml 파일을 편집해야 합니다. 이 파일은 보기>공유에서 찾을 수 있습니다. 클라이언트 쪽 모니터링을 추가하려면 _Layout.cshtml을 열고 클라이언트 쪽 JavaScript SDK 구성에 대한 문서의 JavaScript(웹) SDK 로더 스크립트 기반 설정 지침을 따릅니다.

문제 해결

전용 문제 해결 문서를 참조하세요.

Visual Studio 2019에는 알려진 문제가 있습니다. .NET Framework 기반 앱에서 계측 키나 연결 문자열을 사용자 비밀에 저장할 때 문제가 발생합니다. 이 버그를 해결하려면 키를 applicationinsights.config 파일에 하드 코드해야 합니다. 이 문서는 사용자 비밀을 사용하지 않고 이 문제를 완전히 방지하도록 설계되었습니다.

애플리케이션 호스트와 수집 서비스 간의 연결 테스트

Application Insights SDK 및 에이전트는 수집 엔드포인트에 대한 REST 호출로 수집하기 위해 원격 분석을 보냅니다. PowerShell 또는 curl 명령의 원시 REST 클라이언트를 사용하여 웹 서버 또는 애플리케이션 호스트 컴퓨터에서 수집 서비스 엔드포인트로의 연결을 테스트할 수 있습니다. Azure Monitor Application Insights에서 누락된 애플리케이션 원격 분석 문제 해결을 참조하세요.

오픈 소스 SDK

코드를 읽고 기여합니다.

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

릴리스 정보

버전 2.12 이상: ASP.NET, ASP.NET Core 및 로깅 어댑터를 포함한 .NET SDK(소프트웨어 개발 키트)

서비스 업데이트에는 주요 Application Insights 개선 사항도 요약되어 있습니다.

다음 단계

  • 지원되는 버전의 Application Insights SDK를 실행하고 있는지 확인합니다.
  • 가상 트랜잭션을 추가하여 가용성 모니터링을 통해 전 세계에서 웹 사이트를 사용할 수 있는지 테스트합니다.
  • 샘플링을 구성하면 원격 분석 트래픽과 데이터 스토리지 비용을 줄이는 데 도움이 됩니다.
  • 사용자 흐름을 탐색하여 사용자가 앱에서 어떻게 이동하는지 이해합니다.
  • 예외가 throw되는 시점의 소스 코드 및 변수 상태를 확인할 수 있도록 스냅샷 컬렉션을 구성합니다.
  • 앱의 성능 및 사용량을 자세히 확인할 수 있도록 API를 사용하여 사용자 고유의 이벤트 및 메트릭을 보냅니다.