주의
새 애플리케이션 또는 고객이 Azure Monitor Application Insights에 전원을 공급하려면 Azure Monitor OpenTelemetry Distro를 사용하는 것이 좋습니다. Azure Monitor OpenTelemetry Distro는 Application Insights SDK와 유사한 기능과 환경을 제공합니다. .NET, Node.js 및 Python에 대한 마이그레이션 가이드를 사용하여 Application Insights SDK에서 마이그레이션할 수 있지만 이전 버전과의 호환성을 위해 몇 가지 기능을 더 추가하기 위해 노력하고 있습니다.
이 문서에서는 원격 분석을 보내도록 ASP.NET 및 ASP.NET Core 애플리케이션에 대해 Application Insights 를 사용하도록 설정하고 구성하는 방법을 설명합니다. Application Insights는 앱에서 다음 원격 분석을 수집할 수 있습니다.
- 요청
- 종속성
- 예외
- 성능 계수기
- 추적(로그)
- 하트비트
- 사용자 지정 이벤트 및 메트릭 (수동 계측 필요)
- 페이지 보기 (웹 페이지에 JavaScript SDK 필요)
- 가용성 테스트(가용성 테스트를 수동으로 설정해야 합니다.)
지원되는 시나리오
참고
ASP.NET Core용 Application Insights SDK는 실행되는 위치 또는 방법에 관계없이 애플리케이션을 모니터링할 수 있습니다. 애플리케이션이 실행 중이고 Azure에 네트워크로 연결되어 있는 경우 원격 분석을 수집할 수 있습니다. Application Insights 모니터링은 .NET Core를 지원하는 모든 위치에서 지원됩니다.
지원됨 | ASP.NET | ASP.NET Core |
---|---|---|
운영 체제 | 윈도우즈 | Windows, Linux 또는 macOS |
호스팅 방법 | 프로세스 내(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 또는 명령줄 |
Application Insights 추가
필수 조건
- Azure 구독. 아직 없는 경우 무료 Azure 계정을 만듭니다.
- Application Insights 작업 영역 기반 리소스입니다.
- 작동하는 웹 애플리케이션입니다. 아직 없는 경우 기본 웹앱 만들기를 참조하세요.
- 다음 워크로드가 있는 최신 버전의 Visual Studio :
- ASP.NET 및 웹 개발
- Azure 개발
기본 웹앱 만들기
아직 작동하는 웹 애플리케이션이 없는 경우 다음 지침을 사용하여 웹 애플리케이션을 만들 수 있습니다.
참고
MVC 애플리케이션 예를 사용합니다. 작업자 서비스를 사용하는 경우 작업자 서비스 애플리케이션에 대한 Application Insights의 지침을 따릅니다.
- Visual Studio를 엽니다.
- 새 프로젝트 만들기를 선택합니다.
- C#으로 ASP.NET 웹 애플리케이션(.NET Framework)을 선택하고 다음을 선택합니다.
- 프로젝트 이름을 입력한 다음 만들기를 선택합니다.
- MVC를 선택한 다음 만들기를 선택합니다.
Application Insights 자동 추가(Visual Studio)
이 섹션에서는 템플릿 기반 웹앱에 Application Insights를 자동으로 추가하는 방법을 안내합니다.
Visual Studio의 ASP.NET 웹앱 프로젝트 내에서:
프로젝트>Application Insights 원격 분석 추가>Application Insights Sdk(로컬)>다음>완료>닫기를 선택합니다.
ApplicationInsights.config 파일을 엽니다.
닫는
</ApplicationInsights>
태그 앞에 Application Insights 리소스에 대한 연결 문자열이 포함된 선을 추가합니다. 새로 만든 Application Insights 리소스의 개요 창에서 연결 문자열을 찾습니다.<ConnectionString>Copy connection string from Application Insights Resource Overview</ConnectionString>
프로젝트>NuGet 패키지 관리>업데이트를 선택합니다. 그런 다음, 각
Microsoft.ApplicationInsights
NuGet 패키지를 안정적인 최신 릴리스로 업데이트합니다.IIS Express를 선택하여 애플리케이션을 실행합니다. 기본 ASP.NET 앱이 열립니다. 사이트의 페이지를 탐색할 때 원격 분석 데이터가 Application Insights로 전송됩니다.
Application Insights를 수동으로 추가(Visual Studio 없음)
이 섹션에서는 템플릿 기반 웹앱에 Application Insights를 수동으로 추가하는 방법을 안내합니다.
다음 NuGet 패키지 및 해당 종속성을 프로젝트에 추가합니다.
경우에 따라 ApplicationInsights.config 파일이 자동으로 만들어집니다. 파일이 이미 있는 경우 4단계로 건너뜁니다.
없으면 직접 만들어라. ASP.NET 애플리케이션의 루트 디렉터리에서 ApplicationInsights.config라는 새 파일을 만듭니다.
다음 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>
두 가지 방법으로 수행할 수 있는 연결 문자열 추가합니다.
(권장) 구성에서 연결 문자열 설정합니다.
</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" };
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); } } }
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()); } } }
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=\"Web\" /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로 이동합니다. Application Insights SDK는 다음 원격 분석과 함께 애플리케이션에 대한 들어오는 웹 요청을 자동으로 수집합니다.
원격 분석 구성
이 부분에서는
라이브 메트릭
라이브 메트릭을 사용하면 Application Insights를 통한 애플리케이션 모니터링이 올바르게 구성되었는지 신속하게 확인할 수 있습니다. 원격 분석이 Azure Portal에 표시되는 데 몇 분 정도 걸릴 수 있지만 라이브 메트릭 창에는 실행 중인 프로세스의 CPU 사용량이 거의 실시간으로 표시됩니다. 또한 요청, 종속성, 추적 등의 다른 원격 분석 데이터도 표시할 수 있습니다.
참고
라이브 메트릭은 .NET 애플리케이션에 권장되는 지침을 사용하여 온보딩할 때 기본적으로 사용하도록 설정됩니다.
모든 .NET 애플리케이션에 대해 코드를 사용하여 라이브 메트릭 사용
수동으로 라이브 메트릭을 구성하려면 다음을 수행합니다.
NuGet 패키지 Microsoft.ApplicationInsights.PerfCounterCollector를 설치합니다.
다음 샘플 콘솔 앱 코드는 라이브 메트릭을 설정하는 방법을 보여 줍니다.
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();
}
}
}
}
추적(로그)
Application Insights는 ILogger를 통해 ASP.NET Core 및 기타 .NET 앱의 로그를 캡처하고 클래식 SDK 및 어댑터를 통해 클래식 ASP.NET(.NET Framework)에서 로그를 캡처합니다.
팁 (조언)
기본적으로 Application Insights 공급자는 심각도
Warning
이상의 로그만 보냅니다. 로그를 포함하거나 하위 수준 로그를 포함Information
하려면 .에서appsettings.json
로그 수준 설정을 업데이트합니다.Microsoft.ApplicationInsights.WorkerService
백그라운드 서비스에 Application Insights를 사용하도록 설정하는 데 사용되는 NuGet 패키지는 범위를 벗어났습니다. 자세한 내용은 작업자 서비스 앱용 Application Insights를 참조하세요.
참고
FAQ(질문과 대답)를 검토하려면 .NET FAQ를 사용하여 로깅을 참조하세요.
ILogger 지침은 ASP.NET 적용되지 않습니다. 클래식 ASP.NET 앱에서 Application Insights로 추적 로그를 보내려면 다음과 같은 지원되는 어댑터를 사용합니다.
- Application Insights TraceListener를 사용한 System.Diagnostics.Trace
- 공식 Application Insights 대상이 있는 log4net 또는 NLog
자세한 단계 및 구성 예제는 Application Insights에 추적 로그 보내기를 참조하세요.
콘솔 애플리케이션
콘솔 애플리케이션에 Application Insights 로깅을 추가하려면 먼저 다음 NuGet 패키지를 설치합니다.
다음 예제에서는 패키지를 사용 하 고 Microsoft.Extensions.Logging.ApplicationInsights
콘솔 애플리케이션에 대 한 기본 동작을 보여 줍니다. 패키지는 Microsoft.Extensions.Logging.ApplicationInsights
콘솔 애플리케이션에서 사용하거나 메트릭, 분산 추적, 샘플링 및 원격 분석 이니셜라이저와 같은 전체 기능 집합 없이 Application Insights의 최소 구현을 원할 때마다 사용해야 합니다.
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using var channel = new InMemoryChannel();
try
{
IServiceCollection services = new ServiceCollection();
services.Configure<TelemetryConfiguration>(config => config.TelemetryChannel = channel);
services.AddLogging(builder =>
{
// Only Application Insights is registered as a logger provider
builder.AddApplicationInsights(
configureTelemetryConfiguration: (config) => config.ConnectionString = "<YourConnectionString>",
configureApplicationInsightsLoggerOptions: (options) => { }
);
});
IServiceProvider serviceProvider = services.BuildServiceProvider();
ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Logger is working...");
}
finally
{
// Explicitly call Flush() followed by Delay, as required in console apps.
// This ensures that even if the application terminates, telemetry is sent to the back end.
channel.Flush();
await Task.Delay(TimeSpan.FromMilliseconds(1000));
}
로깅 범위
참고
다음 지침은 ILogger 시나리오에 적용됩니다(ASP.NET Core 및 콘솔에만 해당). 클래식 ASP.NET 적용되지 않습니다.
ApplicationInsightsLoggingProvider
는 기본적으로 사용하도록 설정된 로그 범위를 지원합니다.
범위가 형식 IReadOnlyCollection<KeyValuePair<string,object>>
인 경우 컬렉션의 각 키/값 쌍이 Application Insights 원격 분석에 사용자 지정 속성으로 추가됩니다. 다음 예제에서는 로그가 속성으로 TraceTelemetry
캡처되고 ("MyKey", "MyValue")
있습니다.
using (_logger.BeginScope(new Dictionary<string, object> { ["MyKey"] = "MyValue" }))
{
_logger.LogError("An example of an Error level message");
}
다른 형식이 범위로 사용되는 경우 Application Insights 원격 분석의 속성 Scope
아래에 저장됩니다. 다음 예제 TraceTelemetry
에서는 범위를 포함하는 속성이 호출 Scope
됩니다.
using (_logger.BeginScope("hello scope"))
{
_logger.LogError("An example of an Error level message");
}
로그 찾기
ILogger 로그는 추적 원격 분석으로 표시됩니다(Application Insights 및 traces
Log Analytics의 테이블AppTraces
).
예시
Azure Portal에서 Application Insights로 이동하여 다음을 실행합니다.
traces
| where severityLevel >= 2 // 2=Warning, 1=Information, 0=Verbose
| take 50
종속성
자동으로 추적되는 종속성
.NET 및 .NET Core용 Application Insights SDK는 종속성을 자동으로 수집하는 원격 분석 모듈인 DependencyTrackingTelemetryModule
과 함께 제공됩니다. 이 모듈 DependencyTrackingTelemetryModule
은 Microsoft.ApplicationInsights.DependencyCollector NuGet 패키지로 제공되며 NuGet 패키지 또는 Microsoft.ApplicationInsights.Web
NuGet 패키지를 사용할 Microsoft.ApplicationInsights.AspNetCore
때 자동으로 제공됩니다.
현재 DependencyTrackingTelemetryModule
은 다음 종속성을 자동으로 추적합니다.
종속성 | 세부 정보 |
---|---|
HTTP/HTTPS | 로컬 또는 원격 HTTP/HTTPS 호출 |
WCF 호출 | HTTP 기반 바인딩을 사용하는 경우에만 자동으로 추적됩니다. |
SQL |
SqlClient 를 사용한 호출입니다. SQL 쿼리 캡처에 대한 자세한 내용은 전체 SQL 쿼리를 가져오기 위한 고급 SQL 추적 섹션을 참조하세요. |
Azure Blob Storage, Table Storage 또는 Queue Storage | Azure Storage 클라이언트를 사용한 호출입니다. |
Azure Event Hubs - 클라이언트 SDK | 최신 패키지를 사용합니다. https://nuget.org/packages/Azure.Messaging.EventHubs |
Azure Service Bus 클라이언트 SDK | 최신 패키지를 사용합니다. https://nuget.org/packages/Azure.Messaging.ServiceBus |
Azure Cosmos DB | HTTP/HTTPS를 사용하는 경우 자동으로 추적됩니다. TCP를 사용하는 직접 모드에서 작업에 대한 추적은 미리 보기 패키지 >= 3.33.0-preview를 사용하여 자동으로 캡처됩니다. 자세한 내용은 설명서를 참조하세요. |
종속성이 자동 수집되지 않으면 종속성 호출 추적을 사용하여 수동으로 추적할 수 있습니다.
종속성 추적이 작동하는 방식에 대한 자세한 내용은 Application Insights의 종속성 추적을 참조하세요.
콘솔 앱에서 자동 종속성 추적 설정
.NET 콘솔 앱의 종속성을 자동으로 추적하려면 NuGet 패키지 Microsoft.ApplicationInsights.DependencyCollector
을 설치하고 DependencyTrackingTelemetryModule
를 초기화합니다.
DependencyTrackingTelemetryModule depModule = new DependencyTrackingTelemetryModule();
depModule.Initialize(TelemetryConfiguration.Active);
수동으로 종속성 추적
자동으로 수집되지 않는 종속성의 다음 예에서는 수동 추적이 필요합니다.
- Azure Cosmos DB는 HTTP/HTTPS를 사용하는 경우에만 자동으로 추적됩니다. TCP 모드는 이전 버전의 SDK
2.22.0-Beta1
용 Application Insights에서 자동으로 캡처되지 않습니다. - Redis
SDK에서 자동으로 수집하지 않는 종속성의 경우 표준 자동 컬렉션 모듈에서 사용되는 TrackDependency API를 사용하여 수동으로 추적할 수 있습니다.
예시
사용자가 직접 작성하지 않은 어셈블리로 코드를 빌드하는 경우 모든 호출의 시간을 측정할 수 있습니다. 이 시나리오를 사용하면 응답 시간에 어떤 기여를 하는지 확인할 수 있습니다.
Application Insights에서 종속성 차트에 표시되는 이 데이터를 가지려면, TrackDependency
를 사용하여 이것을 보냅니다.
var startTime = DateTime.UtcNow;
var timer = System.Diagnostics.Stopwatch.StartNew();
try
{
// making dependency call
success = dependency.Call();
}
finally
{
timer.Stop();
telemetryClient.TrackDependency("myDependencyType", "myDependencyCall", "myDependencyData", startTime, timer.Elapsed, success);
}
또는 TelemetryClient
는 StartOperation
에 표시된 대로 종속성을 수동으로 추적하는 데 사용할 수 있는 확장 메서드 StopOperation
및 을 제공합니다.
표준 종속성 추적 모듈 사용 안 함
자세한 내용은 원격 분석 모듈을 참조하세요.
전체 SQL 쿼리를 가져오기 위한 고급 SQL 추적
SQL 호출의 경우 서버 및 데이터베이스의 이름은 항상 수집되고 수집된 DependencyTelemetry
의 이름으로 저장됩니다. 데이터라고 하는 다른 필드에는 전체 SQL 쿼리 텍스트가 포함될 수 있습니다.
참고
Azure Functions는 SQL 텍스트 컬렉션을 사용하도록 설정하기 위해 별도의 설정이 필요합니다. 자세한 내용은 SQL 쿼리 컬렉션 사용을 참조하세요.
ASP.NET 애플리케이션의 경우, 계측 엔진을 사용하거나 System.Data.SqlClient 라이브러리 대신 Microsoft.Data.SqlClient NuGet 패키지를 사용해야 하는 바이트 코드 계측을 통해 전체 SQL 쿼리 텍스트가 수집됩니다. 전체 SQL 쿼리 컬렉션을 사용하도록 설정하는 플랫폼별 단계는 다음 표에 설명되어 있습니다.
플랫폼 | 전체 SQL 쿼리를 가져오는 데 필요한 단계 |
---|---|
Azure App Service의 Web Apps | 웹앱 제어판에서 Application Insights 창을 열고 .NET에서 SQL 명령을 사용하도록 설정합니다. |
IIS 서버(Azure Virtual Machines, 온-프레미스 등) | Microsoft.Data.SqlClient NuGet 패키지를 사용하거나 Application Insights 에이전트 PowerShell 모듈을 사용하여 계측 엔진을 설치하고 IIS를 다시 시작합니다. |
Azure Cloud Services |
StatusMonitor를 설치하기 위한 시작 작업을 추가합니다. ASP.NET 또는 ASP.NET Core 애플리케이션용 NuGet 패키지를 설치하여 빌드 시 ApplicationInsights SDK에 앱을 온보딩해야 합니다. |
IIS Express | Microsoft.Data.SqlClient NuGet 패키지를 사용합니다. |
Azure App Service의 WebJobs | Microsoft.Data.SqlClient NuGet 패키지를 사용합니다. |
앞의 플랫폼별 단계 외에도 다음 코드로 파일을 수정하여 applicationInsights.config
.
<TelemetryModules>
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
<EnableSqlCommandTextInstrumentation>true</EnableSqlCommandTextInstrumentation>
</Add>
앞의 경우 계측 엔진이 올바르게 설치되었는지 유효성을 검사하는 올바른 방법은 수집된 DependencyTelemetry
의 SDK 버전이 rddp
인지 유효성을 검사하는 것입니다.
rdddsd
종속성을 사용하거나 rddf
DiagnosticSource
콜백을 통해 EventSource
수집되므로 전체 SQL 쿼리가 캡처되지 않습니다.
예외
Application Insights를 사용하여 웹 애플리케이션의 예외를 보고할 수 있습니다. 클라이언트와 서버 모두에서 예외 및 기타 이벤트와 실패한 요청의 상관 관계를 지정하여 원인을 신속하게 진단할 수 있습니다. 이 섹션에서는 예외 보고를 설정하고, 예외를 명시적으로 보고하고, 오류를 진단하는 방법을 알아봅니다.
예외 보고 설정
서버 또는 클라이언트에서 발생하는 예외를 보고하도록 Application Insights를 설정할 수 있습니다. 애플리케이션이 종속된 플랫폼에 따라 적절한 확장 또는 SDK가 필요합니다.
서버 쪽 애플리케이션에서 예외가 보고되도록 하려면 다음 시나리오를 고려하세요.
- Azure 웹앱용 Application Insights 확장을 추가합니다.
- Azure Virtual Machines 및 Azure Virtual Machine Scale Sets IIS 호스팅 앱에 대한 애플리케이션 모니터링 확장을 추가합니다.
- 앱 코드에 Application Insights SDK를 추가 하거나, IIS 웹 서버용 Application Insights 에이전트 를 실행하거나, Java 웹앱에 Java 에이전트 를 사용하도록 설정합니다.
중요한
이 섹션은 코드 예제 관점에서 .NET Framework 앱에 초점을 맞췄습니다. .NET Framework에 대해 작동하는 일부 메서드는 .NET Core SDK에서 사용되지 않습니다.
오류 및 예외 진단
Application Insights는 모니터링되는 애플리케이션에서 오류를 진단하는 데 도움이 되는 큐레이팅된 애플리케이션 성능 관리 환경과 함께 제공됩니다.
사용자 지정 추적 및 로그 데이터
앱과 관련된 진단 데이터를 얻으려면 코드를 삽입하여 고유한 원격 분석 데이터를 보낼 수 있습니다. 사용자 지정 원격 분석 또는 로그 데이터는 요청, 페이지 보기 및 기타 자동으로 수집된 데이터와 함께 진단 검색에 표시됩니다.
이 API를 Microsoft.VisualStudio.ApplicationInsights.TelemetryClient사용하면 다음과 같은 여러 API를 사용할 수 있습니다.
- TelemetryClient.TrackEvent 는 일반적으로 사용 패턴을 모니터링하는 데 사용되지만 보내는 데이터는 진단 검색의 사용자 지정 이벤트 아래에도 표시됩니다. 이벤트의 이름은 지정되며 진단 검색을 필터링할 수 있는 문자열 속성 및 숫자 메트릭을 전달할 수 있습니다.
- TelemetryClient.TrackTrace 를 사용하면 POST 정보와 같은 더 긴 데이터를 보낼 수 있습니다.
- TelemetryClient.TrackException 는 스택 추적과 같은 예외 세부 정보를 Application Insights로 보냅니다.
이러한 이벤트를 보려면 왼쪽 메뉴에서 검색을 엽니다. 드롭다운 메뉴 이벤트 유형을 선택한 다음 사용자 지정 이벤트, 추적 또는 예외를 선택합니다.
참고
앱에서 많은 양의 원격 분석을 생성하는 경우 적응 샘플링 모듈은 대표적인 이벤트 부분만 전송하여 포털로 전송되는 볼륨을 자동으로 줄입니다. 동일한 작업의 일부인 이벤트는 그룹으로 선택되거나 선택 취소되므로 관련 이벤트 간에 이동할 수 있습니다. 자세한 내용은 Application Insights의 샘플링을 참조하세요.
POST 데이터 요청 참조
요청 세부 정보에는 POST 호출에서 앱으로 전송된 데이터가 포함되지 않습니다. 이 데이터를 보고하려면 다음을 수행합니다.
- Application Insights SDK를 앱 코드에 추가합니다.
- 애플리케이션에 코드를 삽입하여 Microsoft.ApplicationInsights.TrackTrace()를 호출합니다. 메시지 매개 변수에 POST 데이터를 보냅니다. 허용되는 크기에 제한이 있으므로 필수 데이터만 보내려고 합니다.
- 실패한 요청을 조사할 때 연결된 추적을 찾습니다.
예외 및 관련 진단 데이터 캡처
기본적으로 앱에서 오류를 일으키는 모든 예외가 포털에 표시되지는 않습니다. 웹 페이지에서 JavaScript SDK 를 사용하는 경우 브라우저 예외가 표시됩니다. 그러나 대부분의 서버 쪽 예외는 IIS에 의해 가로채므로 캡처하고 보고하는 코드를 추가해야 합니다.
당신은 할 수 있어요:
- 예외 처리 기에 코드를 삽입하여 예외를 보고하여 예외를 명시적으로 기록합니다.
- ASP.NET 프레임워크를 구성하여 예외를 자동으로 캡처합니다. 필요한 추가는 다양한 유형의 프레임워크에 따라 다릅니다.
예외를 명시적으로 보고
가장 간단한 보고 방법은 예외 처리기에 호출을 삽입하는 것입니다 trackException()
.
var telemetry = new TelemetryClient();
try
{
// ...
}
catch (Exception ex)
{
var properties = new Dictionary<string, string>
{
["Game"] = currentGame.Name
};
var measurements = new Dictionary<string, double>
{
["Users"] = currentGame.Users.Count
};
// Send the exception telemetry:
telemetry.TrackException(ex, properties, measurements);
}
속성 및 측정 매개 변수는 선택 사항이지만 추가 정보를 필터링하고 추가하는 데 유용합니다. 예를 들어 여러 게임을 실행할 수 있는 앱이 있는 경우 특정 게임과 관련된 모든 예외 보고서를 찾을 수 있습니다. 각 사전에 원하는 만큼 항목을 추가할 수 있습니다.
브라우저 예외
대부분의 브라우저 예외가 보고됩니다.
웹 페이지에 콘텐츠 배달 네트워크 또는 다른 도메인의 스크립트 파일이 포함된 경우 스크립트 태그에 특성 crossorigin="anonymous"
이 있고 서버가 CORS 헤더를 보내는지 확인합니다. 이 동작을 사용하면 이러한 리소스에서 처리되지 않은 JavaScript 예외에 대한 스택 추적 및 세부 정보를 가져올 수 있습니다.
원격 분석 클라이언트 다시 사용
참고
한 번 인스턴스화 TelemetryClient
하고 애플리케이션의 수명 동안 다시 사용하는 것이 좋습니다.
.NET의 DI(종속성 주입)와 적절한 .NET SDK를 사용하고 DI용 Application Insights를 올바르게 구성하면 생성자 매개 변수로 필요할 TelemetryClient 수 있습니다.
public class ExampleController : ApiController
{
private readonly TelemetryClient _telemetryClient;
public ExampleController(TelemetryClient telemetryClient)
{
_telemetryClient = telemetryClient;
}
}
앞의 예제 TelemetryClient
에서는 클래스에 ExampleController
삽입됩니다.
웹 양식
웹 양식의 경우 HTTP 모듈은 .으로 구성된 CustomErrors
리디렉션이 없는 경우 예외를 수집할 수 있습니다. 그러나 활성 리디렉션이 있는 경우 Application_Error
함수에 다음 줄을 추가합니다.
void Application_Error(object sender, EventArgs e)
{
if (HttpContext.Current.IsCustomErrorEnabled &&
Server.GetLastError () != null)
{
_telemetryClient.TrackException(Server.GetLastError());
}
}
앞의 예제에서 형식의 _telemetryClient
클래스 범위 변수 TelemetryClient입니다.
MVC
Application Insights 웹 SDK 버전 2.6(베타 3 이상)부터 Application Insights는 MVC 5+ 컨트롤러 메서드에서 throw된 처리되지 않은 예외를 자동으로 수집합니다. 이전에 이러한 예외를 추적하기 위해 사용자 지정 처리기를 추가한 경우 예외를 이중 추적하지 않도록 제거할 수 있습니다.
예외가 throw되면 예외 필터가 오류를 올바르게 처리할 수 없는 몇 가지 시나리오가 있습니다.
- 컨트롤러 생성자에서
- 메시지 처리기에서
- 라우팅 중
- 응답 콘텐츠 serialization 중
- 애플리케이션을 시작하는 동안
- 백그라운드 작업에서
애플리케이션 에서 처리하는 모든 예외는 수동으로 추적해야 합니다. 컨트롤러에서 발생하는 처리되지 않은 예외는 일반적으로 500 "내부 서버 오류" 응답을 발생합니다. 이러한 응답이 처리된 예외의 결과로 수동으로 생성되거나 예외가 전혀 없는 경우 해당 요청 원격 분석에서 500으로 ResultCode
추적됩니다. 그러나 Application Insights SDK는 해당 예외를 추적할 수 없습니다.
이전 버전 지원
Application Insights Web SDK 2.5(및 이전)의 MVC 4(및 이전)를 사용하는 경우 다음 예제를 참조하여 예외를 추적합니다.
확장하여 이전 버전에 대한 지침 보기
CustomErrors 구성이Off
면 HTTP 모듈에서 예외를 수집할 수 있습니다. 그러나 (기본값)으로 RemoteOnly
설정되었거나 On
예외가 지워지고 Application Insights에서 자동으로 수집할 수 없습니다.
System.Web.Mvc.HandleErrorAttribute 클래스를 재정의하고 여기에 표시된 다른 MVC 버전에 대해 재정의된 클래스를 적용하여 해당 동작을 수정할 수 있습니다(GitHub 원본 참조).
using System;
using System.Web.Mvc;
using Microsoft.ApplicationInsights;
namespace MVC2App.Controllers
{
[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)
{
//The attribute should track exceptions only when CustomErrors setting is On
//if CustomErrors is Off, exceptions will be caught by AI HTTP Module
if (filterContext.HttpContext.IsCustomErrorEnabled)
{ //Or reuse instance (recommended!). See note above.
var ai = new TelemetryClient();
ai.TrackException(filterContext.Exception);
}
}
base.OnException(filterContext);
}
}
}
MVC 2
HandleError 특성을 컨트롤러의 새 특성으로 바꿉니다.
namespace MVC2App.Controllers
{
[AiHandleError]
public class HomeController : Controller
{
// Omitted for brevity
}
}
MVC 3
AiHandleErrorAttribute
전역 필터로 등록 합니다.
public class MyMvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AiHandleErrorAttribute());
}
}
MVC 4, MVC 5
AiHandleErrorAttribute
전역 필터로 등록 합니다.
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// Default replaced with the override to track unhandled exceptions
filters.Add(new AiHandleErrorAttribute());
}
}
인터넷 응용 프로그램 인터페이스
Application Insights 웹 SDK 버전 2.6(베타 3 이상)부터 Application Insights는 Web API 2 이상에 대해 컨트롤러 메서드에서 자동으로 throw된 처리되지 않은 예외를 수집합니다. 다음 예제에 설명된 대로 이전에 이러한 예외를 추적하기 위해 사용자 지정 처리기를 추가한 경우 예외를 이중 추적하지 않도록 제거할 수 있습니다.
예외 필터가 처리할 수 없는 몇 가지 경우가 있습니다. 다음은 그 예입니다.
- 컨트롤러 생성자에서 throw된 예외입니다.
- 메시지 처리기에서 throw된 예외입니다.
- 라우팅 중에 throw된 예외입니다.
- 응답 콘텐츠 serialization 중에 throw된 예외입니다.
- 애플리케이션을 시작하는 동안 예외가 throw되었습니다.
- 백그라운드 작업에서 throw된 예외입니다.
애플리케이션 에서 처리하는 모든 예외는 수동으로 추적해야 합니다. 컨트롤러에서 발생하는 처리되지 않은 예외는 일반적으로 500 "내부 서버 오류" 응답을 발생합니다. 이러한 응답이 처리된 예외의 결과로 수동으로 생성되거나 예외가 전혀 없는 경우 500이 있는 해당 요청 원격 분석 ResultCode
에서 추적됩니다. 그러나 Application Insights SDK는 해당 예외를 추적할 수 없습니다.
이전 버전 지원
Application Insights Web SDK 2.5 이하의 Web API 1(및 이전 버전)을 사용하는 경우 다음 예제를 참조하여 예외를 추적합니다.
확장하여 이전 버전에 대한 지침 보기
Web API 1.x
재정 System.Web.Http.Filters.ExceptionFilterAttribute
의:
using System.Web.Http.Filters;
using Microsoft.ApplicationInsights;
namespace WebAPI.App_Start
{
public class AiExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext != null && actionExecutedContext.Exception != null)
{ //Or reuse instance (recommended!). See note above.
var ai = new TelemetryClient();
ai.TrackException(actionExecutedContext.Exception);
}
base.OnException(actionExecutedContext);
}
}
}
이 재정의된 특성을 특정 컨트롤러에 추가하거나 클래스의 전역 필터 구성에 WebApiConfig
추가할 수 있습니다.
using System.Web.Http;
using WebApi1.x.App_Start;
namespace WebApi1.x
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
// ...
config.EnableSystemDiagnosticsTracing();
// Capture exceptions for Application Insights:
config.Filters.Add(new AiExceptionFilterAttribute());
}
}
}
Web API 2.x
다음의 구현을 추가합니다 IExceptionLogger
.
using System.Web.Http.ExceptionHandling;
using Microsoft.ApplicationInsights;
namespace ProductsAppPureWebAPI.App_Start
{
public class AiExceptionLogger : ExceptionLogger
{
public override void Log(ExceptionLoggerContext context)
{
if (context != null && context.Exception != null)
{
//or reuse instance (recommended!). see note above
var ai = new TelemetryClient();
ai.TrackException(context.Exception);
}
base.Log(context);
}
}
}
다음의 서비스에 이 코드 조각을 추가합니다.WebApiConfig
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using ProductsAppPureWebAPI.App_Start;
namespace WebApi2WithMVC
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
config.Services.Add(typeof(IExceptionLogger), new AiExceptionLogger());
}
}
}
대안으로 다음을 수행할 수 있습니다.
- 유일한
ExceptionHandler
인스턴스를 사용자 지정 구현IExceptionHandler
으로 바꿉다. 이 예외 처리기는 프레임워크가 연결이 중단될 때가 아니라 보낼 응답 메시지를 선택할 수 있는 경우에만 호출됩니다. - 모든 경우에 호출되지 않는 Web API 1.x 컨트롤러의 이전 섹션에 설명된 대로 예외 필터를 사용합니다.
WCF
를 확장하고 구현하는 Attribute
클래스를 추가합니다 IErrorHandler
IServiceBehavior
.
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Web;
using Microsoft.ApplicationInsights;
namespace WcfService4.ErrorHandling
{
public class AiLogExceptionAttribute : Attribute, IErrorHandler, IServiceBehavior
{
public void AddBindingParameters(ServiceDescription serviceDescription,
System.ServiceModel.ServiceHostBase serviceHostBase,
System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints,
System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription,
System.ServiceModel.ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher disp in serviceHostBase.ChannelDispatchers)
{
disp.ErrorHandlers.Add(this);
}
}
public void Validate(ServiceDescription serviceDescription,
System.ServiceModel.ServiceHostBase serviceHostBase)
{
}
bool IErrorHandler.HandleError(Exception error)
{//or reuse instance (recommended!). see note above
var ai = new TelemetryClient();
ai.TrackException(error);
return false;
}
void IErrorHandler.ProvideFault(Exception error,
System.ServiceModel.Channels.MessageVersion version,
ref System.ServiceModel.Channels.Message fault)
{
}
}
}
서비스 구현에 특성을 추가합니다.
namespace WcfService4
{
[AiLogException]
public class Service1 : IService1
{
// Omitted for brevity
}
}
예외 성능 카운터
서버에 Azure Monitor Application Insights 에이전트를 설치한 경우 .NET으로 측정된 예외 비율 차트를 가져올 수 있습니다. 처리된 .NET 예외와 처리되지 않은 .NET 예외가 모두 포함됩니다.
메트릭 탐색기 탭을 열고 새 차트를 추가합니다. 성능 카운터에서 예외 속도를 선택합니다.
.NET Framework는 간격의 예외 수를 계산하고 간격의 길이로 나누어 속도를 계산합니다.
이 개수는 Application Insights 포털에서 계산한 예외 수와 보고서 개수와 TrackException
다릅니다. 샘플링 간격은 다르며 SDK는 처리된 예외 및 처리되지 않은 모든 예외에 대한 보고서를 보내지 TrackException
않습니다.
사용자 지정 메트릭 컬렉션
Azure Monitor Application Insights .NET 및 .NET Core SDK에는 사용자 지정 메트릭을 수집하는 두 가지 방법이 있습니다.
-
TrackMetric()
사전 집계가 없는 메서드입니다. -
GetMetric()
사전 집계가 있는 메서드입니다.
집계를 사용하는 것이 좋으므로 TrackMetric()
더 이상 사용자 지정 메트릭을 수집하는 기본 방법이 아닙니다. 이 문서에서는 메서드 및 작동 방식의 몇 가지 근거를 사용하는 GetMetric()
방법을 안내합니다.
사전 집계 및 사전 집계가 아닌 API에 대한 자세한 내용을 알아보려면 확장합니다.
이 메서드는 TrackMetric()
메트릭을 나타내는 원시 원격 분석을 보냅니다. 각 값에 대해 단일 원격 분석 항목을 보내는 것은 비효율적입니다. 모든 TrackMetric()
원격 분석 이 TrackMetric(item)
니셜라이저 및 프로세서의 전체 SDK 파이프라인을 통과하기 때문에 이 메서드는 성능 측면에서도 비효율적입니다.
달리 TrackMetric()
로컬 GetMetric()
사전 집계를 처리한 다음, 1분의 고정 간격으로 집계된 요약 메트릭만 제출합니다. 두 번째 또는 밀리초 수준에서 일부 사용자 지정 메트릭을 면밀히 모니터링해야 하는 경우 1분마다 모니터링하는 스토리지 및 네트워크 트래픽 비용만 발생시키는 동시에 수행할 수 있습니다. 또한 이 동작은 집계된 메트릭에 대해 전송해야 하는 총 원격 분석 항목 수가 크게 감소하므로 제한 발생 위험을 크게 줄입니다.
Application Insights에서 수집된 TrackMetric()
사용자 지정 메트릭은 GetMetric()
샘플링의 대상이 아닙니다. 중요한 메트릭을 샘플링하면 해당 메트릭을 중심으로 작성된 경고가 불안정해지는 시나리오가 발생할 수 있습니다. 사용자 지정 메트릭을 샘플링하지 않으면 일반적으로 경고 임계값이 위반되면 경고가 발생한다는 것을 확신할 수 있습니다. 사용자 지정 메트릭은 샘플링되지 않으므로 몇 가지 잠재적인 문제가 있습니다.
1초마다 또는 훨씬 더 세분화된 간격으로 메트릭에서 추세 추적을 수행하면 다음이 발생할 수 있습니다.
- 데이터 스토리지 비용 증가. Azure Monitor에 보내는 데이터의 양과 관련된 비용이 있습니다. 전송하는 데이터가 많을수록 전체 모니터링 비용이 커지게 됩니다.
- 네트워크 트래픽 또는 성능 오버헤드가 증가했습니다. 일부 시나리오에서는 이 오버헤드에 금전적 비용 및 애플리케이션 성능 비용이 둘 다 있을 수 있습니다.
- 수집 제한의 위험. Azure Monitor는 앱이 짧은 시간 간격으로 높은 원격 분석 속도를 보낼 때 데이터 요소를 삭제합니다("제한").
제한은 누락된 경고로 이어질 수 있으므로 문제가 됩니다. 경고를 트리거하는 조건은 로컬에서 발생한 다음 너무 많은 데이터가 전송되어 수집 엔드포인트에서 삭제될 수 있습니다. 고유한 로컬 집계 논리를 구현하지 않는 한 .NET 및 .NET Core에는 사용하지 TrackMetric()
않는 것이 좋습니다. 지정된 기간 동안 이벤트가 발생하는 모든 인스턴스를 추적하려는 경우 더 적합할 수 있습니다 TrackEvent()
. 사용자 지정 메트릭과 달리 사용자 지정 이벤트는 샘플링의 대상이 됩니다. 사용자 고유의 로컬 사전 집계를 작성하지 않고도 계속 사용할 TrackMetric()
수 있습니다. 그러나 그렇게 한다면, 함정에 유의하십시오.
요약하자면, 사전 집계를 수행하고, 모든 GetMetric()
호출의 값을 누적하고, 1분에 한 번씩 요약/집계를 보내는 것이 좋습니다Track()
. 이 메서드는 GetMetric()
모든 관련 정보를 수집하는 동안 더 적은 데이터 요소를 전송하여 비용 및 성능 오버헤드를 크게 줄일 수 있습니다.
GetMetric 시작
이 예제에서는 기본 .NET Core 3.1 작업자 서비스 애플리케이션을 사용합니다. 이러한 예제와 함께 사용되는 테스트 환경을 복제하려면 작업자 모니터링 서비스 문서의 1-6단계를 수행합니다. 이러한 단계에서는 기본 작업자 서비스 프로젝트 템플릿에 Application Insights를 추가합니다. 개념은 웹앱 및 콘솔 앱을 포함하여 SDK를 사용할 수 있는 모든 일반 애플리케이션에 적용됩니다.
메트릭 보내기
파일의 worker.cs
내용을 다음 코드로 바꿉니다.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.ApplicationInsights;
namespace WorkerService3
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private TelemetryClient _telemetryClient;
public Worker(ILogger<Worker> logger, TelemetryClient tc)
{
_logger = logger;
_telemetryClient = tc;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{ // The following line demonstrates usages of GetMetric API.
// Here "computersSold", a custom metric name, is being tracked with a value of 42 every second.
while (!stoppingToken.IsCancellationRequested)
{
_telemetryClient.GetMetric("ComputersSold").TrackValue(42);
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
}
샘플 코드를 실행하면 Visual Studio 출력 창에서 원격 분석이 전송되지 않고 루프가 반복적으로 실행되는 것을 볼 while
수 있습니다. 단일 원격 분석 항목은 테스트에서 다음과 같은 60초 표시 주위에 전송됩니다.
Application Insights Telemetry: {"name":"Microsoft.ApplicationInsights.Dev.00000000-0000-0000-0000-000000000000.Metric", "time":"2019-12-28T00:54:19.0000000Z",
"ikey":"00000000-0000-0000-0000-000000000000",
"tags":{"ai.application.ver":"1.0.0.0",
"ai.cloud.roleInstance":"Test-Computer-Name",
"ai.internal.sdkVersion":"m-agg2c:2.12.0-21496",
"ai.internal.nodeName":"Test-Computer-Name"},
"data":{"baseType":"MetricData",
"baseData":{"ver":2,"metrics":[{"name":"ComputersSold",
"kind":"Aggregation",
"value":1722,
"count":41,
"min":42,
"max":42,
"stdDev":0}],
"properties":{"_MS.AggregationIntervalMs":"42000",
"DeveloperMode":"true"}}}}
이 단일 원격 분석 항목은 41개의 고유 메트릭 측정의 집계를 나타냅니다. 동일한 값을 반복해서 전송했기 때문에 동일한 최대() 및 최소(stDev
) 값의 0
표준 편차(max
min
)가 있습니다. 이 속성은 value
집계된 모든 개별 값의 합계를 나타냅니다.
참고
이 메서드는 GetMetric
마지막 값(예 gauge
: )을 추적하거나 히스토그램 또는 분포 추적을 지원하지 않습니다.
Logs(분석) 환경에서 Application Insights 리소스를 검사하는 경우 개별 원격 분석 항목은 다음 스크린샷과 같습니다.
참고
원시 원격 분석 항목에 수집된 후 명시적 합계 속성/필드가 포함되지 않았지만 사용자에 대한 항목을 만듭니다. 이 경우 속성과 value
속성은 모두 valueSum
동일한 것을 나타냅니다.
포털의 메트 릭 섹션에서 사용자 지정 메트릭 원격 분석에 로그 기반 및 사용자 지정 메트릭으로 액세스할 수도 있습니다. 다음 스크린샷은 로그 기반 메트릭의 예입니다.
높은 처리량 사용에 대한 캐시 메트릭 참조
경우에 따라 메트릭 값이 자주 관찰될 수 있습니다. 예를 들어 초당 500개의 요청을 처리하는 처리량이 높은 서비스는 각 요청에 대해 20개의 원격 분석 메트릭을 내보내려고 할 수 있습니다. 결과는 초당 10,000개의 값을 추적하는 것을 의미합니다. 이러한 높은 처리량 시나리오에서 사용자는 일부 조회를 방지하여 SDK를 지원해야 할 수 있습니다.
예를 들어 앞의 예제에서는 메트릭 ComputersSold
에 대한 핸들에 대한 조회를 수행한 다음 관찰된 값을 42
추적했습니다. 대신, 핸들은 여러 트랙 호출에 대해 캐시될 수 있습니다.
//...
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// This is where the cache is stored to handle faster lookup
Metric computersSold = _telemetryClient.GetMetric("ComputersSold");
while (!stoppingToken.IsCancellationRequested)
{
computersSold.TrackValue(42);
computersSold.TrackValue(142);
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(50, stoppingToken);
}
}
이전 예제에서는 메트릭 핸들을 캐싱하는 것 외에도 루프가 더 자주 실행되도록 50밀리초로 감소 Task.Delay
했습니다. 결과는 772 TrackValue()
개 호출입니다.
다차원 메트릭
이전 섹션의 예제에서는 0차원 메트릭을 보여 줍니다. 메트릭은 다차원일 수도 있습니다. 현재 최대 10개의 차원을 지원합니다.
다음은 1차원 메트릭을 만드는 방법의 예입니다.
//...
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// This is an example of a metric with a single dimension.
// FormFactor is the name of the dimension.
Metric computersSold= _telemetryClient.GetMetric("ComputersSold", "FormFactor");
while (!stoppingToken.IsCancellationRequested)
{
// The number of arguments (dimension values)
// must match the number of dimensions specified while GetMetric.
// Laptop, Tablet, etc are values for the dimension "FormFactor"
computersSold.TrackValue(42, "Laptop");
computersSold.TrackValue(20, "Tablet");
computersSold.TrackValue(126, "Desktop");
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(50, stoppingToken);
}
}
샘플 코드를 60초 이상 실행하면 세 개의 고유 원격 분석 항목이 Azure로 전송됩니다. 각 항목은 세 가지 폼 팩터 중 하나의 집계를 나타냅니다. 이전과 마찬가지로 로그(분석) 보기에서 자세히 살펴볼 수 있습니다.
메트릭 탐색기에서:
메트릭을 새 사용자 지정 차원으로 분할하거나 메트릭 보기를 사용하여 사용자 지정 차원을 볼 수 없습니다.
기본적으로 메트릭 탐색기 내의 다차원 메트릭은 Application Insights 리소스에서 설정되지 않습니다.
다차원 메트릭 사용
Application Insights 리소스에 다차원 메트릭을 사용하도록 설정하려면 사용자지정 메트릭을> 차원 > 에 대한 경고를 사용하도록 설정하여 사용량 및 예상 비용을>선택합니다. 자세한 내용은 사용자 지정 메트릭 차원 및 사전 집계를 참조하세요.
변경하고 새 다차원 원격 분석을 보낸 후 분할 적용을 선택할 수 있습니다.
참고
포털에서 기능이 켜진 후에 새로 전송된 메트릭에만 차원이 저장됩니다.
각 FormFactor
차원에 대한 메트릭 집계를 봅니다.
세 개 이상의 차원이 있는 경우 MetricIdentifier 사용
현재 10개의 차원이 지원됩니다. 3차원 이상에는 다음을 사용해야 MetricIdentifier
합니다.
// Add "using Microsoft.ApplicationInsights.Metrics;" to use MetricIdentifier
// MetricIdentifier id = new MetricIdentifier("[metricNamespace]","[metricId],"[dim1]","[dim2]","[dim3]","[dim4]","[dim5]");
MetricIdentifier id = new MetricIdentifier("CustomMetricNamespace","ComputerSold", "FormFactor", "GraphicsCard", "MemorySpeed", "BatteryCapacity", "StorageCapacity");
Metric computersSold = _telemetryClient.GetMetric(id);
computersSold.TrackValue(110,"Laptop", "Nvidia", "DDR4", "39Wh", "1TB");
사용자 지정 메트릭 구성
메트릭 구성을 변경하려면 메트릭이 초기화된 위치에서 변경해야 합니다.
특수 차원 이름
메트릭은 액세스하는 데 사용되는 원격 분석 컨텍스트를 TelemetryClient
사용하지 않습니다. 클래스에서 상수로 사용할 수 있는 MetricDimensionNames
특수 차원 이름을 사용하는 것이 이 제한 사항에 가장 적합한 해결 방법입니다.
다음 Special Operation Request Size
메트릭에서 보낸 메트릭 집계는 로 설정Context.Operation.Name
Special Operation
.
TrackMetric()
메서드 또는 다른 TrackXXX()
메서드가 올바르게 OperationName
설정되었습니다Special Operation
.
//...
TelemetryClient specialClient;
private static int GetCurrentRequestSize()
{
// Do stuff
return 1100;
}
int requestSize = GetCurrentRequestSize()
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
//...
specialClient.Context.Operation.Name = "Special Operation";
specialClient.GetMetric("Special Operation Request Size").TrackValue(requestSize);
//...
}
}
이 경우 클래스에 나열된 MetricDimensionNames
특수 차원 이름을 사용하여 값을 지정합니다 TelemetryContext
.
예를 들어 다음 문에서 생성된 메트릭 집계가 Application Insights 클라우드 엔드포인트로 전송되면 해당 Context.Operation.Name
데이터 필드는 다음으로 Special Operation
설정됩니다.
_telemetryClient.GetMetric("Request Size", MetricDimensionNames.TelemetryContext.Operation.Name).TrackValue(requestSize, "Special Operation");
이 특수 차원의 값은 복사 TelemetryContext
되며 일반 차원으로 사용되지 않습니다. 또한 일반적인 메트릭 탐색을 위해 작업 차원을 유지하려면 해당 용도로 별도의 차원을 만들어야 합니다.
_telemetryClient.GetMetric("Request Size", "Operation Name", MetricDimensionNames.TelemetryContext.Operation.Name).TrackValue(requestSize, "Special Operation", "Special Operation");
차원 및 시계열 제한
원격 분석 하위 시스템이 실수로 리소스를 사용하지 않도록 하려면 메트릭당 최대 데이터 계열 수를 제어할 수 있습니다. 기본 제한은 메트릭당 총 데이터 계열이 1,000개 이하이며 차원당 100개 이하의 값입니다.
중요한
차원에 낮은 카디널 값을 사용하여 제한을 방지합니다.
차원 및 시계열 제한의 컨텍스트에서 제한을 관찰하는 데 사용합니다 Metric.TrackValue(..)
. 한도에 이미 도달하면 Metric.TrackValue(..)
반환 False
되고 값이 추적되지 않습니다. 그렇지 않으면 True
. 이 동작은 메트릭에 대한 데이터가 사용자 입력에서 발생하는 경우에 유용합니다.
MetricConfiguration
생성자는 각 메트릭 내에서 다른 계열을 관리하는 방법과 메트릭의 각 개별 계열에 대한 집계 동작을 지정하는 IMetricSeriesConfiguration
클래스의 개체를 관리하는 방법에 대한 몇 가지 옵션을 사용합니다.
var metConfig = new MetricConfiguration(seriesCountLimit: 100, valuesPerDimensionLimit:2,
new MetricSeriesConfigurationForMeasurement(restrictToUInt32Values: false));
Metric computersSold = _telemetryClient.GetMetric("ComputersSold", "Dimension1", "Dimension2", metConfig);
// Start tracking.
computersSold.TrackValue(100, "Dim1Value1", "Dim2Value1");
computersSold.TrackValue(100, "Dim1Value1", "Dim2Value2");
// The following call gives 3rd unique value for dimension2, which is above the limit of 2.
computersSold.TrackValue(100, "Dim1Value1", "Dim2Value3");
// The above call does not track the metric, and returns false.
-
seriesCountLimit
는 메트릭에 포함될 수 있는 데이터 시계열의 최대 수입니다. 이 제한에 도달하면 이 제한을 호출하면TrackValue()
일반적으로 새 계열이 반환false
됩니다. -
valuesPerDimensionLimit
는 비슷한 방식으로 차원당 고유 값 수를 제한합니다. -
restrictToUInt32Values
는 음수가 아닌 정수 값만 추적해야 하는지 여부를 결정합니다.
다음은 상한 한도를 초과하는지 확인하기 위해 메시지를 보내는 방법의 예입니다.
if (! computersSold.TrackValue(100, "Dim1Value1", "Dim2Value3"))
{
// Add "using Microsoft.ApplicationInsights.DataContract;" to use SeverityLevel.Error
_telemetryClient.TrackTrace("Metric value not tracked as value of one of the dimension exceeded the cap. Revisit the dimensions to ensure they are within the limits",
SeverityLevel.Error);
}
사용자 지정 작업 추적
Application Insights SDK는 들어오는 HTTP 요청 및 HTTP 요청 및 SQL 쿼리와 같은 종속 서비스에 대한 호출을 자동으로 추적합니다. 요청 및 종속성의 추적 및 상관 관계를 통해 이 애플리케이션을 결합하는 모든 마이크로 서비스에서 전체 애플리케이션의 응답성과 안정성을 확인할 수 있습니다.
일반적으로 지원될 수 없는 애플리케이션 패턴 클래스가 있습니다. 이러한 패턴을 적절하게 모니터링하려면 수동 코드 계측이 필요합니다. 이 문서에서는 사용자 지정 큐 처리 및 장기 실행 백그라운드 작업 실행과 같은 수동 계측이 필요할 수 있는 몇 가지 패턴을 설명합니다.
이 섹션에서는 Application Insights SDK를 사용하여 사용자 지정 작업을 추적하는 방법에 대한 지침을 제공합니다.
개요
작업은 애플리케이션에서 실행하는 논리적 작업 조각입니다. 이름, 시작 시간, 기간, 결과 및 사용자 이름, 속성 및 결과와 같은 실행 컨텍스트가 있습니다. 작업 A가 작업 B에 의해 시작된 경우 작업 B는 A에 대한 부모로 설정됩니다. 작업에는 부모가 하나만 있을 수 있지만 자식 작업이 많을 수 있습니다. 작업 및 원격 분석 상관 관계에 대한 자세한 내용은 Application Insights 원격 분석 상관 관계를 참조하세요.
Application Insights .NET SDK에서 작업은 추상 클래스 OperationTelemetry 및 하위 항목 RequestTelemetry 및 DependencyTelemetry에 의해 설명됩니다.
들어오는 작업 추적
Application Insights 웹 SDK는 IIS 파이프라인 및 모든 ASP.NET Core 애플리케이션에서 실행되는 ASP.NET 애플리케이션에 대한 HTTP 요청을 자동으로 수집합니다. 다른 플랫폼 및 프레임워크에 대한 커뮤니티 지원 솔루션이 있습니다. 애플리케이션이 표준 또는 커뮤니티 지원 솔루션에서 지원되지 않는 경우 수동으로 계측할 수 있습니다.
사용자 지정 추적이 필요한 또 다른 예는 큐에서 항목을 받는 작업자입니다. 일부 큐의 경우 이 큐에 메시지를 추가하는 호출은 종속성으로 추적됩니다. 메시지 처리를 설명하는 상위 수준 작업은 자동으로 수집되지 않습니다.
이러한 작업을 추적하는 방법을 살펴보겠습니다.
상위 수준에서 작업은 알려진 속성을 만들고 RequestTelemetry
설정하는 것입니다. 작업이 완료되면 원격 분석을 추적합니다. 다음 예제에서는 이 작업을 보여 줍니다.
Owin 자체 호스팅 앱의 HTTP 요청
이 예제에서는 상관 관계에 대한 HTTP 프로토콜에 따라 추적 컨텍스트가 전파됩니다. 설명된 헤더를 수신해야 합니다.
코드를 보려면 확장
public class ApplicationInsightsMiddleware : OwinMiddleware
{
// You may create a new TelemetryConfiguration instance, reuse one you already have,
// or fetch the instance created by Application Insights SDK.
private readonly TelemetryConfiguration telemetryConfiguration = TelemetryConfiguration.CreateDefault();
private readonly TelemetryClient telemetryClient = new TelemetryClient(telemetryConfiguration);
public ApplicationInsightsMiddleware(OwinMiddleware next) : base(next) {}
public override async Task Invoke(IOwinContext context)
{
// Let's create and start RequestTelemetry.
var requestTelemetry = new RequestTelemetry
{
Name = $"{context.Request.Method} {context.Request.Uri.GetLeftPart(UriPartial.Path)}"
};
// If there is a Request-Id received from the upstream service, set the telemetry context accordingly.
if (context.Request.Headers.ContainsKey("Request-Id"))
{
var requestId = context.Request.Headers.Get("Request-Id");
// Get the operation ID from the Request-Id (if you follow the HTTP Protocol for Correlation).
requestTelemetry.Context.Operation.Id = GetOperationId(requestId);
requestTelemetry.Context.Operation.ParentId = requestId;
}
// StartOperation is a helper method that allows correlation of
// current operations with nested operations/telemetry
// and initializes start time and duration on telemetry items.
var operation = telemetryClient.StartOperation(requestTelemetry);
// Process the request.
try
{
await Next.Invoke(context);
}
catch (Exception e)
{
requestTelemetry.Success = false;
requestTelemetry.ResponseCode;
telemetryClient.TrackException(e);
throw;
}
finally
{
// Update status code and success as appropriate.
if (context.Response != null)
{
requestTelemetry.ResponseCode = context.Response.StatusCode.ToString();
requestTelemetry.Success = context.Response.StatusCode >= 200 && context.Response.StatusCode <= 299;
}
else
{
requestTelemetry.Success = false;
}
// Now it's time to stop the operation (and track telemetry).
telemetryClient.StopOperation(operation);
}
}
public static string GetOperationId(string id)
{
// Returns the root ID from the '|' to the first '.' if any.
int rootEnd = id.IndexOf('.');
if (rootEnd < 0)
rootEnd = id.Length;
int rootStart = id[0] == '|' ? 1 : 0;
return id.Substring(rootStart, rootEnd - rootStart);
}
}
상관 관계에 대한 HTTP 프로토콜도 헤더를 Correlation-Context
선언합니다. 간단히 하기 위해 여기에서 생략됩니다.
큐 계측
상관 관계에 대한W3C 추적 컨텍스트 및 HTTP 프로토콜은 HTTP 요청과 상관 관계 세부 정보를 전달하지만 모든 큐 프로토콜은 큐 메시지를 따라 동일한 세부 정보가 전달되는 방법을 정의해야 합니다. AMQP와 같은 일부 큐 프로토콜에서는 더 많은 메타데이터를 전달할 수 있습니다. Azure Storage 큐와 같은 다른 프로토콜에서는 컨텍스트를 메시지 페이로드로 인코딩해야 합니다.
참고
구성 요소 간 추적은 아직 큐에 지원되지 않습니다.
HTTP를 사용하면 생산자와 소비자가 다른 Application Insights 리소스에 원격 분석을 보내는 경우 트랜잭션 진단 환경 및 애플리케이션 맵은 트랜잭션을 표시하고 엔드 투 엔드를 매핑합니다. 큐의 경우 이 기능은 아직 지원되지 않습니다.
Service Bus 큐
추적 정보는 Azure Service Bus 메시징을 통한 분산 추적 및 상관 관계를 참조하세요.
Azure Storage 큐
다음 예제에서는 Azure Storage 큐 작업을 추적하고 생산자, 소비자 및 Azure Storage 간의 원격 분석 상관 관계를 지정하는 방법을 보여 줍니다.
스토리지 큐에는 HTTP API가 있습니다. 큐에 대한 모든 호출은 HTTP 요청에 대한 Application Insights 종속성 수집기에서 추적됩니다. 기본적으로 ASP.NET 및 ASP.NET Core 애플리케이션에서 구성됩니다. 다른 종류의 애플리케이션에서는 콘솔 애플리케이션 설명서를 참조하세요.
Application Insights 작업 ID와 스토리지 요청 ID의 상관 관계를 지정할 수도 있습니다. 스토리지 요청 클라이언트 및 서버 요청 ID를 설정하고 가져오는 방법에 대한 자세한 내용은 Azure Storage 모니터링, 진단 및 문제 해결을 참조하세요.
Storage 큐는 HTTP API를 지원하므로 큐가 있는 모든 작업은 Application Insights에서 자동으로 추적됩니다. 대부분의 경우 이 계측만으로도 충분합니다. 소비자 쪽의 추적을 생산자 추적과 상호 연결하려면 상관 관계에 대한 HTTP 프로토콜에서 수행하는 방식과 비슷한 상관 관계 컨텍스트를 전달해야 합니다.
이 예제에서는 작업을 추적하는 Enqueue
방법을 보여줍니다. 당신은 할 수 있어요:
-
상관 관계 재시도(있는 경우): 모두 작업인 하나의 공통 부모가
Enqueue
있습니다. 그렇지 않으면 들어오는 요청의 자식으로 추적됩니다. 큐에 대한 여러 논리적 요청이 있는 경우 다시 시도된 호출을 찾기 어려울 수 있습니다. - 스토리지 로그 상관 관계(필요한 경우): Application Insights 원격 분석과 상관 관계가 있습니다.
작업은 Enqueue
부모 작업의 자식입니다. 예를 들어 들어오는 HTTP 요청이 있습니다. HTTP 종속성 호출은 작업의 자식 Enqueue
및 들어오는 요청의 손자입니다.
public async Task Enqueue(CloudQueue queue, string message)
{
var operation = telemetryClient.StartOperation<DependencyTelemetry>("enqueue " + queue.Name);
operation.Telemetry.Type = "Azure queue";
operation.Telemetry.Data = "Enqueue " + queue.Name;
// MessagePayload represents your custom message and also serializes correlation identifiers into payload.
// For example, if you choose to pass payload serialized to JSON, it might look like
// {'RootId' : 'some-id', 'ParentId' : '|some-id.1.2.3.', 'message' : 'your message to process'}
var jsonPayload = JsonConvert.SerializeObject(new MessagePayload
{
RootId = operation.Telemetry.Context.Operation.Id,
ParentId = operation.Telemetry.Id,
Payload = message
});
CloudQueueMessage queueMessage = new CloudQueueMessage(jsonPayload);
// Add operation.Telemetry.Id to the OperationContext to correlate Storage logs and Application Insights telemetry.
OperationContext context = new OperationContext { ClientRequestID = operation.Telemetry.Id};
try
{
await queue.AddMessageAsync(queueMessage, null, null, new QueueRequestOptions(), context);
}
catch (StorageException e)
{
operation.Telemetry.Properties.Add("AzureServiceRequestID", e.RequestInformation.ServiceRequestID);
operation.Telemetry.Success = false;
operation.Telemetry.ResultCode = e.RequestInformation.HttpStatusCode.ToString();
telemetryClient.TrackException(e);
}
finally
{
// Update status code and success as appropriate.
telemetryClient.StopOperation(operation);
}
}
애플리케이션 보고서에서 원격 분석의 양을 줄이거나 다른 이유로 작업을 추적 Enqueue
하지 않으려면 API를 Activity
직접 사용합니다.
- Application Insights 작업을 시작하는 대신 새
Activity
작업을 만들고 시작합니다. 작업 이름을 제외한 속성은 할당할 필요가 없습니다 . - 대신 메시지 페이로드로 직렬화
yourActivity.Id
합니다operation.Telemetry.Id
. 를 사용할Activity.Current.Id
수도 있습니다.
마찬가지로 다른 큐 작업을 계측할 수 있습니다. 미리 보기 작업은 큐에서 제거 작업과 유사한 방식으로 계측되어야 합니다. 큐 관리 작업을 계측할 필요는 없습니다. Application Insights는 HTTP와 같은 작업을 추적하며 대부분의 경우 충분합니다.
메시지 삭제를 계측할 때 작업(상관 관계) 식별자를 설정해야 합니다. 또는 API를 Activity
사용할 수 있습니다. 그런 다음 Application Insights SDK에서 수행하므로 원격 분석 항목에 작업 식별자를 설정할 필요가 없습니다.
- 큐에서 항목을 얻은 후 새
Activity
항목을 만듭니다. - 소비자 및 생산자 로그의 상관 관계를 지정하는 데 사용합니다
Activity.SetParentId(message.ParentId)
. - 를 시작합니다
Activity
. - 도우미를 사용하여
Start/StopOperation
큐에서 제거, 처리 및 삭제 작업을 추적합니다. 동일한 비동기 제어 흐름(실행 컨텍스트)에서 수행합니다. 이러한 방식으로 상호 연관이 올바르게 지정됩니다. - 를 중지합니다
Activity
. - 원격 분석을 수동으로 사용
Start/StopOperation
하거나 호출Track
합니다.
종속성 형식
Application Insights는 종속성 유형을 사용하여 UI 환경을 사용자 지정합니다. 큐의 경우 트랜잭션 진단 환경을 개선하는 다음 유형을 DependencyTelemetry
인식합니다.
-
Azure queue
Azure Storage 큐의 경우 -
Azure Event Hubs
Azure Event Hubs용 -
Azure Service Bus
Azure Service Bus용
일괄 처리
일부 큐에서는 하나의 요청으로 여러 메시지를 큐에서 제거할 수 있습니다. 이러한 메시지 처리는 아마도 독립적이며 다른 논리 작업에 속합니다. 작업과 처리 중인 특정 메시지의 Dequeue
상관 관계를 지정할 수 없습니다.
각 메시지는 자체 비동기 제어 흐름에서 처리되어야 합니다. 자세한 내용은 나가는 종속성 추적 섹션을 참조하세요.
장기 실행 백그라운드 작업
일부 애플리케이션은 사용자 요청으로 인해 발생할 수 있는 장기 실행 작업을 시작합니다. 추적/계측 관점에서 요청 또는 종속성 계측과 다르지 않습니다.
async Task BackgroundTask()
{
var operation = telemetryClient.StartOperation<DependencyTelemetry>(taskName);
operation.Telemetry.Type = "Background";
try
{
int progress = 0;
while (progress < 100)
{
// Process the task.
telemetryClient.TrackTrace($"done {progress++}%");
}
// Update status code and success as appropriate.
}
catch (Exception e)
{
telemetryClient.TrackException(e);
// Update status code and success as appropriate.
throw;
}
finally
{
telemetryClient.StopOperation(operation);
}
}
이 예제에서는 telemetryClient.StartOperation
상관 관계 컨텍스트를 만들고 채웁니다 DependencyTelemetry
. 작업을 예약한 들어오는 요청에 의해 만들어진 부모 작업이 있다고 가정해 보겠습니다. 들어오는 요청과 동일한 비동기 제어 흐름에서 시작하는 한 BackgroundTask
해당 부모 작업과 상관 관계가 있습니다.
BackgroundTask
중첩된 모든 원격 분석 항목은 요청이 종료된 후에도 발생한 요청과 자동으로 상관 관계가 지정됩니다.
작업이 연결된 BackgroundTask
작업(Activity
)이 없는 백그라운드 스레드에서 시작하는 경우 부모가 없습니다. 그러나 중첩된 작업이 있을 수 있습니다. 작업에서 보고된 모든 원격 분석 항목은 생성된 항목과 DependencyTelemetry
상관 관계가 있습니다 BackgroundTask
.
나가는 종속성 추적
고유한 종속성 종류 또는 Application Insights에서 지원되지 않는 작업을 추적할 수 있습니다.
Service Bus 큐 또는 스토리지 큐의 메서드는 Enqueue
이러한 사용자 지정 추적에 대한 예제로 사용될 수 있습니다.
사용자 지정 종속성 추적의 일반적인 방법은 다음과 같습니다.
-
TelemetryClient.StartOperation
상관 관계 및 시작, 타임스탬프를 비롯한 다른 속성에 필요한 속성을 채우는DependencyTelemetry
(확장) 메서드를 호출합니다. - 이름 및 필요한 다른 컨텍스트와 같은 다른 사용자 지정 속성을
DependencyTelemetry
설정합니다. - 종속성 호출을 수행하고 기다립니다.
- 작업이 완료되면 작업을
StopOperation
중지합니다. - 예외를 처리합니다.
public async Task RunMyTaskAsync()
{
using (var operation = telemetryClient.StartOperation<DependencyTelemetry>("task 1"))
{
try
{
var myTask = await StartMyTaskAsync();
// Update status code and success as appropriate.
}
catch(...)
{
// Update status code and success as appropriate.
}
}
}
작업을 삭제하면 작업이 중지되므로 호출 StopOperation
하는 대신 작업을 수행할 수 있습니다.
경고
경우에 따라 처리되지 않은 예외가 호출되지 않을finally
수 있으므로 작업이 추적되지 않을 수 있습니다.
병렬 작업 처리 및 추적
호출 StopOperation
은 시작된 작업만 중지합니다. 현재 실행 중인 작업이 중지 StopOperation
하려는 작업과 일치하지 않으면 아무 작업도 수행하지 않습니다. 이 상황은 동일한 실행 컨텍스트에서 여러 작업을 병렬로 시작하는 경우에 발생할 수 있습니다.
var firstOperation = telemetryClient.StartOperation<DependencyTelemetry>("task 1");
var firstTask = RunMyTaskAsync();
var secondOperation = telemetryClient.StartOperation<DependencyTelemetry>("task 2");
var secondTask = RunMyTaskAsync();
await firstTask;
// FAILURE!!! This will do nothing and will not report telemetry for the first operation
// as currently secondOperation is active.
telemetryClient.StopOperation(firstOperation);
await secondTask;
병렬로 실행되는 작업을 격리하기 위해 항상 동일한 비동기 메서드에서 작업을 호출 StartOperation
하고 처리해야 합니다. 작업이 동기(또는 비동기 아님)인 경우 프로세스를 래핑하고 추적합니다 Task.Run
.
public void RunMyTask(string name)
{
using (var operation = telemetryClient.StartOperation<DependencyTelemetry>(name))
{
Process();
// Update status code and success as appropriate.
}
}
public async Task RunAllTasks()
{
var task1 = Task.Run(() => RunMyTask("task 1"));
var task2 = Task.Run(() => RunMyTask("task 2"));
await Task.WhenAll(task1, task2);
}
ApplicationInsights 작업 및 System.Diagnostics.Activity
System.Diagnostics.Activity
는 분산 추적 컨텍스트를 나타내며 프레임워크 및 라이브러리에서 프로세스 내부 및 외부의 컨텍스트를 만들고 전파하고 원격 분석 항목의 상관 관계를 지정하는 데 사용됩니다.
Activity
는 프레임워크/라이브러리 간의 알림 메커니즘과 System.Diagnostics.DiagnosticSource
함께 작동하여 들어오거나 나가는 요청 및 예외와 같은 흥미로운 이벤트에 대해 알립니다.
활동은 Application Insights의 일류 시민입니다. 자동 종속성 및 요청 컬렉션은 이벤트와 DiagnosticSource
함께 크게 의존합니다. 애플리케이션에서 만든 Activity
경우 Application Insights 원격 분석이 생성되지 않습니다. Application Insights는 이벤트를 수신 DiagnosticSource
하고 이벤트 이름과 페이로드를 알고 원격 분석으로 변환 Activity
해야 합니다.
각 Application Insights 작업(요청 또는 종속성)에는 다음이 포함됩니다 Activity
.
StartOperation
호출되면 아래에 생성됩니다Activity
.
StartOperation
는 요청 또는 종속성 원격 분석을 수동으로 추적하고 모든 것이 상관 관계가 있는지 확인하는 권장 방법입니다.
Application Insights의 카운터
Application Insights는 성능 카운터 및 이벤트 카운터를 지원합니다. 이 가이드에서는 .NET 애플리케이션의 용도, 구성 및 사용을 포함하여 두 가지 모두에 대한 개요를 제공합니다.
개요
성능 카운터는 Windows 운영 체제에 기본 제공되며 CPU 사용량, 메모리 사용량 및 디스크 작업과 같은 미리 정의된 메트릭을 제공합니다. 이러한 카운터는 최소한의 설정으로 표준 성능 메트릭을 모니터링하는 데 적합합니다. 리소스 사용률을 추적하거나 Windows 기반 애플리케이션에서 시스템 수준 병목 현상 문제를 해결하는 데 도움이 되지만 사용자 지정 애플리케이션별 메트릭은 지원하지 않습니다.
이벤트 카운터는 Windows, Linux 및 macOS를 비롯한 여러 플랫폼에서 작동합니다. 개발자는 가볍고 사용자 지정 가능한 애플리케이션별 메트릭을 정의하고 모니터링하여 성능 카운터보다 더 많은 유연성을 제공할 수 있습니다. 이벤트 카운터는 시스템 메트릭이 부족하거나 플랫폼 간 애플리케이션에서 자세한 원격 분석이 필요한 경우에 유용합니다. 명시적 구현 및 구성이 필요하므로 설정을 더 많이 사용합니다.
성능 계수기
Windows는 프로세서, 메모리 및 디스크 사용 통계를 수집하는 데 사용되는 것과 같은 다양한 성능 카운터를 제공합니다. 사용자 고유의 성능 카운터를 정의할 수도 있습니다.
애플리케이션은 온-프레미스 호스트 또는 관리 액세스 권한이 있는 가상 머신의 IIS(인터넷 정보 서버)에서 실행되는 경우 성능 카운터 수집을 지원합니다. Azure Web Apps로 실행되는 애플리케이션은 성능 카운터에 직접 액세스할 수 없지만 Application Insights는 사용 가능한 카운터의 하위 집합을 수집합니다.
팁 (조언)
다른 메트릭과 마찬가지로 카운터가 지정된 한도를 벗어나는 경우 경고를 설정할 수 있습니다. 경고를 설정하려면 경고 창을 열고 경고 추가를 선택합니다.
필수 조건
성능 모니터 사용자 그룹에 추가하여 성능 카운터를 모니터링할 수 있는 앱 풀 서비스 계정 권한을 부여합니다.
net localgroup "Performance Monitor Users" /add "IIS APPPOOL\NameOfYourPool"
카운터 보기
메트릭 창에는 기본 성능 카운터 집합이 표시됩니다.
ASP.NET 웹 애플리케이션에 대한 기본 카운터:
- % Process\Processor Time
- % Process\Processor Time normalized
- Memory\Available 바이트
- ASP.NET Requests/Sec
- .NET CLR(공용 언어 런타임) 예외 throw됨/초
- ASP.NET ApplicationsRequest 실행 시간
- Process\Private Bytes
- Process\IO Data Bytes/sec
- ASP.NET Applications\Requests In Application Queue
- Processor(_Total)\% Processor Time
카운터 추가
원하는 성능 카운터가 메트릭 목록에 포함되지 않은 경우 추가할 수 있습니다.
옵션 1: ApplicationInsights.config구성
로컬 서버에서 이 PowerShell 명령을 사용하여 서버에서 사용할 수 있는 카운터를 알아봅니다.
Get-Counter -ListSet *
자세한 내용은
Get-Counter
를 참조하세요.ApplicationInsights.config
을(를) 여십시오.개발 중에 앱에 Application Insights를 추가한 경우:
- 프로젝트에서 편집
ApplicationInsights.config
합니다. - 서버에 다시 배포합니다.
- 프로젝트에서 편집
성능 수집기 지시문을 편집합니다.
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector"> <Counters> <Add PerformanceCounter="\Objects\Processes"/> <Add PerformanceCounter="\Sales(photo)\# Items Sold" ReportAs="Photo sales"/> </Counters> </Add>
직접 구현하는 표준 카운터와 카운터를 모두 캡처합니다.
\Objects\Processes
는 모든 Windows 시스템에서 사용할 수 있는 표준 카운터의 예입니다.
\Sales(photo)\# Items Sold
는 웹 서비스에서 구현될 수 있는 사용자 지정 카운터의 예입니다.
형식은 \Category(instance)\Counter
인스턴스가 없는 범주에 해당 \Category\Counter
합니다.
ReportAs
매개 변수는 일치하지 [a-zA-Z()/-_ \.]+
않는 카운터 이름에 필요합니다.
인스턴스를 지정하면 보고된 메트릭의 차원이 CounterInstanceName
됩니다.
옵션 2: 코드의 구성
다음 섹션을 참조하세요.
ASP.NET 웹 애플리케이션 또는 .NET/.NET Core 콘솔 애플리케이션에 대한 코드에서 성능 카운터 수집
시스템 성능 카운터를 수집하고 Application Insights로 보내려면 다음 코드 조각을 적용할 수 있습니다.
var perfCollectorModule = new PerformanceCollectorModule();
perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(
@"\Process([replace-with-application-process-name])\Page Faults/sec", "PageFaultsPerfSec"));
perfCollectorModule.Initialize(TelemetryConfiguration.Active);
또는 만든 사용자 지정 메트릭을 사용하여 동일한 작업을 수행할 수 있습니다.
var perfCollectorModule = new PerformanceCollectorModule();
perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(
@"\Sales(photo)\# Items Sold", "Photo sales"));
perfCollectorModule.Initialize(TelemetryConfiguration.Active);
Azure App Service의 Azure Web Apps 및 Windows 컨테이너에서 실행되는 애플리케이션에 대한 성능 카운터
Azure Web Apps에 배포된 ASP.NET 및 ASP.NET Core 애플리케이션은 모두 특별한 샌드박스 환경에서 실행됩니다. Azure App Service에 배포된 애플리케이션은 Windows 컨테이너 를 활용하거나 샌드박스 환경에서 호스트될 수 있습니다. 애플리케이션이 Windows 컨테이너에 배포된 경우 모든 표준 성능 카운터를 컨테이너 이미지에서 사용할 수 있습니다.
샌드박스 환경에서는 시스템 성능 카운터에 대한 직접 액세스를 허용하지 않습니다. 그러나 제한된 카운터 하위 집합은 환경 변수로 노출되는 Perf Counters에 설명된 대로 환경 변수로 노출됩니다. 이 환경에서는 카운터의 하위 집합만 사용할 수 있습니다. 전체 목록은 환경 변수로 노출된 성능 카운터를 참조하세요.
ASP.NET 및 ASP.NET Core용 Application Insights SDK는 코드가 웹앱 또는 비 Windows 컨테이너에 배포되는지 여부를 검색합니다. 검색은 샌드박스 환경에서 성능 카운터를 수집할지 아니면 Windows 컨테이너 또는 가상 머신에서 호스트되는 경우 표준 컬렉션 메커니즘을 활용하는지 여부를 결정합니다.
성능 카운터에 대한 Log Analytics 쿼리
Log Analytics에서 성능 카운터 보고서를 검색하고 표시할 수 있습니다.
performanceCounters 스키마는 각 성능 카운터의 category
이름counter
, 이름 및 instance
이름을 노출합니다. 각 애플리케이션에 대한 원격 분석에서 해당 애플리케이션에 대한 카운터만 표시됩니다. 예를 들어 사용할 수 있는 카운터를 확인하려면 다음을 수행합니다.
performanceCounters | summarize count(), avg(value) by category, instance, counter
여기서는 Instance
역할 또는 서버 컴퓨터 인스턴스가 아닌 성능 카운터 인스턴스를 참조합니다. 성능 카운터 인스턴스 이름은 일반적으로 프로세스 또는 애플리케이션의 이름으로 프로세서 시간과 같은 카운터를 분할합니다.
최근 기간 동안 사용 가능한 메모리 차트를 얻으려면 다음을 수행합니다.
performanceCounters | where counter == "Available Bytes" | summarize avg(value), min(value) by bin(timestamp, 1h) | render timechart
다른 원격 분석과 마찬가지로 performanceCounters 에는 앱이 실행 중인 호스트 서버 인스턴스의 ID를 나타내는 열 cloud_RoleInstance
도 있습니다. 예를 들어 다른 컴퓨터에서 앱의 성능을 비교하려면 다음을 수행합니다.
performanceCounters | where counter == "% Processor Time" and instance == "SendMetrics" | summarize avg(value) by cloud_RoleInstance, bin(timestamp, 1d)
성능 카운터 FAQ
FAQ(질문과 대답)를 검토하려면 성능 카운터 FAQ를 참조하세요.
이벤트 카운터
EventCounter
는 카운터 또는 통계를 게시하고 사용하는 .NET/.NET Core 메커니즘입니다. EventCounters는 Windows, Linux 및 macOS와 같은 모든 OS 플랫폼에서 지원됩니다. Windows 시스템에서만 지원되는 PerformanceCounters 에 해당하는 플랫폼 간이라고 생각할 수 있습니다.
사용자가 요구 사항에 맞게 사용자 지정 이벤트 카운터를 게시할 수 있지만 .NET 은 기본적으로 이러한 카운터 집합을 게시합니다. 이 문서에서는 Azure Application Insights에서 이벤트 카운터(시스템 정의 또는 사용자 정의)를 수집하고 보는 데 필요한 단계를 안내합니다.
팁 (조언)
다른 메트릭과 마찬가지로 카운터가 지정된 한도를 벗어나는 경우 경고를 설정할 수 있습니다. 경고를 설정하려면 경고 창을 열고 경고 추가를 선택합니다.
Application Insights를 사용하여 EventCounters 수집
Application Insights는 새로 릴리스된 NuGet 패키지 EventCounters
의 일부인 수집을 지원 EventCounterCollectionModule
합니다.
EventCounterCollectionModule
는 AspNetCore 또는 WorkerService를 사용할 때 자동으로 사용하도록 설정됩니다.
EventCounterCollectionModule
는 구성할 수 없는 컬렉션 빈도가 60초인 카운터를 수집합니다. EventCounters를 수집하는 데 필요한 특별한 권한은 없습니다. ASP.NET Core 애플리케이션의 경우 Microsoft.ApplicationInsights.AspNetCore 패키지도 추가하려고 합니다.
dotnet add package Microsoft.ApplicationInsights.EventCounterCollector
dotnet add package Microsoft.ApplicationInsights.AspNetCore
수집된 기본 카운터
AspNetCore SDK 또는 WorkerService SDK의 2.15.0 버전부터는 기본적으로 카운터가 수집되지 않습니다. 모듈 자체가 활성화되어 사용자가 원하는 카운터를 추가하여 모듈을 수집할 수 있습니다.
.NET 런타임에서 게시한 잘 알려진 카운터 목록을 보려면 사용 가능한 카운터 문서를 참조하세요.
수집할 카운터 사용자 지정
다음 예제에서는 카운터를 추가/제거하는 방법을 보여 줍니다. 이 사용자 지정은 Application Insights 원격 분석 컬렉션을 사용 AddApplicationInsightsTelemetry()
하거나 AddApplicationInsightsWorkerService()
사용하여 사용하도록 설정한 후 애플리케이션 서비스 구성의 일부로 수행됩니다. 다음은 ASP.NET Core 애플리케이션의 예제 코드입니다. 다른 유형의 애플리케이션은 이 문서를 참조하세요.
using Microsoft.ApplicationInsights.Extensibility.EventCounterCollector;
using Microsoft.Extensions.DependencyInjection;
builder.Services.ConfigureTelemetryModule<EventCounterCollectionModule>(
(module, o) =>
{
// Removes all default counters, if any.
module.Counters.Clear();
// Adds a user defined counter "MyCounter" from EventSource named "MyEventSource"
module.Counters.Add(
new EventCounterCollectionRequest("MyEventSource", "MyCounter"));
// Adds the system counter "gen-0-size" from "System.Runtime"
module.Counters.Add(
new EventCounterCollectionRequest("System.Runtime", "gen-0-size"));
}
);
EventCounter 컬렉션 모듈 비활성화
EventCounterCollectionModule
를 사용하여 ApplicationInsightsServiceOptions
사용하지 않도록 설정할 수 있습니다.
다음 예제에서는 ASP.NET Core SDK를 사용합니다.
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.Extensions.DependencyInjection;
var applicationInsightsServiceOptions = new ApplicationInsightsServiceOptions();
applicationInsightsServiceOptions.EnableEventCounterCollectionModule = false;
builder.Services.AddApplicationInsightsTelemetry(applicationInsightsServiceOptions);
WorkerService SDK에도 비슷한 방법을 사용할 수 있지만 다음 예제와 같이 네임스페이스를 변경해야 합니다.
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.Extensions.DependencyInjection;
var applicationInsightsServiceOptions = new ApplicationInsightsServiceOptions();
applicationInsightsServiceOptions.EnableEventCounterCollectionModule = false;
builder.Services.AddApplicationInsightsTelemetry(applicationInsightsServiceOptions);
이벤트 카운터에 대한 Log Analytics 쿼리
사용자 지정 메트릭 테이블의 Log Analytics에서 이벤트 카운터 보고서를 검색하고 표시할 수 있습니다.
예를 들어 다음 쿼리를 실행하여 수집되고 쿼리에 사용할 수 있는 카운터를 확인합니다.
customMetrics | summarize avg(value) by name
최근 기간 동안 특정 카운터(예: ThreadPool Completed Work Item Count
)의 차트를 얻으려면 다음 쿼리를 실행합니다.
customMetrics
| where name contains "System.Runtime|ThreadPool Completed Work Item Count"
| where timestamp >= ago(1h)
| summarize avg(value) by cloud_RoleInstance, bin(timestamp, 1m)
| render timechart
다른 원격 분석 과 마찬가지로 customMetrics 에는 앱이 실행 중인 호스트 서버 인스턴스의 ID를 나타내는 열 cloud_RoleInstance
도 있습니다. 이전 쿼리는 인스턴스당 카운터 값을 표시하며 다른 서버 인스턴스의 성능을 비교하는 데 사용할 수 있습니다.
이벤트 카운터 FAQ
FAQ(질문과 대답)를 검토하려면 이벤트 카운터 FAQ를 참조하세요.
Application Insights SDK 구성
이 부분에서는
- 원격 분석 채널
- 원격 분석 모듈
- 원격 분석 사용 안 함
- 원격 분석 이니셜라이저
- 원격 분석 프로세서
- ApplicationId 공급자
- 스냅샷 컬렉션
- 견본 추출
- HTTP를 통한 보강 및 상관 관계
ASP.NET 및 ASP.NET Core용 Application Insights SDK를 사용자 지정하여 기본 구성을 변경할 수 있습니다.
Application Insights .NET SDK는 여러 NuGet 패키지로 구성됩니다. 핵심 패키지는 Application Insights에 원격 분석을 보내기 위한 API를 제공합니다. 더 많은 패키지는 애플리케이션 및 해당 컨텍스트에서 원격 분석을 자동으로 추적하기 위한 원격 분석 모듈 및 이니셜라이저 를 제공합니다. 구성 파일을 조정하여 원격 분석 모듈 및 이니셜라이저를 사용하거나 사용하지 않도록 설정할 수 있습니다. 일부 매개 변수에 대한 매개 변수를 설정할 수도 있습니다.
구성 파일의 이름이 지정 ApplicationInsights.config
되거나 ApplicationInsights.xml
. 이름은 애플리케이션의 유형에 따라 달라집니다.
대부분의 SDK 버전을 설치하면 프로젝트에 자동으로 추가됩니다.
기본적으로Application Insights 원격 분석>추가ApplicationInsights.config
를 지원하는 Visual Studio 템플릿 프로젝트의 자동화된 환경을 사용하는 경우 파일은 프로젝트 루트 폴더에 만들어집니다. 컴파일한 후 bin 폴더에 복사됩니다. 또한 IIS 서버의 Application Insights 에이전트가 웹앱에 추가합니다.
중요한
Azure 웹 사이트의 확장 또는 AzureVM 및 가상 머신 확장 집합에 대한 확장이 사용되는 경우 구성 파일은 무시됩니다.
웹 페이지에서 SDK를 제어하는 동일한 파일이 없습니다.
원격 분석 채널
원격 분석 채널은 Application Insights SDK의 필수적인 부분입니다. Application Insights 서비스에 대한 원격 분석의 버퍼링 및 전송을 관리합니다. SDK의 .NET 및 .NET Core 버전에는 두 개의 기본 제공 원격 분석 채널이 있습니다InMemoryChannel
. ServerTelemetryChannel
이 문서에서는 각 채널에 대해 설명하고 채널 동작을 사용자 지정하는 방법을 보여 줍니다.
참고
FAQ(질문과 대답)를 검토하려면 원격 분석 채널 FAQ를 참조하세요.
원격 분석 채널이란?
원격 분석 채널은 원격 분석 항목을 버퍼링하고 쿼리 및 분석을 위해 저장되는 Application Insights 서비스로 보냅니다. 원격 분석 채널은 인터페이스를 구현하는 모든 클래스입니다 Microsoft.ApplicationInsights.ITelemetryChannel
.
원격 분석 채널의 메서드는 모든 원격 분석 이 Send(ITelemetry item)
니셜라이저 및 원격 분석 프로세서가 호출된 후에 호출됩니다. 따라서 원격 분석 프로세서에서 삭제한 항목은 채널에 도달하지 않습니다. 메서드는 Send()
일반적으로 항목을 백 엔드에 즉시 보내지 않습니다. 일반적으로 메모리에서 버퍼링하고 효율적인 전송을 위해 일괄 처리로 보냅니다.
버퍼링된 원격 분석을 즉시 보내는 것이 중요한 경우가 아니면 호출 Flush()
하지 마세요. 애플리케이션 종료, 예외 처리와 같은 시나리오 또는 백그라운드 작업 또는 명령줄 도구와 같은 수명이 짧은 프로세스를 사용하는 경우에만 사용합니다. 웹 애플리케이션 또는 장기 실행 서비스에서 SDK는 원격 분석 전송을 자동으로 처리합니다. 불필요하게 호출 Flush()
하면 성능 문제가 발생할 수 있습니다.
라이브 메트릭 스트림 에는 원격 분석의 라이브 스트리밍을 지원하는 사용자 지정 채널도 있습니다. 이 채널은 일반 원격 분석 채널과 독립적이며 이 문서는 적용되지 않습니다.
기본 제공 원격 분석 채널
Application Insights .NET 및 .NET Core SDK는 두 개의 기본 제공 채널과 함께 제공됩니다.
InMemoryChannel: 전송될 때까지 메모리의 항목을 버퍼링하는 경량 채널입니다. 항목은 메모리에 버퍼링되고 30초마다 한 번씩 또는 500개 항목이 버퍼링될 때마다 플러시됩니다. 이 채널은 오류 후 원격 분석 전송을 다시 시도하지 않으므로 최소한의 안정성 보장을 제공합니다. 또한 이 채널은 디스크에 항목을 보관하지 않습니다. 따라서 우아하든 그렇지 않든 관계없이 응용 프로그램 종료 시 언젠트된 항목이 영구적으로 손실됩니다. 이 채널은
Flush()
메모리 내 원격 분석 항목을 동기적으로 강제로 플러시하는 데 사용할 수 있는 메서드를 구현합니다. 이 채널은 동기 플러시가 이상적인 짧은 실행 애플리케이션에 적합합니다.이 채널은 더 큰 Microsoft.ApplicationInsights NuGet 패키지의 일부이며 다른 항목이 구성되지 않은 경우 SDK에서 사용하는 기본 채널입니다.
ServerTelemetryChannel: 재시도 정책과 로컬 디스크에 데이터를 저장하는 기능이 있는 고급 채널입니다. 이 채널은 일시적인 오류가 발생하는 경우 원격 분석 전송을 다시 시도합니다. 또한 이 채널은 로컬 디스크 스토리지를 사용하여 네트워크 중단 또는 높은 원격 분석 볼륨 동안 디스크에 항목을 유지합니다. 이러한 재시도 메커니즘 및 로컬 디스크 스토리지로 인해 이 채널은 더 신뢰할 수 있는 것으로 간주됩니다. 모든 프로덕션 시나리오에 권장됩니다. 이 채널은 공식 설명서에 따라 구성된 ASP.NET 및 ASP.NET Core 애플리케이션의 기본값입니다. 이 채널은 장기 실행 프로세스가 있는 서버 시나리오에 최적화되어 있습니다. 이
Flush()
채널에서 구현하는 메서드는 동기식이 아닙니다.이 채널은 Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel NuGet 패키지로 제공되며 Microsoft.ApplicationInsights.Web 또는 Microsoft.ApplicationInsights.AspNetCore NuGet 패키지를 사용할 때 자동으로 획득됩니다.
원격 분석 채널 구성
원격 분석 채널을 활성 원격 분석 구성으로 설정하여 구성합니다. ASP.NET 애플리케이션의 경우 구성에는 원격 분석 채널 인스턴스 TelemetryConfiguration.Active
를 수정하거나 수정하여 설정하는 작업이 포함됩니다 ApplicationInsights.config
. ASP.NET Core 애플리케이션의 경우 구성에는 종속성 주입 컨테이너에 채널을 추가하는 작업이 포함됩니다.
다음 섹션에서는 다양한 애플리케이션 유형에서 채널에 StorageFolder
대한 설정을 구성하는 예제를 보여 줍니다.
StorageFolder
는 구성 가능한 설정 중 하나일 뿐입니다. 구성 설정의 전체 목록은 이 문서의 뒷부분에 있는 채널 섹션의 구성 가능한 설정을 참조하세요.
옵션 1: 코드의 구성
다음 코드는 사용자 지정 위치로 ServerTelemetryChannel
StorageFolder
설정된 인스턴스를 설정합니다. 일반적으로 Global.aspx.cs 메서드에서 Application_Start()
애플리케이션의 시작 부분에 이 코드를 추가합니다.
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
protected void Application_Start()
{
var serverTelemetryChannel = new ServerTelemetryChannel();
serverTelemetryChannel.StorageFolder = @"d:\temp\applicationinsights";
serverTelemetryChannel.Initialize(TelemetryConfiguration.Active);
TelemetryConfiguration.Active.TelemetryChannel = serverTelemetryChannel;
}
옵션 2: ApplicationInsights.config구성
ApplicationInsights.config 다음 섹션에서는 사용자 지정 위치로 ServerTelemetryChannel
설정하여 구성된 채널을 보여 StorageFolder
줍니다.
<TelemetrySinks>
<Add Name="default">
<TelemetryProcessors>
<!-- Telemetry processors omitted for brevity -->
</TelemetryProcessors>
<TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel">
<StorageFolder>d:\temp\applicationinsights</StorageFolder>
</TelemetryChannel>
</Add>
</TelemetrySinks>
콘솔 애플리케이션에 대한 코드의 구성
콘솔 앱의 경우 코드는 .NET 및 .NET Core 모두에 대해 동일합니다.
var serverTelemetryChannel = new ServerTelemetryChannel();
serverTelemetryChannel.StorageFolder = @"d:\temp\applicationinsights";
serverTelemetryChannel.Initialize(TelemetryConfiguration.Active);
TelemetryConfiguration.Active.TelemetryChannel = serverTelemetryChannel;
ServerTelemetryChannel의 운영 세부 정보
ServerTelemetryChannel
는 메모리 내 버퍼에 도착하는 항목을 저장합니다. 항목은 30초마다 한 번씩 또는 500개 항목이 버퍼링될 때 직렬화, 압축 및 인스턴스에 Transmission
저장됩니다. 단일 Transmission
인스턴스는 최대 500개의 항목을 포함하며 Application Insights 서비스에 대한 단일 HTTPS 호출을 통해 전송되는 원격 분석의 일괄 처리를 나타냅니다.
기본적으로 최대 10 Transmission
개의 인스턴스를 병렬로 보낼 수 있습니다. 원격 분석이 더 빠른 속도로 도착하거나 네트워크 또는 Application Insights 백 엔드가 느린 Transmission
경우 인스턴스가 메모리에 저장됩니다. 이 메모리 Transmission
내 버퍼의 기본 용량은 5MB입니다. 메모리 내 용량을 초과 Transmission
하면 인스턴스가 최대 50MB까지 로컬 디스크에 저장됩니다.
Transmission
인스턴스는 네트워크 문제가 있는 경우에도 로컬 디스크에 저장됩니다. 로컬 디스크에 저장된 항목만 애플리케이션 충돌에서 살아남을 수 있습니다. 애플리케이션이 다시 시작될 때마다 전송됩니다. 네트워크 문제가 지속 ServerTelemetryChannel
되면 원격 분석을 보내기 위해 다시 시도하기 전에 10초에서 1시간 사이의 지수 백오프 논리를 사용합니다.
채널에서 구성 가능한 설정
각 채널에 대한 구성 가능한 설정의 전체 목록은 다음을 참조하세요.
다음은 가장 일반적으로 사용되는 설정입니다.ServerTelemetryChannel
MaxTransmissionBufferCapacity
: 채널에서 메모리의 전송을 버퍼링하는 데 사용하는 최대 메모리 양(바이트)입니다. 이 용량에 도달하면 새 항목이 로컬 디스크에 직접 저장됩니다. 기본값은 5MB입니다. 더 높은 값을 설정하면 디스크 사용량이 줄어들지만 애플리케이션이 충돌할 경우 메모리의 항목이 손실된다는 점을 기억하세요.MaxTransmissionSenderCapacity
: Application Insights로 동시에 전송되는 최대 인스턴스 수Transmission
입니다. 기본값은 10입니다. 이 설정은 더 높은 수로 구성할 수 있으며, 대량의 원격 분석이 생성될 때 권장됩니다. 대용량은 일반적으로 부하 테스트 중 또는 샘플링이 해제된 경우에 발생합니다.StorageFolder
: 필요에 따라 항목을 디스크에 저장하는 데 채널에서 사용하는 폴더입니다. Windows에서는 다른 경로가 명시적으로 지정되지 않은 경우 %LOCALAPPDATA% 또는 %TEMP% 사용됩니다. Windows 이외의 환경에서는 유효한 위치를 지정해야 합니다. 그렇지 않으면 원격 분석이 로컬 디스크에 저장되지 않습니다.
어떤 채널을 사용해야 하나요?
장기 실행 애플리케이션을 포함하는 대부분의 프로덕션 시나리오에 권장 ServerTelemetryChannel
됩니다. 원격 분석을 플러시하는 방법에 대한 자세한 내용은 다음을 참조 Flush()
하세요.
Flush()를 사용하는 경우
메서드는 Flush()
버퍼링된 원격 분석을 즉시 보냅니다. 그러나 특정 시나리오에서만 사용해야 합니다.
사용 Flush()
시기:
- 애플리케이션이 종료하려고 하며 종료하기 전에 원격 분석이 전송되는지 확인하려고 합니다.
- 예외 처리기에 있으며 원격 분석이 전달되도록 보장해야 합니다.
- 백그라운드 작업 또는 신속하게 종료되는 CLI 도구와 같은 수명이 짧은 프로세스를 작성하고 있습니다.
웹 서비스와 같은 장기 실행 애플리케이션에서는 사용하지 Flush()
않습니다. SDK는 버퍼링 및 전송을 자동으로 관리합니다. 불필요하게 호출 Flush()
하면 성능 문제가 발생할 수 있으며, 특히 동기적으로 플러시되지 않는 사용 ServerTelemetryChannel
시 모든 데이터가 전송되도록 보장하지는 않습니다.
원격 분석 모듈
Application Insights는 사용자가 수동으로 추적할 필요 없이 특정 워크로드에 대한 원격 분석 데이터를 자동으로 수집합니다.
다음 자동 수집 모듈은 기본적으로 사용하도록 설정되어 있습니다. 자동 수집 모듈을 사용하지 않도록 설정하거나 해당 기본 동작을 변경하도록 구성할 수 있습니다.
각 원격 분석 모듈은 특정 유형의 데이터를 수집하고 핵심 API를 사용하여 데이터를 보냅니다. 모듈은 다른 NuGet 패키지에 의해 설치되며 .config 파일에 필요한 줄도 추가합니다.
Area | 설명 |
---|---|
요청 추적 | 들어오는 웹 요청에 대한 요청 원격 분석(응답 시간, 결과 코드)을 수집합니다. 모듈: Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule NuGet:Microsoft.ApplicationInsights.Web |
종속성 추적 | 나가는 종속성(HTTP 호출, SQL 호출)에 대한 원격 분석을 수집합니다. IIS에서 작업하려면 Application Insights 에이전트를 설치합니다.
TrackDependency API를 사용하여 사용자 지정 종속성 추적을 작성할 수도 있습니다.
App Service 및 VM/VMSS 모니터링을 사용하여 자동 침입을 지원합니다. 모듈: Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule NuGet:Microsoft.ApplicationInsights.DependencyCollector |
성능 카운터 | Windows 성능 카운터(IIS 설치에서 CPU, 메모리, 네트워크 부하)를 수집합니다. 어떤 카운터(사용자 지정 카운터 포함)를 지정합니다. 자세한 내용은 시스템 성능 카운터 수집을 참조하세요. 모듈: Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule NuGet:Microsoft.ApplicationInsights.PerfCounterCollector |
이벤트 카운터 |
.NET EventCounters를 수집합니다. Windows 성능 카운터 대신 ASP.NET Core 및 플랫폼 간에 권장됩니다. 모듈: EventCounterCollectionModule (SDK ≥ 2.8.0) |
라이브 메트릭(QuickPulse) | 라이브 메트릭 창에 대한 원격 분석을 수집합니다. 모듈: QuickPulseTelemetryModule |
하트비트(App Service) | App Service 환경에 대한 하트비트 및 사용자 지정 메트릭을 보냅니다. 모듈: AppServicesHeartbeatTelemetryModule |
하트비트(VM/VMSS) | Azure VM 환경에 대한 하트비트 및 사용자 지정 메트릭을 보냅니다. 모듈: AzureInstanceMetadataTelemetryModule |
진단 원격 분석 | Application Insights 계측 코드에서 오류를 보고합니다(예: 누락된 카운터, ITelemetryInitializer 예외).
진단 검색에 추적 원격 분석이 나타납니다.모듈: Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule NuGet:Microsoft.ApplicationInsights 메모: 이 패키지만 설치하면 ApplicationInsights.config 파일이 자동으로 만들어지지 않습니다. |
개발자 모드(디버거 연결됨) | 디버거가 연결될 때 즉시 항목을 보내도록 강제 TelemetryChannel 합니다. 대기 시간을 줄이지만 CPU/네트워크 오버헤드가 증가합니다.모듈: Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule NuGet:Application Insights Windows Server |
예외 추적(웹) | 웹앱에서 처리되지 않은 예외를 추적합니다.
오류 및 예외를 참조하세요. 모듈: Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule NuGet:Microsoft.ApplicationInsights.Web |
예외 추적(관찰되지 않음/처리되지 않음) | 작업자 역할, Windows 서비스 및 콘솔 앱에 대한 관찰되지 않은 작업 예외 및 처리되지 않은 예외를 추적합니다. 모듈: • Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule • Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule NuGet:Microsoft.ApplicationInsights.WindowsServer |
EventSource 추적 | 구성된 EventSource 이벤트를 Application Insights에 추적으로 보냅니다. 모듈: Microsoft.ApplicationInsights.EventSourceListener.EventSourceTelemetryModule NuGet:Microsoft.ApplicationInsights.EventSourceListener |
ETW 수집기 | 구성된 ETW 공급자 이벤트를 Application Insights에 추적으로 보냅니다. 모듈: Microsoft.ApplicationInsights.EtwCollector.EtwCollectorTelemetryModule NuGet:Microsoft.ApplicationInsights.EtwCollector |
코어 API(모듈 아님) | 다른 원격 분석 구성 요소 및 사용자 지정 원격 분석에 사용되는 핵심 API입니다. 모듈: Microsoft.ApplicationInsights package NuGet:Microsoft.ApplicationInsights 메모: 이 패키지만 설치하면 ApplicationInsights.config 파일이 자동으로 만들어지지 않습니다. |
원격 분석 모듈 구성
TelemetryModules
ApplicationInsights.config 섹션을 사용하여 모듈을 구성, 추가 또는 제거합니다. 다음 예제는 다음과 같습니다.
- 구성
DependencyTrackingTelemetryModule
(W3C 헤더 삽입 사용). - 구성
EventCounterCollectionModule
(기본값 지우기 및 단일 카운터 추가). - 를 제거
PerformanceCollectorModule
하여 perf-counter 컬렉션을 사용하지 않도록 설정합니다.
<ApplicationInsights>
<TelemetryModules>
<!-- Dependency tracking -->
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
<!-- Match Core example: enable W3C header injection -->
<EnableW3CHeadersInjection>true</EnableW3CHeadersInjection>
</Add>
<!-- EventCounterCollectionModule: add a single counter (if you use event counters) -->
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.EventCounterCollectionModule, Microsoft.AI.PerfCounterCollector">
<Counters>
<!-- Mirrors Core example: only collect 'gen-0-size' from System.Runtime -->
<Add ProviderName="System.Runtime" CounterName="gen-0-size" />
</Counters>
</Add>
<!-- PerformanceCollectorModule (classic Windows performance counters).
To DISABLE perf-counter collection, do NOT include this module.
If it already exists in your file, remove or comment it out.
Example of the line you would remove:
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector" />
-->
</TelemetryModules>
</ApplicationInsights>
참고
현재 ApplicationInsights.config
모듈의 정확한 집합은 설치한 SDK 패키지에 따라 달라집니다.
원격 분석 사용 안 함
구성 파일에는 각 모듈에 대한 노드가 있습니다. 모듈을 사용하지 않도록 설정하려면 노드를 삭제하거나 주석 처리합니다.
원격 분석 이니셜라이저
추가 정보로 원격 분석을 보강하거나 표준 원격 분석 모듈에서 설정한 원격 분석 속성을 재정의하려면 원격 분석 이니셜라이저를 사용합니다.
원격 분석 이니셜라이저는 원격 분석의 모든 항목과 함께 전송되는 컨텍스트 속성을 설정합니다.
고유한 이니셜라이저를 작성하여 컨텍스트 속성을 설정할 수 있습니다.
표준 이니셜라이저는 모두 웹 또는 WindowsServer NuGet 패키지에 의해 설정됩니다.
이니셜라이저 | 설명 |
---|---|
AccountIdTelemetryInitializer |
AccountId 속성을 설정합니다. |
AuthenticatedUserIdTelemetryInitializer |
AuthenticatedUserId JavaScript SDK에서 설정한 대로 속성을 설정합니다. |
AzureRoleEnvironmentTelemetryInitializer |
RoleName
RoleInstance Azure 런타임 환경에서 추출된 정보를 사용하여 모든 원격 분석 항목에 대한 컨텍스트 및 속성을 Device 업데이트합니다. |
BuildInfoConfigComponentVersionTelemetryInitializer |
Version MS Build에서 Component 생성된 파일에서 추출된 값으로 모든 원격 분석 항목에 대한 컨텍스트의 BuildInfo.config 속성을 업데이트합니다. |
ClientIpHeaderTelemetryInitializer |
Ip 요청의 HTTP 헤더를 Location 기반으로 X-Forwarded-For 모든 원격 분석 항목의 컨텍스트 속성을 업데이트합니다. |
DeviceTelemetryInitializer |
모든 원격 분석 항목에 대한 컨텍스트의 Device 다음 속성을 업데이트합니다.• Type 로 설정됩니다 PC .• Id 웹 애플리케이션이 실행 중인 컴퓨터의 도메인 이름으로 설정됩니다.• OemName WMI를 사용하여 필드에서 추출된 Win32_ComputerSystem.Manufacturer 값으로 설정됩니다.• Model WMI를 사용하여 필드에서 추출된 Win32_ComputerSystem.Model 값으로 설정됩니다.• NetworkType 속성에서 추출된 값으로 설정됩니다 NetworkInterface .• Language 속성의 이름으로 설정됩니다 CurrentCulture . |
DomainNameRoleInstanceTelemetryInitializer |
웹 애플리케이션이 RoleInstance Device 실행 중인 컴퓨터의 도메인 이름으로 모든 원격 분석 항목에 대한 컨텍스트의 속성을 업데이트합니다. |
OperationNameTelemetryInitializer |
Name
RequestTelemetry HTTP 메서드를 기반으로 하는 모든 원격 분석 항목의 Name 컨텍스트 속성과 Operation 요청을 처리하기 위해 호출된 ASP.NET MVC 컨트롤러 및 작업의 이름을 업데이트합니다. |
OperationIdTelemetryInitializer 또는 OperationCorrelationTelemetryInitializer |
Operation.Id 자동으로 생성된 RequestTelemetry.Id 요청을 처리하는 동안 추적된 모든 원격 분석 항목의 컨텍스트 속성을 업데이트합니다. |
SessionTelemetryInitializer |
Id 사용자의 브라우저에서 실행되는 JavaScript 계측 코드에서 생성된 쿠키에서 Session 추출된 ai_session 값으로 모든 원격 분석 항목에 대한 컨텍스트의 속성을 ApplicationInsights 업데이트합니다. |
SyntheticTelemetryInitializer 또는 SyntheticUserAgentTelemetryInitializer |
User
Session 가용성 테스트 또는 검색 엔진 봇과 Operation 같은 가상 원본의 요청을 처리할 때 추적되는 모든 원격 분석 항목의 컨텍스트 속성을 업데이트합니다. 기본적으로 메트릭 탐색기는 가상 원격 분석을 표시하지 않습니다.<Filters> 요청의 속성을 식별하는 집합입니다. |
UserTelemetryInitializer |
Id
AcquisitionDate 사용자의 브라우저에서 실행되는 Application Insights JavaScript 계측 코드에서 생성된 쿠키에서 User 추출된 값으로 모든 원격 분석 항목에 대한 컨텍스트 및 속성을 ai_user 업데이트합니다. |
WebTestTelemetryInitializer |
가용성 테스트에서 가져온 HTTP 요청에 대한 사용자 ID, 세션 ID 및 가상 원본 속성을 설정합니다.<Filters> 요청의 속성을 식별하는 집합입니다. |
참고
Azure Service Fabric에서 실행되는 .NET 애플리케이션의 경우 NuGet 패키지를 포함할 Microsoft.ApplicationInsights.ServiceFabric
수 있습니다. 이 패키지에는 원격 분석 항목에 FabricTelemetryInitializer
Service Fabric 속성을 추가하는 속성이 포함되어 있습니다. 자세한 내용은 이 NuGet 패키지에 의해 추가된 속성에 대한 GitHub 페이지를 참조하세요.
ASP.NET 애플리케이션에서 원격 분석 이니셜라이저를 사용하는 방법을 알아보려면 Application Insights SDK에서 원격 분석 필터링 및 전처리를 참조하세요.
원격 분석 프로세서
원격 분석 프로세서는 SDK에서 포털로 전송되기 전에 각 원격 분석 항목을 필터링하고 수정할 수 있습니다.
ASP.NET 애플리케이션에서 원격 분석 프로세서를 사용하는 방법을 알아보려면 Application Insights SDK에서 원격 분석 필터링 및 전처리를 참조하세요.
사용자 고유의 원격 분석 프로세서를 작성할 수 있습니다.
적응 샘플링 원격 분석 프로세서(2.0.0-beta3부터)
이 기능은 기본적으로 사용하도록 설정됩니다. 앱이 상당한 원격 분석을 보내는 경우 이 프로세서는 일부 원격 분석을 제거합니다.
<TelemetryProcessors>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
<MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
</Add>
</TelemetryProcessors>
매개 변수는 알고리즘이 달성하려고 하는 대상을 제공합니다. SDK의 각 인스턴스는 독립적으로 작동합니다. 따라서 서버가 여러 컴퓨터의 클러스터인 경우 그에 따라 실제 원격 분석 볼륨을 곱합니다.
샘플링에 대해 자세히 알아봅니 다.
고정 속도 샘플링 원격 분석 프로세서(2.0.0-beta1부터)
표준 샘플링 원격 분석 프로세서 (2.0.1부터)도 있습니다.
<TelemetryProcessors>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.SamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
<!-- Set a percentage close to 100/N where N is an integer. -->
<!-- E.g. 50 (=100/2), 33.33 (=100/3), 25 (=100/4), 20, 1 (=100/100), 0.1 (=100/1000) -->
<SamplingPercentage>10</SamplingPercentage>
</Add>
</TelemetryProcessors>
연결 문자열
이 설정은 데이터가 표시되는 Application Insights 리소스를 결정합니다. 일반적으로 각 애플리케이션에 대해 별도의 연결 문자열을 사용하여 별도의 리소스를 만듭니다.
코드 샘플 은 Application Insights의 연결 문자열 을 참조하세요.
예를 들어 애플리케이션의 결과를 다른 리소스로 전송하기 위해 연결 문자열을 동적으로 설정하려면 구성 파일에서 연결 문자열을 생략하고 대신 코드로 설정할 수 있습니다.
표준 원격 분석 모듈을 포함하여 모든 인스턴스에 TelemetryClient
대한 연결 문자열을 설정하려면 ASP.NET 서비스의 global.aspx.cs 같은 초기화 메서드에서 이 단계를 수행합니다.
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights;
protected void Application_Start()
{
TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
configuration.ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000";
var telemetryClient = new TelemetryClient(configuration);
특정 이벤트 집합을 다른 리소스로 보내려면 특정 원격 분석 클라이언트에 대한 키를 설정할 수 있습니다.
var tc = new TelemetryClient();
tc.Context.ConnectionString = "InstrumentationKey=00000000-0000-0000-0000-000000000000";
tc.TrackEvent("myEvent");
// ...
새 연결 문자열을 얻으려면 Application Insights 포털에서 새 리소스를 만듭니다.
ApplicationId 공급자
참고
ASP.NET 경우 이 공급자는 SDK v2.6.0*부터 사용할 수 있습니다.
이 공급자의 목적은 연결 문자열을 기반으로 애플리케이션 ID를 조회하는 것입니다. 애플리케이션 ID가 포함되어 있으며 RequestTelemetry
포털에서 DependencyTelemetry
상관 관계를 확인하는 데 사용됩니다.
이 기능은 설정 TelemetryConfiguration.ApplicationIdProvider
하여 사용할 수 있습니다.
인터페이스: IApplicationIdProvider
public interface IApplicationIdProvider
{
bool TryGetApplicationId(string instrumentationKey, out string applicationId);
}
Microsoft.ApplicationInsights SDK ApplicationInsightsApplicationIdProvider
DictionaryApplicationIdProvider
에서 두 가지 구현을 제공합니다.
ApplicationInsightsApplicationIdProvider
이 래퍼는 프로필 API용입니다. 요청을 제한하고 결과를 캐시합니다. 이 공급자는 Microsoft.ApplicationInsights.DependencyCollector 또는 Microsoft.ApplicationInsights.Web을 설치할 때 자동으로 포함됩니다.
클래스는 라는 ProfileQueryEndpoint
선택적 속성을 노출 합니다. 기본적으로 .로 설정됩니다 https://dc.services.visualstudio.com/api/profiles/{0}/appId
.
프록시를 구성해야 하는 경우 기본 주소를 프록시하고 경로에 포함 /api/profiles/{0}/appId
되도록 하는 것이 좋습니다. 런타임 시 {0}
각 요청에 대한 계측 키로 바뀝니다.
ApplicationInsights.config통한 예제 구성
<ApplicationInsights>
...
<ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights">
<ProfileQueryEndpoint>https://dc.services.visualstudio.com/api/profiles/{0}/appId</ProfileQueryEndpoint>
</ApplicationIdProvider>
...
</ApplicationInsights>
코드를 통한 예제 구성
TelemetryConfiguration.Active.ApplicationIdProvider = new ApplicationInsightsApplicationIdProvider();
DictionaryApplicationIdProvider
이 정적 공급자는 구성된 계측 키/애플리케이션 ID 쌍을 사용합니다.
이 클래스에는 Defined
계측 키/애플리케이션 ID 쌍의 속성 Dictionary<string,string>
이 있습니다.
이 클래스에는 선택적 속성 Next
이 있으며, 구성에 없는 연결 문자열이 요청될 때 사용할 다른 공급자를 구성하는 데 사용할 수 있습니다.
ApplicationInsights.config통한 예제 구성
<ApplicationInsights>
...
<ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.DictionaryApplicationIdProvider, Microsoft.ApplicationInsights">
<Defined>
<Type key="InstrumentationKey_1" value="ApplicationId_1"/>
<Type key="InstrumentationKey_2" value="ApplicationId_2"/>
</Defined>
<Next Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights" />
</ApplicationIdProvider>
...
</ApplicationInsights>
코드를 통한 예제 구성
TelemetryConfiguration.Active.ApplicationIdProvider = new DictionaryApplicationIdProvider{
Defined = new Dictionary<string, string>
{
{"InstrumentationKey_1", "ApplicationId_1"},
{"InstrumentationKey_2", "ApplicationId_2"}
}
};
스냅샷 컬렉션 구성
ASP.NET 및 ASP.NET Core 애플리케이션에 대한 스냅샷 컬렉션을 구성하는 방법을 알아보려면 Azure Service Fabric, Cloud Services 및 Virtual Machines에서 .NET 앱에 대한 스냅샷 디버거 사용을 참조하세요.
샘플링
ASP.NET 및 ASP.NET Core 애플리케이션에 대한 샘플링을 구성하는 방법을 알아보려면 Application Insights의 샘플링을 참조하세요.
HTTP를 통해 데이터 보강
var requestTelemetry = HttpContext.Current?.Items["Microsoft.ApplicationInsights.RequestTelemetry"] as RequestTelemetry;
if (requestTelemetry != null)
{
requestTelemetry.Properties["myProp"] = "someData";
}
클라이언트쪽 모니터링을 추가 합니다.
이전 섹션에서는 서버 쪽 모니터링을 자동 및 수동으로 구성하는 방법에 대한 지침을 제공했습니다. 클라이언트 쪽 모니터링을 추가하려면 클라이언트 쪽 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 개선 사항도 요약되어 있습니다.
다음 단계
- FAQ(질문과 대답)를 검토하려면 ASP.NET FAQ용 Applications Insights 및 ASP.NET Core FAQ용 Application Insights를 참조하세요.
- 지원되는 버전의 Application Insights SDK를 실행하고 있는지 확인합니다.
- Application Insights 형식 및 데이터 모델에 대한 데이터 모델을 참조하세요.
- 가상 트랜잭션을 추가하여 가용성 모니터링을 통해 전 세계에서 웹 사이트를 사용할 수 있는지 테스트합니다.
- Application Insights에서 원격 분석 상관 관계의 기본 사항에 대해 알아봅니다.
- System.Diagnostics.Activity 사용자 가이드를 확인하여 원격 분석의 상관 관계를 확인합니다.
- 예외가 throw되는 시점의 소스 코드 및 변수 상태를 확인할 수 있도록 스냅샷 컬렉션을 구성합니다.
- 앱의 성능 및 사용량을 자세히 확인할 수 있도록 API를 사용하여 사용자 고유의 이벤트 및 메트릭을 보냅니다.